180 return MediaWikiServices::getInstance()->getTitleFormatter();
192 return MediaWikiServices::getInstance()->getInterwikiLookup();
211 $t->mDbkeyform = $key;
214 $t->secureAndSplit();
229 return self::newFromLinkTarget( $titleValue );
240 if ( $linkTarget instanceof
Title ) {
244 return self::makeTitle(
267 if ( $text !==
null && !is_string( $text ) && !is_int( $text ) ) {
268 throw new InvalidArgumentException(
'$text must be a string.' );
270 if ( $text ===
null ) {
296 if ( is_object( $text ) ) {
297 throw new MWException(
'$text must be a string, given an object' );
306 if ( $defaultNamespace ==
NS_MAIN ) {
314 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
317 $t->mDbkeyform = strtr( $filteredText,
' ',
'_' );
318 $t->mDefaultNamespace = intval( $defaultNamespace );
320 $t->secureAndSplit();
321 if ( $defaultNamespace ==
NS_MAIN ) {
345 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
346 # but some URLs used it as a space replacement and they still come
347 # from some external search tools.
348 if ( strpos( self::legalChars(),
'+' ) ===
false ) {
349 $url = strtr( $url,
'+',
' ' );
352 $t->mDbkeyform = strtr( $url,
' ',
'_' );
355 $t->secureAndSplit();
366 if ( self::$titleCache ==
null ) {
367 self::$titleCache =
new HashBagOStuff( [
'maxKeys' => self::CACHE_MAX ] );
369 return self::$titleCache;
383 'page_namespace',
'page_title',
'page_id',
384 'page_len',
'page_is_redirect',
'page_latest',
388 $fields[] =
'page_content_model';
392 $fields[] =
'page_lang';
407 $row = $db->selectRow(
409 self::getSelectFields(),
410 [
'page_id' => $id ],
413 if ( $row !==
false ) {
428 if ( !count( $ids ) ) {
435 self::getSelectFields(),
436 [
'page_id' => $ids ],
441 foreach (
$res as $row ) {
454 $t = self::makeTitle( $row->page_namespace, $row->page_title );
455 $t->loadFromRow( $row );
467 if ( isset( $row->page_id ) ) {
468 $this->mArticleID = (int)$row->page_id;
470 if ( isset( $row->page_len ) ) {
471 $this->mLength = (int)$row->page_len;
473 if ( isset( $row->page_is_redirect ) ) {
474 $this->mRedirect = (bool)$row->page_is_redirect;
476 if ( isset( $row->page_latest ) ) {
477 $this->mLatestID = (int)$row->page_latest;
479 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
480 $this->mContentModel = strval( $row->page_content_model );
481 } elseif ( !$this->mForcedContentModel ) {
484 if ( isset( $row->page_lang ) ) {
485 $this->mDbPageLanguage = (
string)$row->page_lang;
487 if ( isset( $row->page_restrictions ) ) {
488 $this->mOldRestrictions = $row->page_restrictions;
491 $this->mArticleID = 0;
493 $this->mRedirect =
false;
494 $this->mLatestID = 0;
495 if ( !$this->mForcedContentModel ) {
514 public static function makeTitle( $ns, $title, $fragment =
'', $interwiki =
'' ) {
516 $t->mInterwiki = $interwiki;
517 $t->mFragment = $fragment;
518 $t->mNamespace = $ns = intval( $ns );
519 $t->mDbkeyform = strtr(
$title,
' ',
'_' );
520 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
522 $t->mTextform = strtr(
$title,
'_',
' ' );
538 public static function makeTitleSafe( $ns, $title, $fragment =
'', $interwiki =
'' ) {
539 if ( !MWNamespace::exists( $ns ) ) {
547 $t->secureAndSplit();
579 [
'page_namespace',
'page_title' ],
580 [
'page_id' => $id ],
583 if (
$s ===
false ) {
587 $n = self::makeName(
$s->page_namespace,
$s->page_title );
625 $length = strlen( $byteClass );
627 $x0 = $x1 = $x2 =
'';
629 $d0 = $d1 = $d2 =
'';
631 $ord0 = $ord1 = $ord2 = 0;
633 $r0 = $r1 = $r2 =
'';
637 $allowUnicode =
false;
638 for ( $pos = 0; $pos < $length; $pos++ ) {
649 $inChar = $byteClass[$pos];
650 if ( $inChar ==
'\\' ) {
651 if ( preg_match(
'/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
652 $x0 = $inChar . $m[0];
653 $d0 = chr( hexdec( $m[1] ) );
654 $pos += strlen( $m[0] );
655 } elseif ( preg_match(
'/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
656 $x0 = $inChar . $m[0];
657 $d0 = chr( octdec( $m[0] ) );
658 $pos += strlen( $m[0] );
659 } elseif ( $pos + 1 >= $length ) {
662 $d0 = $byteClass[$pos + 1];
671 if ( $ord0 < 32 || $ord0 == 0x7f ) {
672 $r0 = sprintf(
'\x%02x', $ord0 );
673 } elseif ( $ord0 >= 0x80 ) {
675 $r0 = sprintf(
'\x%02x', $ord0 );
676 $allowUnicode =
true;
677 } elseif ( strpos(
'-\\[]^', $d0 ) !==
false ) {
683 if ( $x0 !==
'' && $x1 ===
'-' && $x2 !==
'' ) {
685 if ( $ord2 > $ord0 ) {
687 } elseif ( $ord0 >= 0x80 ) {
689 $allowUnicode =
true;
690 if ( $ord2 < 0x80 ) {
699 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 =
'';
700 } elseif ( $ord2 < 0x80 ) {
705 if ( $ord1 < 0x80 ) {
708 if ( $ord0 < 0x80 ) {
711 if ( $allowUnicode ) {
712 $out .=
'\u0080-\uFFFF';
728 public static function makeName( $ns, $title, $fragment =
'', $interwiki =
'',
729 $canonicalNamespace =
false
733 if ( $canonicalNamespace ) {
734 $namespace = MWNamespace::getCanonicalName( $ns );
738 $name = $namespace ==
'' ?
$title :
"$namespace:$title";
739 if ( strval( $interwiki ) !=
'' ) {
740 $name =
"$interwiki:$name";
742 if ( strval( $fragment ) !=
'' ) {
743 $name .=
'#' . $fragment;
755 # Note that we don't urlencode the fragment. urlencoded Unicode
756 # fragments appear not to work in IE (at least up to 7) or in at least
757 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
758 # to care if they aren't encoded.
759 return Sanitizer::escapeId( $fragment,
'noninitial' );
787 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
789 return $iw->isLocal();
801 return $this->mInterwiki !==
'';
812 return $this->mInterwiki;
821 return $this->mLocalInterwiki;
835 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
848 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
861 if ( $this->mTitleValue ===
null ) {
869 }
catch ( InvalidArgumentException $ex ) {
870 wfDebug( __METHOD__ .
': Can\'t create a TitleValue for [[' .
875 return $this->mTitleValue;
884 return $this->mTextform;
893 return $this->mUrlform;
902 return $this->mDbkeyform;
911 if ( !is_null( $this->mUserCaseDBKey ) ) {
912 return $this->mUserCaseDBKey;
915 return $this->mDbkeyform;
925 return $this->mNamespace;
935 if ( !$this->mForcedContentModel
939 $linkCache = LinkCache::singleton();
940 $linkCache->addLinkObj( $this ); #
in case we already had an
article ID
941 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this,
'model' );
944 if ( !$this->mContentModel ) {
948 return $this->mContentModel;
973 $this->mContentModel = $model;
974 $this->mForcedContentModel =
true;
988 if ( MWNamespace::exists( $this->mNamespace ) ) {
989 return MWNamespace::getCanonicalName( $this->mNamespace );
994 $formatter = self::getTitleFormatter();
995 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
996 }
catch ( InvalidArgumentException $ex ) {
997 wfDebug( __METHOD__ .
': ' . $ex->getMessage() .
"\n" );
1009 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1019 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1028 return MWNamespace::canTalk( $this->mNamespace );
1037 return $this->mNamespace >=
NS_MAIN;
1067 if (
$name == $thisName ) {
1083 if ( $canonicalName ) {
1085 if ( $localName != $this->mDbkeyform ) {
1104 return MWNamespace::equals( $this->
getNamespace(), $ns );
1143 return MWNamespace::subjectEquals( $this->
getNamespace(), $ns );
1154 return MWNamespace::isContent( $this->
getNamespace() );
1170 Hooks::run(
'TitleIsMovable', [ $this, &
$result ] );
1194 return MWNamespace::hasSubpages( $this->mNamespace )
1208 strpos( $this->
getText(),
'Conversiontable/' ) === 0;
1239 return $isCssOrJsPage;
1259 $subpage = explode(
'/', $this->mTextform );
1260 $subpage = $subpage[count( $subpage ) - 1];
1261 $lastdot = strrpos( $subpage,
'.' );
1262 if ( $lastdot ===
false ) {
1263 return $subpage; # Never happens: only called
for names ending
in '.css' or '.js'
1265 return substr( $subpage, 0, $lastdot );
1314 $subjectNS = MWNamespace::getSubject( $this->
getNamespace() );
1331 throw new MWException(
'Special pages cannot have other pages' );
1346 return $this->mDefaultNamespace;
1357 return $this->mFragment;
1367 return $this->mFragment !==
'';
1395 $this->mFragment = strtr( substr( $fragment, 1 ),
'_',
' ' );
1406 return self::makeTitle(
1424 $p = $this->mInterwiki .
':';
1427 if ( 0 != $this->mNamespace ) {
1440 $s = $this->
prefix( $this->mDbkeyform );
1441 $s = strtr(
$s,
' ',
'_' );
1452 if ( $this->mPrefixedText ===
null ) {
1453 $s = $this->
prefix( $this->mTextform );
1454 $s = strtr(
$s,
'_',
' ' );
1455 $this->mPrefixedText =
$s;
1457 return $this->mPrefixedText;
1496 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1500 return strtok( $this->
getText(),
'/' );
1531 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1535 $parts = explode(
'/', $this->
getText() );
1536 # Don't discard the real title if there's no subpage involved
1537 if ( count( $parts ) > 1 ) {
1538 unset( $parts[count( $parts ) - 1] );
1540 return implode(
'/', $parts );
1571 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1572 return $this->mTextform;
1574 $parts = explode(
'/', $this->mTextform );
1575 return $parts[count( $parts ) - 1];
1612 $s = $this->
prefix( $this->mDbkeyform );
1631 if ( $query2 !==
false ) {
1632 wfDeprecated(
"Title::get{Canonical,Full,Link,Local,Internal}URL " .
1633 "method called with a second parameter is deprecated. Add your " .
1634 "parameter to an array passed as the first parameter.",
"1.19" );
1636 if ( is_array(
$query ) ) {
1640 if ( is_string( $query2 ) ) {
1671 # Hand off all the decisions on urls to getLocalURL
1674 # Expand the url to make it a full url. Note that getLocalURL has the
1675 # potential to output full urls for a variety of reasons, so we use
1676 # wfExpandUrl instead of simply prepending $wgServer
1679 # Finally, add the fragment.
1683 Hooks::run(
'GetFullURL', [ &$titleRef, &$url,
$query ] );
1708 $this->getPrefixedDBKey()
1711 return $target->getFullUrl(
$query,
false, $proto );
1742 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1745 if ( $namespace !=
'' ) {
1746 # Can this actually happen? Interwikis shouldn't be parsed.
1747 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1750 $url = $interwiki->getURL( $namespace . $this->
getDBkey() );
1758 Hooks::run(
'GetLocalURL::Article', [ &$titleRef, &$url ] );
1765 && preg_match(
'/^(.*&|)action=([^&]*)(&(.*)|)$/',
$query,
$matches )
1767 $action = urldecode(
$matches[2] );
1786 $variant = urldecode(
$matches[1] );
1791 $url = str_replace(
'$1', $dbkey, $url );
1795 if ( $url ===
false ) {
1799 $url =
"{$wgScript}?title={$dbkey}&{$query}";
1804 Hooks::run(
'GetLocalURL::Internal', [ &$titleRef, &$url,
$query ] );
1808 if (
$wgRequest->getVal(
'action' ) ==
'render' ) {
1814 Hooks::run(
'GetLocalURL', [ &$titleRef, &$url,
$query ] );
1836 if ( $this->
isExternal() || $proto !==
false ) {
1865 Hooks::run(
'GetInternalURL', [ &$titleRef, &$url,
$query ] );
1885 Hooks::run(
'GetCanonicalURL', [ &$titleRef, &$url,
$query ] );
1930 public function userCan( $action, $user =
null, $rigor =
'secure' ) {
1955 $action, $user, $rigor =
'secure', $ignoreErrors = []
1960 foreach ( $errors
as $index => $error ) {
1961 $errKey = is_array( $error ) ? $error[0] : $error;
1963 if ( in_array( $errKey, $ignoreErrors ) ) {
1964 unset( $errors[$index] );
1966 if ( $errKey instanceof
MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
1967 unset( $errors[$index] );
1986 if ( !Hooks::run(
'TitleQuickPermissions',
1987 [ $this,
$user, $action, &$errors, ( $rigor !==
'quick' ), $short ] )
1992 if ( $action ==
'create' ) {
1995 ( !$this->isTalkPage() && !
$user->isAllowed(
'createpage' ) )
1997 $errors[] =
$user->isAnon() ? [
'nocreatetext' ] : [
'nocreate-loggedin' ];
1999 } elseif ( $action ==
'move' ) {
2000 if ( !
$user->isAllowed(
'move-rootuserpages' )
2001 && $this->mNamespace ==
NS_USER && !$this->isSubpage() ) {
2003 $errors[] = [
'cant-move-user-page' ];
2007 if ( $this->mNamespace ==
NS_FILE && !
$user->isAllowed(
'movefile' ) ) {
2008 $errors[] = [
'movenotallowedfile' ];
2012 if ( $this->mNamespace ==
NS_CATEGORY && !
$user->isAllowed(
'move-categorypages' ) ) {
2013 $errors[] = [
'cant-move-category-page' ];
2016 if ( !
$user->isAllowed(
'move' ) ) {
2018 $userCanMove = User::groupHasPermission(
'user',
'move' );
2019 $autoconfirmedCanMove = User::groupHasPermission(
'autoconfirmed',
'move' );
2020 if (
$user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2022 $errors[] = [
'movenologintext' ];
2024 $errors[] = [
'movenotallowed' ];
2027 } elseif ( $action ==
'move-target' ) {
2028 if ( !
$user->isAllowed(
'move' ) ) {
2030 $errors[] = [
'movenotallowed' ];
2031 } elseif ( !
$user->isAllowed(
'move-rootuserpages' )
2032 && $this->mNamespace ==
NS_USER && !$this->isSubpage() ) {
2034 $errors[] = [
'cant-move-to-user-page' ];
2035 } elseif ( !
$user->isAllowed(
'move-categorypages' )
2038 $errors[] = [
'cant-move-to-category-page' ];
2040 } elseif ( !
$user->isAllowed( $action ) ) {
2061 $errors = array_merge( $errors,
$result );
2068 } elseif (
$result ===
false ) {
2070 $errors[] = [
'badaccess-group0' ];
2091 if ( !Hooks::run(
'userCan', [ &$titleRef, &
$user, $action, &
$result ] ) ) {
2092 return $result ? [] : [ [
'badaccess-group0' ] ];
2097 if ( !Hooks::run(
'getUserPermissionsErrors', [ &$titleRef, &
$user, $action, &
$result ] ) ) {
2103 && !( $short && count( $errors ) > 0 )
2104 && !Hooks::run(
'getUserPermissionsErrorsExpensive', [ &$titleRef, &
$user, $action, &
$result ] )
2124 # Only 'createaccount' can be performed on special pages,
2125 # which don't actually exist in the DB.
2126 if (
NS_SPECIAL == $this->mNamespace && $action !==
'createaccount' ) {
2127 $errors[] = [
'ns-specialprotected' ];
2130 # Check $wgNamespaceProtection for restricted namespaces
2132 $ns = $this->mNamespace ==
NS_MAIN ?
2135 [
'protectedinterface', $action ] : [
'namespaceprotected', $ns, $action ];
2153 # Protect css/js subpages of user pages
2154 # XXX: this might be better using restrictions
2155 if ( $action !=
'patrol' ) {
2156 if ( preg_match(
'/^' . preg_quote(
$user->getName(),
'/' ) .
'\//', $this->mTextform ) ) {
2157 if ( $this->
isCssSubpage() && !
$user->isAllowedAny(
'editmyusercss',
'editusercss' ) ) {
2158 $errors[] = [
'mycustomcssprotected', $action ];
2159 } elseif ( $this->
isJsSubpage() && !
$user->isAllowedAny(
'editmyuserjs',
'edituserjs' ) ) {
2160 $errors[] = [
'mycustomjsprotected', $action ];
2164 $errors[] = [
'customcssprotected', $action ];
2166 $errors[] = [
'customjsprotected', $action ];
2190 if ( $right ==
'sysop' ) {
2191 $right =
'editprotected';
2194 if ( $right ==
'autoconfirmed' ) {
2195 $right =
'editsemiprotected';
2197 if ( $right ==
'' ) {
2200 if ( !
$user->isAllowed( $right ) ) {
2201 $errors[] = [
'protectedpagetext', $right, $action ];
2202 } elseif ( $this->mCascadeRestriction && !
$user->isAllowed(
'protect' ) ) {
2203 $errors[] = [
'protectedpagetext',
'protect', $action ];
2223 # We /could/ use the protection level on the source page, but it's
2224 # fairly ugly as we have to establish a precedence hierarchy for pages
2225 # included by multiple cascade-protected pages. So just restrict
2226 # it to people with 'protect' permission, as they could remove the
2227 # protection anyway.
2229 # Cascading protection depends on more than this page...
2230 # Several cascading protected pages may include this page...
2231 # Check each cascading level
2232 # This is only for protection restrictions, not for all actions
2233 if ( isset( $restrictions[$action] ) ) {
2234 foreach ( $restrictions[$action]
as $right ) {
2236 if ( $right ==
'sysop' ) {
2237 $right =
'editprotected';
2240 if ( $right ==
'autoconfirmed' ) {
2241 $right =
'editsemiprotected';
2243 if ( $right !=
'' && !
$user->isAllowedAll(
'protect', $right ) ) {
2245 foreach ( $cascadingSources
as $page ) {
2246 $pages .=
'* [[:' .
$page->getPrefixedText() .
"]]\n";
2248 $errors[] = [
'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2271 if ( $action ==
'protect' ) {
2274 $errors[] = [
'protect-cantedit' ];
2276 } elseif ( $action ==
'create' ) {
2278 if ( $title_protection ) {
2279 if ( $title_protection[
'permission'] ==
''
2280 || !
$user->isAllowed( $title_protection[
'permission'] )
2284 User::whoIs( $title_protection[
'user'] ),
2285 $title_protection[
'reason']
2289 } elseif ( $action ==
'move' ) {
2291 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2293 $errors[] = [
'immobile-source-namespace', $this->
getNsText() ];
2296 $errors[] = [
'immobile-source-page' ];
2298 } elseif ( $action ==
'move-target' ) {
2299 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2300 $errors[] = [
'immobile-target-namespace', $this->
getNsText() ];
2302 $errors[] = [
'immobile-target-page' ];
2304 } elseif ( $action ==
'delete' ) {
2306 if ( !$tempErrors ) {
2308 $user, $tempErrors, $rigor,
true );
2310 if ( $tempErrors ) {
2312 $errors[] = [
'deleteprotected' ];
2319 } elseif ( $action ===
'undelete' ) {
2322 $errors[] = [
'undelete-cantedit' ];
2328 $errors[] = [
'undelete-cantcreate' ];
2349 if ( $rigor ===
'quick' || in_array( $action, [
'createaccount',
'unblock' ] ) ) {
2359 && !
$user->isEmailConfirmed()
2360 && $action ===
'edit'
2362 $errors[] = [
'confirmedittext' ];
2365 $useSlave = ( $rigor !==
'secure' );
2366 if ( ( $action ==
'edit' || $action ==
'create' )
2367 && !
$user->isBlockedFrom( $this, $useSlave )
2371 } elseif (
$user->isBlocked() &&
$user->getBlock()->prevents( $action ) !==
false ) {
2393 $whitelisted =
false;
2394 if ( User::isEveryoneAllowed(
'read' ) ) {
2395 # Shortcut for public wikis, allows skipping quite a bit of code
2396 $whitelisted =
true;
2397 } elseif (
$user->isAllowed(
'read' ) ) {
2398 # If the user is allowed to read pages, he is allowed to read all pages
2399 $whitelisted =
true;
2400 } elseif ( $this->
isSpecial(
'Userlogin' )
2404 # Always grant access to the login page.
2405 # Even anons need to be able to log in.
2406 $whitelisted =
true;
2408 # Time to check the whitelist
2409 # Only do these checks is there's something to check against
2415 $whitelisted =
true;
2417 # Old settings might have the title prefixed with
2418 # a colon for main-namespace pages
2420 $whitelisted =
true;
2423 # If it's a special page, ditch the subpage bit and check again
2429 $whitelisted =
true;
2439 if ( preg_match( $listItem,
$name ) ) {
2440 $whitelisted =
true;
2446 if ( !$whitelisted ) {
2447 # If the title is not whitelisted, give extensions a chance to do so...
2448 Hooks::run(
'TitleReadWhitelist', [ $this,
$user, &$whitelisted ] );
2449 if ( !$whitelisted ) {
2468 return [
'badaccess-group0' ];
2471 return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2489 $action, $user, $rigor =
'secure', $short =
false
2491 if ( $rigor ===
true ) {
2493 } elseif ( $rigor ===
false ) {
2495 } elseif ( !in_array( $rigor, [
'quick',
'full',
'secure' ] ) ) {
2496 throw new Exception(
"Invalid rigor parameter '$rigor'." );
2499 # Read has special handling
2500 if ( $action ==
'read' ) {
2502 'checkPermissionHooks',
2503 'checkReadPermissions',
2506 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2507 # here as it will lead to duplicate error messages. This is okay to do
2508 # since anywhere that checks for create will also check for edit, and
2509 # those checks are called for edit.
2510 } elseif ( $action ==
'create' ) {
2512 'checkQuickPermissions',
2513 'checkPermissionHooks',
2514 'checkPageRestrictions',
2515 'checkCascadingSourcesRestrictions',
2516 'checkActionPermissions',
2521 'checkQuickPermissions',
2522 'checkPermissionHooks',
2523 'checkSpecialsAndNSPermissions',
2524 'checkCSSandJSPermissions',
2525 'checkPageRestrictions',
2526 'checkCascadingSourcesRestrictions',
2527 'checkActionPermissions',
2533 while ( count( $checks ) > 0 &&
2534 !( $short && count( $errors ) > 0 ) ) {
2535 $method = array_shift( $checks );
2536 $errors = $this->$method( $action,
$user, $errors, $rigor, $short );
2553 # Remove the create restriction for existing titles
2554 $types = array_diff( $types, [
'create' ] );
2556 # Only the create and upload restrictions apply to non-existing titles
2557 $types = array_intersect( $types, [
'create',
'upload' ] );
2572 $types = self::getFilteredRestrictionTypes( $this->
exists() );
2575 # Remove the upload restriction for non-file titles
2576 $types = array_diff( $types, [
'upload' ] );
2579 Hooks::run(
'TitleGetRestrictionTypes', [ $this, &$types ] );
2581 wfDebug( __METHOD__ .
': applicable restrictions to [[' .
2582 $this->
getPrefixedText() .
']] are {' . implode(
',', $types ) .
"}\n" );
2596 if ( $protection ) {
2597 if ( $protection[
'permission'] ==
'sysop' ) {
2598 $protection[
'permission'] =
'editprotected';
2600 if ( $protection[
'permission'] ==
'autoconfirmed' ) {
2601 $protection[
'permission'] =
'editsemiprotected';
2628 if ( $this->mTitleProtection ===
null ) {
2633 'user' =>
'pt_user',
2634 'reason' =>
'pt_reason',
2635 'expiry' =>
'pt_expiry',
2636 'permission' =>
'pt_create_perm'
2645 $row[
'expiry'] =
$dbr->decodeExpiry( $row[
'expiry'] );
2647 $this->mTitleProtection = $row;
2649 return $this->mTitleProtection;
2663 $this->mTitleProtection =
false;
2678 if ( !$restrictions || !$semi ) {
2684 foreach ( array_keys( $semi,
'autoconfirmed' )
as $key ) {
2685 $semi[$key] =
'editsemiprotected';
2687 foreach ( array_keys( $restrictions,
'autoconfirmed' )
as $key ) {
2688 $restrictions[$key] =
'editsemiprotected';
2691 return !array_diff( $restrictions, $semi );
2706 # Special pages have inherent protection
2711 # Check regular protection levels
2712 foreach ( $restrictionTypes
as $type ) {
2713 if ( $action ==
$type || $action ==
'' ) {
2716 if ( in_array( $level, $r ) && $level !=
'' ) {
2738 if ( $right !=
'' && !
$user->isAllowed( $right ) ) {
2753 return ( $sources > 0 );
2766 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !==
null;
2783 $pagerestrictions = [];
2785 if ( $this->mCascadeSources !==
null && $getPages ) {
2786 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2787 } elseif ( $this->mHasCascadingRestrictions !==
null && !$getPages ) {
2788 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2794 $tables = [
'imagelinks',
'page_restrictions' ];
2801 $tables = [
'templatelinks',
'page_restrictions' ];
2811 $cols = [
'pr_page',
'page_namespace',
'page_title',
2812 'pr_expiry',
'pr_type',
'pr_level' ];
2813 $where_clauses[] =
'page_id=pr_page';
2816 $cols = [
'pr_expiry' ];
2821 $sources = $getPages ? [] :
false;
2824 foreach (
$res as $row ) {
2825 $expiry =
$dbr->decodeExpiry( $row->pr_expiry );
2826 if ( $expiry > $now ) {
2828 $page_id = $row->pr_page;
2829 $page_ns = $row->page_namespace;
2830 $page_title = $row->page_title;
2832 # Add groups needed for each restriction type if its not already there
2833 # Make sure this restriction type still exists
2835 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2836 $pagerestrictions[$row->pr_type] = [];
2840 isset( $pagerestrictions[$row->pr_type] )
2841 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2843 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2852 $this->mCascadeSources = $sources;
2853 $this->mCascadingRestrictions = $pagerestrictions;
2855 $this->mHasCascadingRestrictions = $sources;
2858 return [ $sources, $pagerestrictions ];
2869 return $this->mRestrictionsLoaded;
2882 if ( !$this->mRestrictionsLoaded ) {
2885 return isset( $this->mRestrictions[$action] )
2886 ? $this->mRestrictions[$action]
2898 if ( !$this->mRestrictionsLoaded ) {
2901 return $this->mRestrictions;
2912 if ( !$this->mRestrictionsLoaded ) {
2915 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] :
false;
2924 if ( !$this->mRestrictionsLoaded ) {
2928 return $this->mCascadeRestriction;
2945 foreach ( $restrictionTypes
as $type ) {
2946 $this->mRestrictions[
$type] = [];
2947 $this->mRestrictionsExpiry[
$type] =
'infinity';
2950 $this->mCascadeRestriction =
false;
2952 # Backwards-compatibility: also load the restrictions from the page record (old format).
2953 if ( $oldFashionedRestrictions !==
null ) {
2954 $this->mOldRestrictions = $oldFashionedRestrictions;
2957 if ( $this->mOldRestrictions ===
false ) {
2958 $this->mOldRestrictions =
$dbr->selectField(
'page',
'page_restrictions',
2962 if ( $this->mOldRestrictions !=
'' ) {
2963 foreach ( explode(
':', trim( $this->mOldRestrictions ) )
as $restrict ) {
2964 $temp = explode(
'=', trim( $restrict ) );
2965 if ( count( $temp ) == 1 ) {
2967 $this->mRestrictions[
'edit'] = explode(
',', trim( $temp[0] ) );
2968 $this->mRestrictions[
'move'] = explode(
',', trim( $temp[0] ) );
2970 $restriction = trim( $temp[1] );
2971 if ( $restriction !=
'' ) {
2972 $this->mRestrictions[$temp[0]] = explode(
',', $restriction );
2978 if ( count( $rows ) ) {
2979 # Current system - load second to make them override.
2982 # Cycle through all the restrictions.
2983 foreach ( $rows
as $row ) {
2985 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2989 $expiry =
$dbr->decodeExpiry( $row->pr_expiry );
2992 if ( !$expiry || $expiry > $now ) {
2993 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2994 $this->mRestrictions[$row->pr_type] = explode(
',', trim( $row->pr_level ) );
2996 $this->mCascadeRestriction |= $row->pr_cascade;
3001 $this->mRestrictionsLoaded =
true;
3011 if ( $this->mRestrictionsLoaded ) {
3017 $cache = ObjectCache::getMainWANInstance();
3018 $rows =
$cache->getWithSetCallback(
3020 $cache->makeKey(
'page-restrictions', $id, $this->getLatestRevID() ),
3025 $setOpts += Database::getCacheSetOptions(
$dbr );
3027 return iterator_to_array(
3029 'page_restrictions',
3030 [
'pr_type',
'pr_expiry',
'pr_level',
'pr_cascade' ],
3031 [
'pr_page' => $this->getArticleID() ],
3042 if ( $title_protection ) {
3046 if ( !$expiry || $expiry > $now ) {
3048 $this->mRestrictionsExpiry[
'create'] = $expiry;
3049 $this->mRestrictions[
'create'] =
3050 explode(
',', trim( $title_protection[
'permission'] ) );
3052 $this->mTitleProtection =
false;
3055 $this->mRestrictionsExpiry[
'create'] =
'infinity';
3057 $this->mRestrictionsLoaded =
true;
3066 $this->mRestrictionsLoaded =
false;
3067 $this->mTitleProtection =
null;
3084 $config = MediaWikiServices::getInstance()->getMainConfig();
3086 'page_restrictions',
3090 [
'LIMIT' => $config->get(
'UpdateRowsPerQuery' ) ]
3093 $dbw->
delete(
'page_restrictions', [
'pr_id' => $ids ],
$fname );
3117 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3122 # We dynamically add a member variable for the purpose of this method
3123 # alone to cache the result. There's no point in having it hanging
3124 # around uninitialized in every Title object; therefore we only add it
3125 # if needed and don't declare it statically.
3126 if ( $this->mHasSubpages ===
null ) {
3127 $this->mHasSubpages =
false;
3130 $this->mHasSubpages = (bool)$subpages->count();
3134 return $this->mHasSubpages;
3145 if ( !MWNamespace::hasSubpages( $this->
getNamespace() ) ) {
3151 $conds[] =
'page_title ' .
$dbr->buildLike( $this->
getDBkey() .
'/',
$dbr->anyString() );
3157 $dbr->select(
'page',
3158 [
'page_id',
'page_namespace',
'page_title',
'page_is_redirect' ],
3164 return $this->mSubpages;
3178 $n =
$dbr->selectField(
'archive',
'COUNT(*)',
3183 $n +=
$dbr->selectField(
'filearchive',
'COUNT(*)',
3184 [
'fa_name' => $this->
getDBkey() ],
3202 $deleted = (bool)
$dbr->selectField(
'archive',
'1',
3203 [
'ar_namespace' => $this->getNamespace(),
'ar_title' => $this->
getDBkey() ],
3207 $deleted = (bool)
$dbr->selectField(
'filearchive',
'1',
3208 [
'fa_name' => $this->getDBkey() ],
3225 $this->mArticleID = 0;
3226 return $this->mArticleID;
3228 $linkCache = LinkCache::singleton();
3229 if (
$flags & self::GAID_FOR_UPDATE ) {
3230 $oldUpdate = $linkCache->forUpdate(
true );
3231 $linkCache->clearLink( $this );
3232 $this->mArticleID = $linkCache->addLinkObj( $this );
3233 $linkCache->forUpdate( $oldUpdate );
3235 if ( -1 == $this->mArticleID ) {
3236 $this->mArticleID = $linkCache->addLinkObj( $this );
3239 return $this->mArticleID;
3250 if ( !is_null( $this->mRedirect ) ) {
3251 return $this->mRedirect;
3254 $this->mRedirect =
false;
3255 return $this->mRedirect;
3258 $linkCache = LinkCache::singleton();
3259 $linkCache->addLinkObj( $this ); #
in case we already had an
article ID
3260 $cached = $linkCache->getGoodLinkFieldObj( $this,
'redirect' );
3261 if ( $cached ===
null ) {
3262 # Trust LinkCache's state over our own
3263 # LinkCache is telling us that the page doesn't exist, despite there being cached
3264 # data relating to an existing page in $this->mArticleID. Updaters should clear
3265 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3266 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3267 # LinkCache to refresh its data from the master.
3268 $this->mRedirect =
false;
3269 return $this->mRedirect;
3272 $this->mRedirect = (bool)$cached;
3274 return $this->mRedirect;
3285 if ( $this->mLength != -1 ) {
3286 return $this->mLength;
3290 return $this->mLength;
3292 $linkCache = LinkCache::singleton();
3293 $linkCache->addLinkObj( $this ); #
in case we already had an
article ID
3294 $cached = $linkCache->getGoodLinkFieldObj( $this,
'length' );
3295 if ( $cached ===
null ) {
3296 # Trust LinkCache's state over our own, as for isRedirect()
3298 return $this->mLength;
3301 $this->mLength = intval( $cached );
3303 return $this->mLength;
3314 return intval( $this->mLatestID );
3317 $this->mLatestID = 0;
3318 return $this->mLatestID;
3320 $linkCache = LinkCache::singleton();
3321 $linkCache->addLinkObj( $this ); #
in case we already had an
article ID
3322 $cached = $linkCache->getGoodLinkFieldObj( $this,
'revision' );
3323 if ( $cached ===
null ) {
3324 # Trust LinkCache's state over our own, as for isRedirect()
3325 $this->mLatestID = 0;
3326 return $this->mLatestID;
3329 $this->mLatestID = intval( $cached );
3331 return $this->mLatestID;
3345 $linkCache = LinkCache::singleton();
3346 $linkCache->clearLink( $this );
3348 if ( $newid ===
false ) {
3349 $this->mArticleID = -1;
3351 $this->mArticleID = intval( $newid );
3353 $this->mRestrictionsLoaded =
false;
3354 $this->mRestrictions = [];
3355 $this->mOldRestrictions =
false;
3356 $this->mRedirect =
null;
3357 $this->mLength = -1;
3358 $this->mLatestID =
false;
3359 $this->mContentModel =
false;
3360 $this->mEstimateRevisions =
null;
3361 $this->mPageLanguage =
false;
3362 $this->mDbPageLanguage =
false;
3363 $this->mIsBigDeletion =
null;
3367 $linkCache = LinkCache::singleton();
3368 $linkCache->clear();
3384 if ( MWNamespace::isCapitalized( $ns ) ) {
3405 $this->mInterwiki =
'';
3406 $this->mFragment =
'';
3407 $this->mNamespace = $this->mDefaultNamespace; # Usually
NS_MAIN
3409 $dbkey = $this->mDbkeyform;
3416 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3422 $this->mInterwiki = $parts[
'interwiki'];
3423 $this->mLocalInterwiki = $parts[
'local_interwiki'];
3424 $this->mNamespace = $parts[
'namespace'];
3425 $this->mUserCaseDBKey = $parts[
'user_case_dbkey'];
3427 $this->mDbkeyform = $parts[
'dbkey'];
3428 $this->mUrlform =
wfUrlencode( $this->mDbkeyform );
3429 $this->mTextform = strtr( $this->mDbkeyform,
'_',
' ' );
3431 # We already know that some pages won't be in the database!
3433 $this->mArticleID = 0;
3460 self::getSelectFields(),
3462 "{$prefix}_from=page_id",
3464 "{$prefix}_title" => $this->
getDBkey() ],
3470 if (
$res->numRows() ) {
3471 $linkCache = LinkCache::singleton();
3472 foreach (
$res as $row ) {
3475 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3476 $retVal[] = $titleObj;
3512 # If the page doesn't exist; there can't be any link from this page
3519 $blNamespace =
"{$prefix}_namespace";
3520 $blTitle =
"{$prefix}_title";
3525 [ $blNamespace, $blTitle ],
3528 [
"{$prefix}_from" => $id ],
3533 [
"page_namespace=$blNamespace",
"page_title=$blTitle" ]
3538 $linkCache = LinkCache::singleton();
3539 foreach (
$res as $row ) {
3540 if ( $row->page_id ) {
3544 $linkCache->addBadLinkObj( $titleObj );
3546 $retVal[] = $titleObj;
3576 # All links from article ID 0 are false positives
3582 [
'page',
'pagelinks' ],
3583 [
'pl_namespace',
'pl_title' ],
3586 'page_namespace IS NULL'
3592 [
'pl_namespace=page_namespace',
'pl_title=page_title' ]
3598 foreach (
$res as $row ) {
3617 if ( $pageLang->hasVariants() ) {
3618 $variants = $pageLang->getVariants();
3619 foreach ( $variants
as $vCode ) {
3631 Hooks::run(
'TitleSquidURLs', [ $this, &
$urls ] );
3646 DeferredUpdates::addUpdate(
3648 DeferredUpdates::PRESEND
3665 if ( !( $nt instanceof
Title ) ) {
3668 return [ [
'badtitletext' ] ];
3672 $errors = $mp->isValidMove()->getErrorsArray();
3676 $mp->checkPermissions(
$wgUser, $reason )->getErrorsArray()
3680 return $errors ?:
true;
3695 $destFile->load( File::READ_LATEST );
3696 if ( !
$wgUser->isAllowed(
'reupload-shared' )
3699 $errors[] = [
'file-exists-sharedrepo' ];
3718 public function moveTo( &$nt, $auth =
true, $reason =
'', $createRedirect =
true,
3719 array $changeTags = [] ) {
3723 if ( is_array( $err ) ) {
3725 $wgUser->spreadAnyEditBlock();
3729 if ( $auth && !
$wgUser->isAllowed(
'suppressredirect' ) ) {
3730 $createRedirect =
true;
3734 $status = $mp->move(
$wgUser, $reason, $createRedirect, $changeTags );
3738 return $status->getErrorsArray();
3756 public function moveSubpages( $nt, $auth =
true, $reason =
'', $createRedirect =
true,
3757 array $changeTags = [] ) {
3761 if ( !$this->
userCan(
'move-subpages' ) ) {
3763 [
'cant-move-subpages' ],
3767 if ( !MWNamespace::hasSubpages( $this->
getNamespace() ) ) {
3769 [
'namespace-nosubpages', MWNamespace::getCanonicalName( $this->
getNamespace() ) ],
3772 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3774 [
'namespace-nosubpages', MWNamespace::getCanonicalName( $nt->getNamespace() ) ],
3781 foreach ( $subpages
as $oldSubpage ) {
3784 $retval[$oldSubpage->getPrefixedText()] = [
3793 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3794 || $oldSubpage->getArticleID() == $nt->getArticleID()
3800 $newPageName = preg_replace(
3801 '#^' . preg_quote( $this->
getDBkey(),
'#' ) .
'#',
3803 $oldSubpage->getDBkey() );
3804 if ( $oldSubpage->isTalkPage() ) {
3805 $newNs = $nt->getTalkPage()->getNamespace();
3807 $newNs = $nt->getSubjectPage()->getNamespace();
3809 # T16385: we need makeTitleSafe because the new page names may
3810 # be longer than 255 characters.
3813 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3815 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3835 $fields = [
'page_is_redirect',
'page_latest',
'page_id' ];
3837 $fields[] =
'page_content_model';
3840 $row = $dbw->selectRow(
'page',
3846 # Cache some fields we may want
3847 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3848 $this->mRedirect = $row ? (bool)$row->page_is_redirect :
false;
3849 $this->mLatestID = $row ? intval( $row->page_latest ) :
false;
3850 $this->mContentModel = $row && isset( $row->page_content_model )
3851 ? strval( $row->page_content_model )
3854 if ( !$this->mRedirect ) {
3857 # Does the article have a history?
3858 $row = $dbw->selectField( [
'page',
'revision' ],
3863 'page_latest != rev_id'
3868 # Return true if there was no history
3869 return ( $row ===
false );
3881 # Is it an existing file?
3882 if ( $nt->getNamespace() ==
NS_FILE ) {
3884 $file->load( File::READ_LATEST );
3885 if ( $file->exists() ) {
3886 wfDebug( __METHOD__ .
": file exists\n" );
3890 # Is it a redirect with no history?
3891 if ( !$nt->isSingleRevRedirect() ) {
3892 wfDebug( __METHOD__ .
": not a one-rev redirect\n" );
3895 # Get the article text
3897 if ( !is_object(
$rev ) ) {
3901 # Does the redirect point to the source?
3902 # Or is it a broken self-redirect, usually caused by namespace collisions?
3905 if ( $redirTitle ) {
3906 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3907 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3908 wfDebug( __METHOD__ .
": redirect points to other page\n" );
3914 # Fail safe (not a redirect after all. strange.)
3915 wfDebug( __METHOD__ .
": failsafe: database sais " . $nt->getPrefixedDBkey() .
3916 " is a redirect, but it doesn't contain a valid redirect.\n" );
3935 if ( $titleKey === 0 ) {
3944 [
'cl_from' => $titleKey ],
3948 if (
$res->numRows() > 0 ) {
3949 foreach (
$res as $row ) {
3968 foreach ( $parents
as $parent => $current ) {
3969 if ( array_key_exists( $parent, $children ) ) {
3970 # Circular reference
3971 $stack[$parent] = [];
3975 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3991 if ( $this->mArticleID > 0 ) {
3993 return [
'page_id' => $this->mArticleID ];
3995 return [
'page_namespace' => $this->mNamespace,
'page_title' => $this->mDbkeyform ];
4011 if (
$flags & self::GAID_FOR_UPDATE ) {
4016 $revId = $db->selectField(
'revision',
'rev_id',
4019 'rev_id < ' . intval(
$revId )
4022 [
'ORDER BY' =>
'rev_id DESC',
'IGNORE INDEX' =>
'PRIMARY' ]
4025 if (
$revId ===
false ) {
4040 if (
$flags & self::GAID_FOR_UPDATE ) {
4045 $revId = $db->selectField(
'revision',
'rev_id',
4048 'rev_id > ' . intval(
$revId )
4051 [
'ORDER BY' =>
'rev_id',
'IGNORE INDEX' =>
'PRIMARY' ]
4054 if (
$revId ===
false ) {
4072 [
'rev_page' => $pageId ],
4075 'ORDER BY' =>
'rev_timestamp ASC',
4076 'IGNORE INDEX' =>
'rev_timestamp'
4094 return $rev ?
$rev->getTimestamp() :
null;
4104 return (
bool)
$dbr->selectField(
'page',
'page_is_new', $this->
pageCond(), __METHOD__ );
4119 if ( $this->mIsBigDeletion ===
null ) {
4122 $revCount =
$dbr->selectRowCount(
4133 return $this->mIsBigDeletion;
4142 if ( !$this->
exists() ) {
4146 if ( $this->mEstimateRevisions ===
null ) {
4148 $this->mEstimateRevisions =
$dbr->estimateRowCount(
'revision',
'*',
4152 return $this->mEstimateRevisions;
4165 if ( !( $old instanceof
Revision ) ) {
4168 if ( !( $new instanceof
Revision ) ) {
4171 if ( !$old || !$new ) {
4177 'rev_timestamp > ' .
$dbr->addQuotes(
$dbr->timestamp( $old->getTimestamp() ) ),
4178 'rev_timestamp < ' .
$dbr->addQuotes(
$dbr->timestamp( $new->getTimestamp() ) )
4180 if ( $max !==
null ) {
4181 return $dbr->selectRowCount(
'revision',
'1',
4184 [
'LIMIT' => $max + 1 ]
4187 return (
int)
$dbr->selectField(
'revision',
'count(*)', $conds, __METHOD__ );
4208 if ( !( $old instanceof
Revision ) ) {
4211 if ( !( $new instanceof
Revision ) ) {
4217 if ( !$old || !$new ) {
4224 if ( in_array(
'include_old',
$options ) ) {
4227 if ( in_array(
'include_new',
$options ) ) {
4230 if ( in_array(
'include_both',
$options ) ) {
4235 if ( $old->getId() === $new->getId() ) {
4236 return ( $old_cmp ===
'>' && $new_cmp ===
'<' ) ?
4239 } elseif ( $old->getId() === $new->getParentId() ) {
4240 if ( $old_cmp ===
'>=' && $new_cmp ===
'<=' ) {
4245 } elseif ( $old_cmp ===
'>=' ) {
4247 } elseif ( $new_cmp ===
'<=' ) {
4253 $res =
$dbr->select(
'revision',
'DISTINCT rev_user_text',
4256 "rev_timestamp $old_cmp " .
$dbr->addQuotes(
$dbr->timestamp( $old->getTimestamp() ) ),
4257 "rev_timestamp $new_cmp " .
$dbr->addQuotes(
$dbr->timestamp( $new->getTimestamp() ) )
4259 [
'LIMIT' =>
$limit + 1 ]
4261 foreach (
$res as $row ) {
4262 $authors[] = $row->rev_user_text;
4283 return $authors ? count( $authors ) : 0;
4324 Hooks::run(
'TitleExists', [ $this, &$exists ] );
4357 Hooks::run(
'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4359 if ( !is_null( $isKnown ) ) {
4367 switch ( $this->mNamespace ) {
4377 return $this->mDbkeyform ==
'';
4421 return $message->exists();
4444 if ( $message->exists() ) {
4445 return $message->plain();
4460 } elseif ( $this->mArticleID === 0 ) {
4465 $dbw->onTransactionPreCommitOrIdle(
function () {
4470 DeferredUpdates::addUpdate(
4475 $dbTimestamp = $dbw->
timestamp( $purgeTime ?: time() );
4478 [
'page_touched' => $dbTimestamp ],
4479 $conds + [
'page_touched < ' . $dbw->
addQuotes( $dbTimestamp ) ],
4482 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4485 DeferredUpdates::PRESEND
4497 DeferredUpdates::addUpdate(
new HTMLCacheUpdate( $this,
'pagelinks' ) );
4499 DeferredUpdates::addUpdate(
new HTMLCacheUpdate( $this,
'categorylinks' ) );
4510 if ( $db ===
null ) {
4513 $touched = $db->selectField(
'page',
'page_touched', $this->
pageCond(), __METHOD__ );
4531 $uid =
$user->getId();
4536 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4537 return $this->mNotificationTimestamp[$uid];
4540 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4541 $this->mNotificationTimestamp = [];
4544 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4545 $watchedItem = $store->getWatchedItem(
$user, $this );
4546 if ( $watchedItem ) {
4547 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4549 $this->mNotificationTimestamp[$uid] =
false;
4552 return $this->mNotificationTimestamp[$uid];
4564 $namespace = MWNamespace::getSubject( $this->
getNamespace() );
4568 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4576 if ( $namespaceKey ==
'' ) {
4577 $namespaceKey =
'main';
4580 if ( $namespaceKey ==
'file' ) {
4581 $namespaceKey =
'image';
4583 return $prepend . $namespaceKey;
4604 $where[] =
'rd_interwiki = ' .
$dbr->addQuotes(
'' ) .
' OR rd_interwiki IS NULL';
4606 if ( !is_null( $ns ) ) {
4607 $where[
'page_namespace'] = $ns;
4611 [
'redirect',
'page' ],
4612 [
'page_namespace',
'page_title' ],
4617 foreach (
$res as $row ) {
4618 $redirs[] = self::newFromRow( $row );
4633 if ( $this->
isSpecial(
'Userlogout' ) ) {
4665 ? MWNamespace::getContentNamespaces()
4668 return !in_array( $this->mNamespace, $bannedNamespaces );
4682 $unprefixed = $this->
getText();
4688 Hooks::run(
'GetDefaultSortkey', [ $this, &$unprefixed ] );
4689 if ( $prefix !==
'' ) {
4690 # Separate with a line feed, so the unprefixed part is only used as
4691 # a tiebreaker when two pages have the exact same prefix.
4692 # In UCA, tab is the only character that can sort above LF
4693 # so we strip both of them from the original prefix.
4694 $prefix = strtr( $prefix,
"\n\t",
' ' );
4695 return "$prefix\n$unprefixed";
4713 $linkCache = LinkCache::singleton();
4714 $linkCache->addLinkObj( $this );
4715 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this,
'lang' );
4718 return $this->mDbPageLanguage;
4738 if ( $dbPageLanguage ) {
4742 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !==
$wgLanguageCode ) {
4750 $langObj = $contentHandler->getPageLanguage( $this );
4773 $variant =
$wgLang->getPreferredVariant();
4774 if (
$wgLang->getCode() !== $variant ) {
4775 return Language::factory( $variant );
4783 if ( $dbPageLanguage ) {
4785 $variant = $pageLang->getPreferredVariant();
4786 if ( $pageLang->getCode() !== $variant ) {
4787 $pageLang = Language::factory( $variant );
4797 $pageLang = $contentHandler->getPageViewLanguage( $this );
4815 $editnotice_ns =
'editnotice-' . $this->
getNamespace();
4817 if ( $msg->exists() ) {
4818 $html = $msg->parseAsBlock();
4820 if ( trim(
$html ) !==
'' ) {
4821 $notices[$editnotice_ns] = Html::rawElement(
4825 'mw-editnotice-namespace',
4826 Sanitizer::escapeClass(
"mw-$editnotice_ns" )
4833 if ( MWNamespace::hasSubpages( $this->
getNamespace() ) ) {
4835 $parts = explode(
'/', $this->
getDBkey() );
4836 $editnotice_base = $editnotice_ns;
4837 while ( count( $parts ) > 0 ) {
4838 $editnotice_base .=
'-' . array_shift( $parts );
4840 if ( $msg->exists() ) {
4841 $html = $msg->parseAsBlock();
4842 if ( trim(
$html ) !==
'' ) {
4843 $notices[$editnotice_base] = Html::rawElement(
4847 'mw-editnotice-base',
4848 Sanitizer::escapeClass(
"mw-$editnotice_base" )
4857 $editnoticeText = $editnotice_ns .
'-' . strtr( $this->
getDBkey(),
'/',
'-' );
4859 if ( $msg->exists() ) {
4860 $html = $msg->parseAsBlock();
4861 if ( trim(
$html ) !==
'' ) {
4862 $notices[$editnoticeText] = Html::rawElement(
4866 'mw-editnotice-page',
4867 Sanitizer::escapeClass(
"mw-$editnoticeText" )
4875 Hooks::run(
'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4890 'mDefaultNamespace',
4895 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4896 $this->mUrlform =
wfUrlencode( $this->mDbkeyform );
4897 $this->mTextform = strtr( $this->mDbkeyform,
'_',
' ' );
within a display generated by the Derivative if and wherever such third party notices normally appear The contents of the NOTICE file are for informational purposes only and do not modify the License You may add Your own attribution notices within Derivative Works that You alongside or as an addendum to the NOTICE text from the provided that such additional attribution notices cannot be construed as modifying the License You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for or distribution of Your or for any such Derivative Works as a provided Your and distribution of the Work otherwise complies with the conditions stated in this License Submission of Contributions Unless You explicitly state any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this without any additional terms or conditions Notwithstanding the nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions Trademarks This License does not grant permission to use the trade names
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgRestrictionLevels
Rights which can be required for each protection level (via action=protect)
$wgExemptFromUserRobotsControl
An array of namespace keys in which the INDEX/__NOINDEX__ magic words will not function,...
$wgLegalTitleChars
Allowed title characters – regex character class Don't change this unless you know what you're doing.
bool $wgPageLanguageUseDB
Enable page language feature Allows setting page language in database.
$wgSemiprotectedRestrictionLevels
Restriction levels that should be considered "semiprotected".
$wgLanguageCode
Site language code.
$wgMaximumMovedPages
Maximum number of pages to move at once when moving subpages with a page.
$wgScript
The URL path to index.php.
$wgInternalServer
Internal server name as known to CDN, if different.
$wgInvalidRedirectTargets
Array of invalid page redirect targets.
$wgNamespaceProtection
Set the minimum permissions required to edit pages in each namespace.
$wgRestrictionTypes
Set of available actions that can be restricted via action=protect You probably shouldn't change this...
$wgWhitelistRead
Pages anonymous user may see, set as an array of pages titles.
$wgWhitelistReadRegexp
Pages anonymous user may see, set as an array of regular expressions.
$wgDeleteRevisionsLimit
Optional to restrict deletion of pages with higher revision counts to users with the 'bigdelete' perm...
$wgBlockDisablesLogin
If true, blocked users will not be allowed to login.
$wgEmailConfirmToEdit
Should editors be required to have a validated e-mail address before being allowed to edit?
$wgVariantArticlePath
Like $wgArticlePath, but on multi-variant wikis, this provides a path format that describes which par...
$wgServer
URL of the server.
$wgContentHandlerUseDB
Set to false to disable use of the database fields introduced by the ContentHandler facility.
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMergeErrorArrays()
Merge arrays in the style of getUserPermissionsErrors, with duplicate removal e.g.
wfLocalFile( $title)
Get an object referring to a locally registered file.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfFindFile( $title, $options=[])
Find a file.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfArrayToCgi( $array1, $array2=null, $prefix='')
This function takes one or two arrays as input, and returns a CGI-style string, e....
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
if(! $wgDBerrorLogTZ) $wgRequest
Deferrable Update for closure/callback updates via IDatabase::doAtomicSection()
Deferrable Update for closure/callback updates that should use auto-commit mode.
static get(Title $title)
Create a new BacklinkCache or reuse any existing one.
get( $key, $flags=0, $oldFlags=null)
Get an item with the given key.
Handles purging appropriate CDN URLs given a title (or titles)
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
static getDefaultModelFor(Title $title)
Returns the name of the default content model to be used for the page with the given title.
Class to invalidate the HTML cache of all the pages linking to a given title.
Simple store for keeping values in an associative array for the current process.
set( $key, $value, $exptime=0, $flags=0)
Set an item.
static singleton()
Get the signleton instance of this class.
Handles the backend logic of moving a page from one title to another.
static getMain()
Static methods.
static invalidateModuleCache(Title $title, Revision $old=null, Revision $new=null, $wikiId)
Clear the preloadTitleInfo() cache for all wiki modules on this wiki on page change if it was a JS or...
static selectFields()
Return the list of revision fields that should be selected to create a new revision.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
static getLocalNameFor( $name, $subpage=false)
Get the local name for a specified canonical name.
static exists( $name)
Check if a given name exist as a special page or as a special page alias.
static resolveAlias( $alias)
Given a special page name with a possible subpage, return an array where the first element is the spe...
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
The TitleArray class only exists to provide the newFromResult method at pre- sent.
static newFromResult( $res)
Represents a page (or page fragment) title within MediaWiki.
Represents a title within MediaWiki.
string $mInterwiki
Interwiki prefix.
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
inNamespaces()
Returns true if the title is inside one of the specified namespaces.
getSubpages( $limit=-1)
Get all subpages of this page.
static getTitleInvalidRegex()
Returns a simple regex that will match on characters and sequences invalid in titles.
isWatchable()
Can this title be added to a user's watchlist?
getNamespace()
Get the namespace index, i.e.
estimateRevisionCount()
Get the approximate revision count of this page.
__wakeup()
Text form (spaces not underscores) of the main part.
static newFromDBkey( $key)
Create a new Title from a prefixed DB key.
isProtected( $action='')
Does the title correspond to a protected article?
getTitleProtectionInternal()
Fetch title protection settings.
getLinkURL( $query='', $query2=false, $proto=false)
Get a URL that's the simplest URL that will be valid to link, locally, to the current Title.
bool $mPageLanguage
The (string) language code of the page's language and content code.
array $mCascadeSources
Where are the cascading restrictions coming from on this page?
isSingleRevRedirect()
Checks if this page is just a one-rev redirect.
wasLocalInterwiki()
Was this a local interwiki link?
checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short)
Check CSS/JS sub-page permissions.
getInternalURL( $query='', $query2=false)
Get the URL form for an internal link.
purgeSquid()
Purge all applicable CDN URLs.
getFullURL( $query='', $query2=false, $proto=PROTO_RELATIVE)
Get a real URL referring to this title, with interwiki link and fragment.
getRestrictions( $action)
Accessor/initialisation for mRestrictions.
isKnown()
Does this title refer to a page that can (or might) be meaningfully viewed? In particular,...
int $mEstimateRevisions
Estimated number of revisions; null of not loaded.
getBacklinkCache()
Get a backlink cache object.
static getInterwikiLookup()
B/C kludge: provide an InterwikiLookup for use by Title.
static getTitleFormatter()
B/C kludge: provide a TitleParser for use by Title.
inNamespace( $ns)
Returns true if the title is inside the specified namespace.
equals(Title $title)
Compare with another title.
isDeletedQuick()
Is there a version of this page in the deletion archive?
static capitalize( $text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
checkQuickPermissions( $action, $user, $errors, $rigor, $short)
Permissions checks that fail most often, and which are easiest to test.
getTalkPage()
Get a Title object associated with the talk page of this article.
secureAndSplit()
Secure and split - main initialisation function for this object.
getAllRestrictions()
Accessor/initialisation for mRestrictions.
hasContentModel( $id)
Convenience method for checking a title's content model name.
getSkinFromCssJsSubpage()
Trim down a .css or .js subpage title to get the corresponding skin name.
static clearCaches()
Text form (spaces not underscores) of the main part.
createFragmentTarget( $fragment)
Creates a new Title for a different fragment of the same page.
getDefaultNamespace()
Get the default namespace index, for when there is no namespace.
moveTo(&$nt, $auth=true, $reason='', $createRedirect=true, array $changeTags=[])
Move a title to a new location.
isConversionTable()
Is this a conversion table for the LanguageConverter?
getFragment()
Get the Title fragment (i.e.
isCascadeProtected()
Cascading protection: Return true if cascading restrictions apply to this page, false if not.
static getFilteredRestrictionTypes( $exists=true)
Get a filtered list of all restriction types supported by this wiki.
getPrefixedURL()
Get a URL-encoded title (not an actual URL) including interwiki.
TitleValue $mTitleValue
A corresponding TitleValue object.
checkUserBlock( $action, $user, $errors, $rigor, $short)
Check that the user isn't blocked from editing.
isWikitextPage()
Does that page contain wikitext, or it is JS, CSS or whatever?
validateFileMoveOperation( $nt)
Check if the requested move target is a valid file move target.
getTalkNsText()
Get the namespace text of the talk page.
areRestrictionsCascading()
Returns cascading restrictions for the current article.
hasFragment()
Check if a Title fragment is set.
static nameOf( $id)
Get the prefixed DB key associated with an ID.
isSpecial( $name)
Returns true if this title resolves to the named special page.
getRedirectsHere( $ns=null)
Get all extant redirects to this Title.
getLength( $flags=0)
What is the length of this page? Uses link cache, adding it if necessary.
array $mNotificationTimestamp
Associative array of user ID -> timestamp/false.
isValidMoveOperation(&$nt, $auth=true, $reason='')
Check whether a given move operation would be valid.
getFullText()
Get the prefixed title with spaces, plus any fragment (part beginning with '#')
areRestrictionsLoaded()
Accessor for mRestrictionsLoaded.
canUseNoindex()
Whether the magic words INDEX and NOINDEX function for this page.
exists( $flags=0)
Check if page exists.
static newFromURL( $url)
THIS IS NOT THE FUNCTION YOU WANT.
static newFromTextThrow( $text, $defaultNamespace=NS_MAIN)
Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,...
isLocal()
Determine whether the object refers to a page within this project (either this wiki or a wiki with a ...
int $mLength
The page length, 0 for special pages.
loadFromRow( $row)
Load Title object fields from a DB row.
getPageLanguage()
Get the language in which the content of this page is written in wikitext.
bool $mLocalInterwiki
Was this Title created from a string with a local interwiki prefix?
getUserCaseDBKey()
Get the DB key with the initial letter case as specified by the user.
isMovable()
Would anybody with sufficient privileges be able to move this page? Some pages just aren't movable.
const CACHE_MAX
Title::newFromText maintains a cache to avoid expensive re-normalization of commonly used titles.
getRestrictionExpiry( $action)
Get the expiry time for the restriction against a given action.
getUserPermissionsErrors( $action, $user, $rigor='secure', $ignoreErrors=[])
Can $user perform $action on this page?
getSubjectPage()
Get a title object associated with the subject page of this talk page.
getTemplateLinksTo( $options=[])
Get an array of Title objects using this Title as a template Also stores the IDs in the link cache.
fixSpecialName()
If the Title refers to a special page alias which is not the local default, resolve the alias,...
getRestrictionTypes()
Returns restriction types for the current Title.
static legalChars()
Get a regex character class describing the legal characters in a link.
__toString()
Return a string representation of this title.
hasSubjectNamespace( $ns)
Returns true if the title has the same subject namespace as the namespace specified.
isSemiProtected( $action='edit')
Is this page "semi-protected" - the only protection levels are listed in $wgSemiprotectedRestrictionL...
isCssJsSubpage()
Is this a .css or .js subpage of a user page?
getPrefixedDBkey()
Get the prefixed database key form.
areCascadeProtectionSourcesLoaded( $getPages=true)
Determines whether cascading protection sources have already been loaded from the database.
getPreviousRevisionID( $revId, $flags=0)
Get the revision ID of the previous revision.
getNsText()
Get the namespace text.
canExist()
Is this in a namespace that allows actual pages?
static purgeExpiredRestrictions()
Purge expired restrictions from the page_restrictions table.
getDefaultMessageText()
Get the default message text or false if the message doesn't exist.
getDbPageLanguageCode()
Returns the page language code saved in the database, if $wgPageLanguageUseDB is set to true in Local...
countRevisionsBetween( $old, $new, $max=null)
Get the number of revisions between the given revision.
checkPermissionHooks( $action, $user, $errors, $rigor, $short)
Check various permission hooks.
bool $mForcedContentModel
If a content model was forced via setContentModel() this will be true to avoid having other code path...
getNotificationTimestamp( $user=null)
Get the timestamp when this page was updated since the user last saw it.
isTrans()
Determine whether the object refers to a page within this project and is transcludable.
resetArticleID( $newid)
This clears some fields in this object, and clears any associated keys in the "bad links" section of ...
isNewPage()
Check if this is a new page.
touchLinks()
Update page_touched timestamps and send CDN purge messages for pages linking to this title.
isExternal()
Is this Title interwiki?
bool $mRestrictionsLoaded
Boolean for initialisation on demand.
isMainPage()
Is this the mainpage?
getFragmentForURL()
Get the fragment in URL form, including the "#" character if there is one.
string bool null $mDbPageLanguage
The page language code from the database, null if not saved in the database or false if not loaded,...
getAuthorsBetween( $old, $new, $limit, $options=[])
Get the authors between the given revisions or revision IDs.
isSpecialPage()
Returns true if this is a special page.
isNamespaceProtected(User $user)
Determines if $user is unable to edit this page because it has been protected by $wgNamespaceProtecti...
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
getSubpageUrlForm()
Get a URL-encoded form of the subpage text.
isTalkPage()
Is this a talk page of some sort?
getRootTitle()
Get the root page name title, i.e.
bool int $mLatestID
ID of most recent revision.
getBrokenLinksFrom()
Get an array of Title objects referring to non-existent articles linked from this page.
getDBkey()
Get the main part with underscores.
missingPermissionError( $action, $short)
Get a description array when the user doesn't have the right to perform $action (i....
prefix( $name)
Prefix some arbitrary text with the namespace or interwiki prefix of this object.
getEarliestRevTime( $flags=0)
Get the oldest revision timestamp of this page.
checkActionPermissions( $action, $user, $errors, $rigor, $short)
Check action permissions not already checked in checkQuickPermissions.
string $mFragment
Title fragment (i.e.
getRootText()
Get the root page name text without a namespace, i.e.
getFullUrlForRedirect( $query='', $proto=PROTO_CURRENT)
Get a url appropriate for making redirects based on an untrusted url arg.
static newFromTitleValue(TitleValue $titleValue)
Create a new Title from a TitleValue.
string $mPrefixedText
Text form including namespace/interwiki, initialised on demand.
bool string $mContentModel
ID of the page's content model, i.e.
getLatestRevID( $flags=0)
What is the page_latest field for this page?
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
isValidRedirectTarget()
Check if this Title is a valid redirect target.
static HashBagOStuff $titleCache
getLinksFrom( $options=[], $table='pagelinks', $prefix='pl')
Get an array of Title objects linked from this Title Also stores the IDs in the link cache.
static makeName( $ns, $title, $fragment='', $interwiki='', $canonicalNamespace=false)
Make a prefixed DB key from a DB key and a namespace index.
getLinksTo( $options=[], $table='pagelinks', $prefix='pl')
Get an array of Title objects linking to this Title Also stores the IDs in the link cache.
bool $mHasCascadingRestrictions
Are cascading restrictions in effect on this page?
getPartialURL()
Get the URL-encoded form of the main part.
getBaseText()
Get the base page name without a namespace, i.e.
isContentPage()
Is this Title in a namespace which contains content? In other words, is this a content page,...
getText()
Get the text form (spaces not underscores) of the main part.
getTouched( $db=null)
Get the last touched timestamp.
getTitleValue()
Get a TitleValue object representing this Title.
pageCond()
Get an associative array for selecting this title from the "page" table.
bool $mCascadeRestriction
Cascade restrictions on this page to included templates and images?
string $mUrlform
URL-encoded form of the main part.
isJsSubpage()
Is this a .js subpage of a user page?
getFirstRevision( $flags=0)
Get the first revision of the page.
string $mTextform
Text form (spaces not underscores) of the main part.
getOtherPage()
Get the other title for this page, if this is a subject page get the talk page, if it is a subject pa...
static newFromIDs( $ids)
Make an array of titles from an array of IDs.
getUserPermissionsErrorsInternal( $action, $user, $rigor='secure', $short=false)
Can $user perform $action on this page? This is an internal function, with multiple levels of checks ...
quickUserCan( $action, $user=null)
Can $user perform $action on this page? This skips potentially expensive cascading permission checks ...
static getSelectFields()
Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
isSubpageOf(Title $title)
Check if this title is a subpage of another title.
getBaseTitle()
Get the base page name title, i.e.
static newMainPage()
Create a new Title for the Main Page.
getParentCategoryTree( $children=[])
Get a tree of parent categories.
checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short)
Check permissions on special pages & namespaces.
bool $mHasSubpages
Whether a page has any subpages.
isCssSubpage()
Is this a .css subpage of a user page?
getNextRevisionID( $revId, $flags=0)
Get the revision ID of the next revision.
array $mRestrictionsExpiry
When do the restrictions on this page expire?
loadRestrictionsFromRows( $rows, $oldFashionedRestrictions=null)
Compiles list of active page restrictions from both page table (pre 1.10) and page_restrictions table...
static fixUrlQueryArgs( $query, $query2=false)
Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args get{Canonical,...
isValidMoveTarget( $nt)
Checks if $this can be moved to a given Title.
loadRestrictions( $oldFashionedRestrictions=null)
Load restrictions from the page_restrictions table.
isRedirect( $flags=0)
Is this an article that is a redirect page? Uses link cache, adding it if necessary.
checkPageRestrictions( $action, $user, $errors, $rigor, $short)
Check against page_restrictions table requirements on this page.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
invalidateCache( $purgeTime=null)
Updates page_touched for this page; called from LinksUpdate.php.
$mCascadingRestrictions
Caching the results of getCascadeProtectionSources.
static escapeFragmentForURL( $fragment)
Escape a text fragment, say from a link, for a URL.
getArticleID( $flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
getSubjectNsText()
Get the namespace text of the subject (rather than talk) page.
bool $mIsBigDeletion
Would deleting this page be a big deletion?
int $mNamespace
Namespace index, i.e.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
null $mRedirect
Is the article at this title a redirect?
countAuthorsBetween( $old, $new, $limit, $options=[])
Get the number of authors between the given revisions or revision IDs.
static compare(LinkTarget $a, LinkTarget $b)
Callback for usort() to do title sorts by (namespace, title)
getCanonicalURL( $query='', $query2=false)
Get the URL for a canonical link, for use in things like IRC and e-mail notifications.
checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short)
Check restrictions on cascading pages.
isDeleted()
Is there a version of this page in the deletion archive?
getPageViewLanguage()
Get the language in which the content of this page is written when viewed by user.
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
checkReadPermissions( $action, $user, $errors, $rigor, $short)
Check that the user is allowed to read this page.
userCan( $action, $user=null, $rigor='secure')
Can $user perform $action on this page?
array $mRestrictions
Array of groups allowed to edit this article.
int $mDefaultNamespace
Namespace index when there is no namespace.
moveSubpages( $nt, $auth=true, $reason='', $createRedirect=true, array $changeTags=[])
Move this page's subpages to be subpages of $nt.
deleteTitleProtection()
Remove any title protection due to page existing.
getSubpage( $text)
Get the title for a subpage of the current page.
getTitleProtection()
Is this title subject to title protection? Title protection is the one applied against creation of su...
getEditURL()
Get the edit URL for this Title.
getParentCategories()
Get categories to which this Title belongs and return an array of categories' names.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
int $mArticleID
Article ID, fetched from the link cache on demand.
getTemplateLinksFrom( $options=[])
Get an array of Title objects used on this Title as a template Also stores the IDs in the link cache.
getTransWikiID()
Returns the DB name of the distant wiki which owns the object.
isSubpage()
Is this a subpage?
setFragment( $fragment)
Set the fragment for this title.
getLocalURL( $query='', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
getContentModel( $flags=0)
Get the page's content model id, see the CONTENT_MODEL_XXX constants.
isCssOrJsPage()
Could this page contain custom CSS or JavaScript for the global UI.
isBigDeletion()
Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit.
getCdnUrls()
Get a list of URLs to purge from the CDN cache when this page changes.
string $mUserCaseDBKey
Database key with the initial letter in the case specified by the user.
getInterwiki()
Get the interwiki prefix.
getEditNotices( $oldid=0)
Get a list of rendered edit notices for this page.
setContentModel( $model)
Set a proposed content model for the page for permissions checking.
getCascadeProtectionSources( $getPages=true)
Cascading protection: Get the source of any cascading restrictions on this page.
mixed $mTitleProtection
Cached value for getTitleProtection (create protection)
getSubpageText()
Get the lowest-level subpage name, i.e.
string $mDbkeyform
Main part with underscores.
hasSourceText()
Does this page have source text?
flushRestrictions()
Flush the protection cache in this object and force reload from the database.
getPrefixedText()
Get the prefixed title with spaces.
hasSubpages()
Does this have subpages? (Warning, usually requires an extra DB query.)
string bool $mOldRestrictions
Text form (spaces not underscores) of the main part.
canTalk()
Could this title have a corresponding talk page?
resultToError( $errors, $result)
Add the resulting error code to the errors array.
isAlwaysKnown()
Should links to this title be shown as potentially viewable (i.e.
getNamespaceKey( $prepend='nstab-')
Generate strings used for xml 'id' names in monobook tabs.
getCategorySortkey( $prefix='')
Returns the raw sort key to be used for categories, with the specified prefix.
static newFromRow( $row)
Make a Title object from a DB row.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static selectFields()
Return the list of revision fields that should be selected to create a new page.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an article
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
when a variable name is used in a function
when a variable name is used in a it is silently declared as a new local masking the global
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_JAVASCRIPT
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers please use GetContentModels hook to make them known to core if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
namespace and then decline to actually register it & $namespaces
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
namespace and then decline to actually register it file or subcat img or subcat $title
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null for the local wiki Added in
it s the revision text itself In either if gzip is the revision text is gzipped $flags
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Allows to change the fields on the form that will be generated $name
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context $revId
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
processing should stop and the error should be shown to the user * false
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
if(!isset( $args[0])) $lang