Update button focus and hover state according to spec
[mediawiki.git] / includes / Title.php
blobfac45d0c7a1e0f7d0203f4387b1718777287f95c
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
5 * See title.txt
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @file
25 /**
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
30 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
31 * and does not rely on global state or the database.
33 class Title {
34 /** @var MapCacheLRU */
35 static private $titleCache = null;
37 /**
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX = 1000;
44 /**
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE = 1;
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
55 // @{
57 /** @var string Text form (spaces not underscores) of the main part */
58 public $mTextform = '';
60 /** @var string URL-encoded form of the main part */
61 public $mUrlform = '';
63 /** @var string Main part with underscores */
64 public $mDbkeyform = '';
66 /** @var string Database key with the initial letter in the case specified by the user */
67 protected $mUserCaseDBKey;
69 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
70 public $mNamespace = NS_MAIN;
72 /** @var string Interwiki prefix */
73 public $mInterwiki = '';
75 /** @var bool Was this Title created from a string with a local interwiki prefix? */
76 private $mLocalInterwiki = false;
78 /** @var string Title fragment (i.e. the bit after the #) */
79 public $mFragment = '';
81 /** @var int Article ID, fetched from the link cache on demand */
82 public $mArticleID = -1;
84 /** @var bool|int ID of most recent revision */
85 protected $mLatestID = false;
87 /**
88 * @var bool|string ID of the page's content model, i.e. one of the
89 * CONTENT_MODEL_XXX constants
91 public $mContentModel = false;
93 /** @var int Estimated number of revisions; null of not loaded */
94 private $mEstimateRevisions;
96 /** @var array Array of groups allowed to edit this article */
97 public $mRestrictions = array();
99 /** @var string|bool */
100 protected $mOldRestrictions = false;
102 /** @var bool Cascade restrictions on this page to included templates and images? */
103 public $mCascadeRestriction;
105 /** Caching the results of getCascadeProtectionSources */
106 public $mCascadingRestrictions;
108 /** @var array When do the restrictions on this page expire? */
109 protected $mRestrictionsExpiry = array();
111 /** @var bool Are cascading restrictions in effect on this page? */
112 protected $mHasCascadingRestrictions;
114 /** @var array Where are the cascading restrictions coming from on this page? */
115 public $mCascadeSources;
117 /** @var bool Boolean for initialisation on demand */
118 public $mRestrictionsLoaded = false;
120 /** @var string Text form including namespace/interwiki, initialised on demand */
121 protected $mPrefixedText = null;
123 /** @var mixed Cached value for getTitleProtection (create protection) */
124 public $mTitleProtection;
127 * @var int Namespace index when there is no namespace. Don't change the
128 * following default, NS_MAIN is hardcoded in several places. See bug 696.
129 * Zero except in {{transclusion}} tags.
131 public $mDefaultNamespace = NS_MAIN;
134 * @var bool Is $wgUser watching this page? null if unfilled, accessed
135 * through userIsWatching()
137 protected $mWatched = null;
139 /** @var int The page length, 0 for special pages */
140 protected $mLength = -1;
142 /** @var null Is the article at this title a redirect? */
143 public $mRedirect = null;
145 /** @var array Associative array of user ID -> timestamp/false */
146 private $mNotificationTimestamp = array();
148 /** @var bool Whether a page has any subpages */
149 private $mHasSubpages;
151 /** @var bool The (string) language code of the page's language and content code. */
152 private $mPageLanguage = false;
154 /** @var string The page language code from the database */
155 private $mDbPageLanguage = null;
157 /** @var TitleValue A corresponding TitleValue object */
158 private $mTitleValue = null;
160 /** @var bool Would deleting this page be a big deletion? */
161 private $mIsBigDeletion = null;
162 // @}
165 * B/C kludge: provide a TitleParser for use by Title.
166 * Ideally, Title would have no methods that need this.
167 * Avoid usage of this singleton by using TitleValue
168 * and the associated services when possible.
170 * @return TitleParser
172 private static function getTitleParser() {
173 global $wgContLang, $wgLocalInterwikis;
175 static $titleCodec = null;
176 static $titleCodecFingerprint = null;
178 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
179 // make sure we are using the right one. To detect changes over the course
180 // of a request, we remember a fingerprint of the config used to create the
181 // codec singleton, and re-create it if the fingerprint doesn't match.
182 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
184 if ( $fingerprint !== $titleCodecFingerprint ) {
185 $titleCodec = null;
188 if ( !$titleCodec ) {
189 $titleCodec = new MediaWikiTitleCodec(
190 $wgContLang,
191 GenderCache::singleton(),
192 $wgLocalInterwikis
194 $titleCodecFingerprint = $fingerprint;
197 return $titleCodec;
201 * B/C kludge: provide a TitleParser for use by Title.
202 * Ideally, Title would have no methods that need this.
203 * Avoid usage of this singleton by using TitleValue
204 * and the associated services when possible.
206 * @return TitleFormatter
208 private static function getTitleFormatter() {
209 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
210 // which implements TitleFormatter.
211 return self::getTitleParser();
214 function __construct() {
218 * Create a new Title from a prefixed DB key
220 * @param string $key The database key, which has underscores
221 * instead of spaces, possibly including namespace and
222 * interwiki prefixes
223 * @return Title|null Title, or null on an error
225 public static function newFromDBkey( $key ) {
226 $t = new Title();
227 $t->mDbkeyform = $key;
229 try {
230 $t->secureAndSplit();
231 return $t;
232 } catch ( MalformedTitleException $ex ) {
233 return null;
238 * Create a new Title from a TitleValue
240 * @param TitleValue $titleValue Assumed to be safe.
242 * @return Title
244 public static function newFromTitleValue( TitleValue $titleValue ) {
245 return self::makeTitle(
246 $titleValue->getNamespace(),
247 $titleValue->getText(),
248 $titleValue->getFragment() );
252 * Create a new Title from text, such as what one would find in a link. De-
253 * codes any HTML entities in the text.
255 * @param string $text The link text; spaces, prefixes, and an
256 * initial ':' indicating the main namespace are accepted.
257 * @param int $defaultNamespace The namespace to use if none is specified
258 * by a prefix. If you want to force a specific namespace even if
259 * $text might begin with a namespace prefix, use makeTitle() or
260 * makeTitleSafe().
261 * @throws InvalidArgumentException
262 * @return Title|null Title or null on an error.
264 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
265 if ( is_object( $text ) ) {
266 throw new InvalidArgumentException( '$text must be a string.' );
267 } elseif ( !is_string( $text ) ) {
268 wfDebugLog( 'T76305', wfGetAllCallers( 5 ) );
269 wfWarn( __METHOD__ . ': $text must be a string. This will throw an InvalidArgumentException in future.', 2 );
272 try {
273 return Title::newFromTextThrow( $text, $defaultNamespace );
274 } catch ( MalformedTitleException $ex ) {
275 return null;
280 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
281 * rather than returning null.
283 * The exception subclasses encode detailed information about why the title is invalid.
285 * @see Title::newFromText
287 * @since 1.25
288 * @param string $text Title text to check
289 * @param int $defaultNamespace
290 * @throws MalformedTitleException If the title is invalid
291 * @return Title
293 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
294 if ( is_object( $text ) ) {
295 throw new MWException( 'Title::newFromTextThrow given an object' );
298 $cache = self::getTitleCache();
301 * Wiki pages often contain multiple links to the same page.
302 * Title normalization and parsing can become expensive on
303 * pages with many links, so we can save a little time by
304 * caching them.
306 * In theory these are value objects and won't get changed...
308 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
309 return $cache->get( $text );
312 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
313 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
315 $t = new Title();
316 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
317 $t->mDefaultNamespace = intval( $defaultNamespace );
319 $t->secureAndSplit();
320 if ( $defaultNamespace == NS_MAIN ) {
321 $cache->set( $text, $t );
323 return $t;
327 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
329 * Example of wrong and broken code:
330 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
332 * Example of right code:
333 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
335 * Create a new Title from URL-encoded text. Ensures that
336 * the given title's length does not exceed the maximum.
338 * @param string $url The title, as might be taken from a URL
339 * @return Title|null The new object, or null on an error
341 public static function newFromURL( $url ) {
342 $t = new Title();
344 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
345 # but some URLs used it as a space replacement and they still come
346 # from some external search tools.
347 if ( strpos( self::legalChars(), '+' ) === false ) {
348 $url = strtr( $url, '+', ' ' );
351 $t->mDbkeyform = strtr( $url, ' ', '_' );
353 try {
354 $t->secureAndSplit();
355 return $t;
356 } catch ( MalformedTitleException $ex ) {
357 return null;
362 * @return MapCacheLRU
364 private static function getTitleCache() {
365 if ( self::$titleCache == null ) {
366 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
368 return self::$titleCache;
372 * Returns a list of fields that are to be selected for initializing Title
373 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
374 * whether to include page_content_model.
376 * @return array
378 protected static function getSelectFields() {
379 global $wgContentHandlerUseDB;
381 $fields = array(
382 'page_namespace', 'page_title', 'page_id',
383 'page_len', 'page_is_redirect', 'page_latest',
386 if ( $wgContentHandlerUseDB ) {
387 $fields[] = 'page_content_model';
390 return $fields;
394 * Create a new Title from an article ID
396 * @param int $id The page_id corresponding to the Title to create
397 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
398 * @return Title|null The new object, or null on an error
400 public static function newFromID( $id, $flags = 0 ) {
401 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
402 $row = $db->selectRow(
403 'page',
404 self::getSelectFields(),
405 array( 'page_id' => $id ),
406 __METHOD__
408 if ( $row !== false ) {
409 $title = Title::newFromRow( $row );
410 } else {
411 $title = null;
413 return $title;
417 * Make an array of titles from an array of IDs
419 * @param int[] $ids Array of IDs
420 * @return Title[] Array of Titles
422 public static function newFromIDs( $ids ) {
423 if ( !count( $ids ) ) {
424 return array();
426 $dbr = wfGetDB( DB_SLAVE );
428 $res = $dbr->select(
429 'page',
430 self::getSelectFields(),
431 array( 'page_id' => $ids ),
432 __METHOD__
435 $titles = array();
436 foreach ( $res as $row ) {
437 $titles[] = Title::newFromRow( $row );
439 return $titles;
443 * Make a Title object from a DB row
445 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
446 * @return Title Corresponding Title
448 public static function newFromRow( $row ) {
449 $t = self::makeTitle( $row->page_namespace, $row->page_title );
450 $t->loadFromRow( $row );
451 return $t;
455 * Load Title object fields from a DB row.
456 * If false is given, the title will be treated as non-existing.
458 * @param stdClass|bool $row Database row
460 public function loadFromRow( $row ) {
461 if ( $row ) { // page found
462 if ( isset( $row->page_id ) ) {
463 $this->mArticleID = (int)$row->page_id;
465 if ( isset( $row->page_len ) ) {
466 $this->mLength = (int)$row->page_len;
468 if ( isset( $row->page_is_redirect ) ) {
469 $this->mRedirect = (bool)$row->page_is_redirect;
471 if ( isset( $row->page_latest ) ) {
472 $this->mLatestID = (int)$row->page_latest;
474 if ( isset( $row->page_content_model ) ) {
475 $this->mContentModel = strval( $row->page_content_model );
476 } else {
477 $this->mContentModel = false; # initialized lazily in getContentModel()
479 if ( isset( $row->page_lang ) ) {
480 $this->mDbPageLanguage = (string)$row->page_lang;
482 if ( isset( $row->page_restrictions ) ) {
483 $this->mOldRestrictions = $row->page_restrictions;
485 } else { // page not found
486 $this->mArticleID = 0;
487 $this->mLength = 0;
488 $this->mRedirect = false;
489 $this->mLatestID = 0;
490 $this->mContentModel = false; # initialized lazily in getContentModel()
495 * Create a new Title from a namespace index and a DB key.
496 * It's assumed that $ns and $title are *valid*, for instance when
497 * they came directly from the database or a special page name.
498 * For convenience, spaces are converted to underscores so that
499 * eg user_text fields can be used directly.
501 * @param int $ns The namespace of the article
502 * @param string $title The unprefixed database key form
503 * @param string $fragment The link fragment (after the "#")
504 * @param string $interwiki The interwiki prefix
505 * @return Title The new object
507 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
508 $t = new Title();
509 $t->mInterwiki = $interwiki;
510 $t->mFragment = $fragment;
511 $t->mNamespace = $ns = intval( $ns );
512 $t->mDbkeyform = strtr( $title, ' ', '_' );
513 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
514 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
515 $t->mTextform = strtr( $title, '_', ' ' );
516 $t->mContentModel = false; # initialized lazily in getContentModel()
517 return $t;
521 * Create a new Title from a namespace index and a DB key.
522 * The parameters will be checked for validity, which is a bit slower
523 * than makeTitle() but safer for user-provided data.
525 * @param int $ns The namespace of the article
526 * @param string $title Database key form
527 * @param string $fragment The link fragment (after the "#")
528 * @param string $interwiki Interwiki prefix
529 * @return Title The new object, or null on an error
531 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
532 if ( !MWNamespace::exists( $ns ) ) {
533 return null;
536 $t = new Title();
537 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
539 try {
540 $t->secureAndSplit();
541 return $t;
542 } catch ( MalformedTitleException $ex ) {
543 return null;
548 * Create a new Title for the Main Page
550 * @return Title The new object
552 public static function newMainPage() {
553 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
554 // Don't give fatal errors if the message is broken
555 if ( !$title ) {
556 $title = Title::newFromText( 'Main Page' );
558 return $title;
562 * Extract a redirect destination from a string and return the
563 * Title, or null if the text doesn't contain a valid redirect
564 * This will only return the very next target, useful for
565 * the redirect table and other checks that don't need full recursion
567 * @param string $text Text with possible redirect
568 * @return Title The corresponding Title
569 * @deprecated since 1.21, use Content::getRedirectTarget instead.
571 public static function newFromRedirect( $text ) {
572 ContentHandler::deprecated( __METHOD__, '1.21' );
574 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
575 return $content->getRedirectTarget();
579 * Extract a redirect destination from a string and return the
580 * Title, or null if the text doesn't contain a valid redirect
581 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
582 * in order to provide (hopefully) the Title of the final destination instead of another redirect
584 * @param string $text Text with possible redirect
585 * @return Title
586 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
588 public static function newFromRedirectRecurse( $text ) {
589 ContentHandler::deprecated( __METHOD__, '1.21' );
591 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
592 return $content->getUltimateRedirectTarget();
596 * Extract a redirect destination from a string and return an
597 * array of Titles, or null if the text doesn't contain a valid redirect
598 * The last element in the array is the final destination after all redirects
599 * have been resolved (up to $wgMaxRedirects times)
601 * @param string $text Text with possible redirect
602 * @return Title[] Array of Titles, with the destination last
603 * @deprecated since 1.21, use Content::getRedirectChain instead.
605 public static function newFromRedirectArray( $text ) {
606 ContentHandler::deprecated( __METHOD__, '1.21' );
608 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
609 return $content->getRedirectChain();
613 * Get the prefixed DB key associated with an ID
615 * @param int $id The page_id of the article
616 * @return Title|null An object representing the article, or null if no such article was found
618 public static function nameOf( $id ) {
619 $dbr = wfGetDB( DB_SLAVE );
621 $s = $dbr->selectRow(
622 'page',
623 array( 'page_namespace', 'page_title' ),
624 array( 'page_id' => $id ),
625 __METHOD__
627 if ( $s === false ) {
628 return null;
631 $n = self::makeName( $s->page_namespace, $s->page_title );
632 return $n;
636 * Get a regex character class describing the legal characters in a link
638 * @return string The list of characters, not delimited
640 public static function legalChars() {
641 global $wgLegalTitleChars;
642 return $wgLegalTitleChars;
646 * Returns a simple regex that will match on characters and sequences invalid in titles.
647 * Note that this doesn't pick up many things that could be wrong with titles, but that
648 * replacing this regex with something valid will make many titles valid.
650 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
652 * @return string Regex string
654 static function getTitleInvalidRegex() {
655 wfDeprecated( __METHOD__, '1.25' );
656 return MediaWikiTitleCodec::getTitleInvalidRegex();
660 * Utility method for converting a character sequence from bytes to Unicode.
662 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
663 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
665 * @param string $byteClass
666 * @return string
668 public static function convertByteClassToUnicodeClass( $byteClass ) {
669 $length = strlen( $byteClass );
670 // Input token queue
671 $x0 = $x1 = $x2 = '';
672 // Decoded queue
673 $d0 = $d1 = $d2 = '';
674 // Decoded integer codepoints
675 $ord0 = $ord1 = $ord2 = 0;
676 // Re-encoded queue
677 $r0 = $r1 = $r2 = '';
678 // Output
679 $out = '';
680 // Flags
681 $allowUnicode = false;
682 for ( $pos = 0; $pos < $length; $pos++ ) {
683 // Shift the queues down
684 $x2 = $x1;
685 $x1 = $x0;
686 $d2 = $d1;
687 $d1 = $d0;
688 $ord2 = $ord1;
689 $ord1 = $ord0;
690 $r2 = $r1;
691 $r1 = $r0;
692 // Load the current input token and decoded values
693 $inChar = $byteClass[$pos];
694 if ( $inChar == '\\' ) {
695 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
696 $x0 = $inChar . $m[0];
697 $d0 = chr( hexdec( $m[1] ) );
698 $pos += strlen( $m[0] );
699 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
700 $x0 = $inChar . $m[0];
701 $d0 = chr( octdec( $m[0] ) );
702 $pos += strlen( $m[0] );
703 } elseif ( $pos + 1 >= $length ) {
704 $x0 = $d0 = '\\';
705 } else {
706 $d0 = $byteClass[$pos + 1];
707 $x0 = $inChar . $d0;
708 $pos += 1;
710 } else {
711 $x0 = $d0 = $inChar;
713 $ord0 = ord( $d0 );
714 // Load the current re-encoded value
715 if ( $ord0 < 32 || $ord0 == 0x7f ) {
716 $r0 = sprintf( '\x%02x', $ord0 );
717 } elseif ( $ord0 >= 0x80 ) {
718 // Allow unicode if a single high-bit character appears
719 $r0 = sprintf( '\x%02x', $ord0 );
720 $allowUnicode = true;
721 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
722 $r0 = '\\' . $d0;
723 } else {
724 $r0 = $d0;
726 // Do the output
727 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
728 // Range
729 if ( $ord2 > $ord0 ) {
730 // Empty range
731 } elseif ( $ord0 >= 0x80 ) {
732 // Unicode range
733 $allowUnicode = true;
734 if ( $ord2 < 0x80 ) {
735 // Keep the non-unicode section of the range
736 $out .= "$r2-\\x7F";
738 } else {
739 // Normal range
740 $out .= "$r2-$r0";
742 // Reset state to the initial value
743 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
744 } elseif ( $ord2 < 0x80 ) {
745 // ASCII character
746 $out .= $r2;
749 if ( $ord1 < 0x80 ) {
750 $out .= $r1;
752 if ( $ord0 < 0x80 ) {
753 $out .= $r0;
755 if ( $allowUnicode ) {
756 $out .= '\u0080-\uFFFF';
758 return $out;
762 * Make a prefixed DB key from a DB key and a namespace index
764 * @param int $ns Numerical representation of the namespace
765 * @param string $title The DB key form the title
766 * @param string $fragment The link fragment (after the "#")
767 * @param string $interwiki The interwiki prefix
768 * @param bool $canoncialNamespace If true, use the canonical name for
769 * $ns instead of the localized version.
770 * @return string The prefixed form of the title
772 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
773 $canoncialNamespace = false
775 global $wgContLang;
777 if ( $canoncialNamespace ) {
778 $namespace = MWNamespace::getCanonicalName( $ns );
779 } else {
780 $namespace = $wgContLang->getNsText( $ns );
782 $name = $namespace == '' ? $title : "$namespace:$title";
783 if ( strval( $interwiki ) != '' ) {
784 $name = "$interwiki:$name";
786 if ( strval( $fragment ) != '' ) {
787 $name .= '#' . $fragment;
789 return $name;
793 * Escape a text fragment, say from a link, for a URL
795 * @param string $fragment Containing a URL or link fragment (after the "#")
796 * @return string Escaped string
798 static function escapeFragmentForURL( $fragment ) {
799 # Note that we don't urlencode the fragment. urlencoded Unicode
800 # fragments appear not to work in IE (at least up to 7) or in at least
801 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
802 # to care if they aren't encoded.
803 return Sanitizer::escapeId( $fragment, 'noninitial' );
807 * Callback for usort() to do title sorts by (namespace, title)
809 * @param Title $a
810 * @param Title $b
812 * @return int Result of string comparison, or namespace comparison
814 public static function compare( $a, $b ) {
815 if ( $a->getNamespace() == $b->getNamespace() ) {
816 return strcmp( $a->getText(), $b->getText() );
817 } else {
818 return $a->getNamespace() - $b->getNamespace();
823 * Determine whether the object refers to a page within
824 * this project (either this wiki or a wiki with a local
825 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
827 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
829 public function isLocal() {
830 if ( $this->isExternal() ) {
831 $iw = Interwiki::fetch( $this->mInterwiki );
832 if ( $iw ) {
833 return $iw->isLocal();
836 return true;
840 * Is this Title interwiki?
842 * @return bool
844 public function isExternal() {
845 return $this->mInterwiki !== '';
849 * Get the interwiki prefix
851 * Use Title::isExternal to check if a interwiki is set
853 * @return string Interwiki prefix
855 public function getInterwiki() {
856 return $this->mInterwiki;
860 * Was this a local interwiki link?
862 * @return bool
864 public function wasLocalInterwiki() {
865 return $this->mLocalInterwiki;
869 * Determine whether the object refers to a page within
870 * this project and is transcludable.
872 * @return bool True if this is transcludable
874 public function isTrans() {
875 if ( !$this->isExternal() ) {
876 return false;
879 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
883 * Returns the DB name of the distant wiki which owns the object.
885 * @return string The DB name
887 public function getTransWikiID() {
888 if ( !$this->isExternal() ) {
889 return false;
892 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
896 * Get a TitleValue object representing this Title.
898 * @note Not all valid Titles have a corresponding valid TitleValue
899 * (e.g. TitleValues cannot represent page-local links that have a
900 * fragment but no title text).
902 * @return TitleValue|null
904 public function getTitleValue() {
905 if ( $this->mTitleValue === null ) {
906 try {
907 $this->mTitleValue = new TitleValue(
908 $this->getNamespace(),
909 $this->getDBkey(),
910 $this->getFragment() );
911 } catch ( InvalidArgumentException $ex ) {
912 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
913 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
917 return $this->mTitleValue;
921 * Get the text form (spaces not underscores) of the main part
923 * @return string Main part of the title
925 public function getText() {
926 return $this->mTextform;
930 * Get the URL-encoded form of the main part
932 * @return string Main part of the title, URL-encoded
934 public function getPartialURL() {
935 return $this->mUrlform;
939 * Get the main part with underscores
941 * @return string Main part of the title, with underscores
943 public function getDBkey() {
944 return $this->mDbkeyform;
948 * Get the DB key with the initial letter case as specified by the user
950 * @return string DB key
952 function getUserCaseDBKey() {
953 if ( !is_null( $this->mUserCaseDBKey ) ) {
954 return $this->mUserCaseDBKey;
955 } else {
956 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
957 return $this->mDbkeyform;
962 * Get the namespace index, i.e. one of the NS_xxxx constants.
964 * @return int Namespace index
966 public function getNamespace() {
967 return $this->mNamespace;
971 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
973 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
974 * @return string Content model id
976 public function getContentModel( $flags = 0 ) {
977 if ( !$this->mContentModel && $this->getArticleID( $flags ) ) {
978 $linkCache = LinkCache::singleton();
979 $linkCache->addLinkObj( $this ); # in case we already had an article ID
980 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
983 if ( !$this->mContentModel ) {
984 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
987 return $this->mContentModel;
991 * Convenience method for checking a title's content model name
993 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
994 * @return bool True if $this->getContentModel() == $id
996 public function hasContentModel( $id ) {
997 return $this->getContentModel() == $id;
1001 * Get the namespace text
1003 * @return string Namespace text
1005 public function getNsText() {
1006 if ( $this->isExternal() ) {
1007 // This probably shouldn't even happen. ohh man, oh yuck.
1008 // But for interwiki transclusion it sometimes does.
1009 // Shit. Shit shit shit.
1011 // Use the canonical namespaces if possible to try to
1012 // resolve a foreign namespace.
1013 if ( MWNamespace::exists( $this->mNamespace ) ) {
1014 return MWNamespace::getCanonicalName( $this->mNamespace );
1018 try {
1019 $formatter = self::getTitleFormatter();
1020 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
1021 } catch ( InvalidArgumentException $ex ) {
1022 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
1023 return false;
1028 * Get the namespace text of the subject (rather than talk) page
1030 * @return string Namespace text
1032 public function getSubjectNsText() {
1033 global $wgContLang;
1034 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1038 * Get the namespace text of the talk page
1040 * @return string Namespace text
1042 public function getTalkNsText() {
1043 global $wgContLang;
1044 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1048 * Could this title have a corresponding talk page?
1050 * @return bool
1052 public function canTalk() {
1053 return MWNamespace::canTalk( $this->mNamespace );
1057 * Is this in a namespace that allows actual pages?
1059 * @return bool
1061 public function canExist() {
1062 return $this->mNamespace >= NS_MAIN;
1066 * Can this title be added to a user's watchlist?
1068 * @return bool
1070 public function isWatchable() {
1071 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1075 * Returns true if this is a special page.
1077 * @return bool
1079 public function isSpecialPage() {
1080 return $this->getNamespace() == NS_SPECIAL;
1084 * Returns true if this title resolves to the named special page
1086 * @param string $name The special page name
1087 * @return bool
1089 public function isSpecial( $name ) {
1090 if ( $this->isSpecialPage() ) {
1091 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1092 if ( $name == $thisName ) {
1093 return true;
1096 return false;
1100 * If the Title refers to a special page alias which is not the local default, resolve
1101 * the alias, and localise the name as necessary. Otherwise, return $this
1103 * @return Title
1105 public function fixSpecialName() {
1106 if ( $this->isSpecialPage() ) {
1107 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1108 if ( $canonicalName ) {
1109 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1110 if ( $localName != $this->mDbkeyform ) {
1111 return Title::makeTitle( NS_SPECIAL, $localName );
1115 return $this;
1119 * Returns true if the title is inside the specified namespace.
1121 * Please make use of this instead of comparing to getNamespace()
1122 * This function is much more resistant to changes we may make
1123 * to namespaces than code that makes direct comparisons.
1124 * @param int $ns The namespace
1125 * @return bool
1126 * @since 1.19
1128 public function inNamespace( $ns ) {
1129 return MWNamespace::equals( $this->getNamespace(), $ns );
1133 * Returns true if the title is inside one of the specified namespaces.
1135 * @param int $namespaces,... The namespaces to check for
1136 * @return bool
1137 * @since 1.19
1139 public function inNamespaces( /* ... */ ) {
1140 $namespaces = func_get_args();
1141 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1142 $namespaces = $namespaces[0];
1145 foreach ( $namespaces as $ns ) {
1146 if ( $this->inNamespace( $ns ) ) {
1147 return true;
1151 return false;
1155 * Returns true if the title has the same subject namespace as the
1156 * namespace specified.
1157 * For example this method will take NS_USER and return true if namespace
1158 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1159 * as their subject namespace.
1161 * This is MUCH simpler than individually testing for equivalence
1162 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1163 * @since 1.19
1164 * @param int $ns
1165 * @return bool
1167 public function hasSubjectNamespace( $ns ) {
1168 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1172 * Is this Title in a namespace which contains content?
1173 * In other words, is this a content page, for the purposes of calculating
1174 * statistics, etc?
1176 * @return bool
1178 public function isContentPage() {
1179 return MWNamespace::isContent( $this->getNamespace() );
1183 * Would anybody with sufficient privileges be able to move this page?
1184 * Some pages just aren't movable.
1186 * @return bool
1188 public function isMovable() {
1189 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1190 // Interwiki title or immovable namespace. Hooks don't get to override here
1191 return false;
1194 $result = true;
1195 Hooks::run( 'TitleIsMovable', array( $this, &$result ) );
1196 return $result;
1200 * Is this the mainpage?
1201 * @note Title::newFromText seems to be sufficiently optimized by the title
1202 * cache that we don't need to over-optimize by doing direct comparisons and
1203 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1204 * ends up reporting something differently than $title->isMainPage();
1206 * @since 1.18
1207 * @return bool
1209 public function isMainPage() {
1210 return $this->equals( Title::newMainPage() );
1214 * Is this a subpage?
1216 * @return bool
1218 public function isSubpage() {
1219 return MWNamespace::hasSubpages( $this->mNamespace )
1220 ? strpos( $this->getText(), '/' ) !== false
1221 : false;
1225 * Is this a conversion table for the LanguageConverter?
1227 * @return bool
1229 public function isConversionTable() {
1230 // @todo ConversionTable should become a separate content model.
1232 return $this->getNamespace() == NS_MEDIAWIKI &&
1233 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1237 * Does that page contain wikitext, or it is JS, CSS or whatever?
1239 * @return bool
1241 public function isWikitextPage() {
1242 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1246 * Could this page contain custom CSS or JavaScript for the global UI.
1247 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1248 * or CONTENT_MODEL_JAVASCRIPT.
1250 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1251 * for that!
1253 * Note that this method should not return true for pages that contain and
1254 * show "inactive" CSS or JS.
1256 * @return bool
1258 public function isCssOrJsPage() {
1259 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1260 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1261 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1263 # @note This hook is also called in ContentHandler::getDefaultModel.
1264 # It's called here again to make sure hook functions can force this
1265 # method to return true even outside the MediaWiki namespace.
1267 Hooks::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1269 return $isCssOrJsPage;
1273 * Is this a .css or .js subpage of a user page?
1274 * @return bool
1276 public function isCssJsSubpage() {
1277 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1278 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1279 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1283 * Trim down a .css or .js subpage title to get the corresponding skin name
1285 * @return string Containing skin name from .css or .js subpage title
1287 public function getSkinFromCssJsSubpage() {
1288 $subpage = explode( '/', $this->mTextform );
1289 $subpage = $subpage[count( $subpage ) - 1];
1290 $lastdot = strrpos( $subpage, '.' );
1291 if ( $lastdot === false ) {
1292 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1294 return substr( $subpage, 0, $lastdot );
1298 * Is this a .css subpage of a user page?
1300 * @return bool
1302 public function isCssSubpage() {
1303 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1304 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1308 * Is this a .js subpage of a user page?
1310 * @return bool
1312 public function isJsSubpage() {
1313 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1314 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1318 * Is this a talk page of some sort?
1320 * @return bool
1322 public function isTalkPage() {
1323 return MWNamespace::isTalk( $this->getNamespace() );
1327 * Get a Title object associated with the talk page of this article
1329 * @return Title The object for the talk page
1331 public function getTalkPage() {
1332 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1336 * Get a title object associated with the subject page of this
1337 * talk page
1339 * @return Title The object for the subject page
1341 public function getSubjectPage() {
1342 // Is this the same title?
1343 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1344 if ( $this->getNamespace() == $subjectNS ) {
1345 return $this;
1347 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1351 * Get the other title for this page, if this is a subject page
1352 * get the talk page, if it is a subject page get the talk page
1354 * @since 1.25
1355 * @throws MWException
1356 * @return Title
1358 public function getOtherPage() {
1359 if ( $this->isSpecialPage() ) {
1360 throw new MWException( 'Special pages cannot have other pages' );
1362 if ( $this->isTalkPage() ) {
1363 return $this->getSubjectPage();
1364 } else {
1365 return $this->getTalkPage();
1370 * Get the default namespace index, for when there is no namespace
1372 * @return int Default namespace index
1374 public function getDefaultNamespace() {
1375 return $this->mDefaultNamespace;
1379 * Get the Title fragment (i.e.\ the bit after the #) in text form
1381 * Use Title::hasFragment to check for a fragment
1383 * @return string Title fragment
1385 public function getFragment() {
1386 return $this->mFragment;
1390 * Check if a Title fragment is set
1392 * @return bool
1393 * @since 1.23
1395 public function hasFragment() {
1396 return $this->mFragment !== '';
1400 * Get the fragment in URL form, including the "#" character if there is one
1401 * @return string Fragment in URL form
1403 public function getFragmentForURL() {
1404 if ( !$this->hasFragment() ) {
1405 return '';
1406 } else {
1407 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1412 * Set the fragment for this title. Removes the first character from the
1413 * specified fragment before setting, so it assumes you're passing it with
1414 * an initial "#".
1416 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1417 * Still in active use privately.
1419 * @param string $fragment Text
1421 public function setFragment( $fragment ) {
1422 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1426 * Prefix some arbitrary text with the namespace or interwiki prefix
1427 * of this object
1429 * @param string $name The text
1430 * @return string The prefixed text
1432 private function prefix( $name ) {
1433 $p = '';
1434 if ( $this->isExternal() ) {
1435 $p = $this->mInterwiki . ':';
1438 if ( 0 != $this->mNamespace ) {
1439 $p .= $this->getNsText() . ':';
1441 return $p . $name;
1445 * Get the prefixed database key form
1447 * @return string The prefixed title, with underscores and
1448 * any interwiki and namespace prefixes
1450 public function getPrefixedDBkey() {
1451 $s = $this->prefix( $this->mDbkeyform );
1452 $s = strtr( $s, ' ', '_' );
1453 return $s;
1457 * Get the prefixed title with spaces.
1458 * This is the form usually used for display
1460 * @return string The prefixed title, with spaces
1462 public function getPrefixedText() {
1463 if ( $this->mPrefixedText === null ) {
1464 $s = $this->prefix( $this->mTextform );
1465 $s = strtr( $s, '_', ' ' );
1466 $this->mPrefixedText = $s;
1468 return $this->mPrefixedText;
1472 * Return a string representation of this title
1474 * @return string Representation of this title
1476 public function __toString() {
1477 return $this->getPrefixedText();
1481 * Get the prefixed title with spaces, plus any fragment
1482 * (part beginning with '#')
1484 * @return string The prefixed title, with spaces and the fragment, including '#'
1486 public function getFullText() {
1487 $text = $this->getPrefixedText();
1488 if ( $this->hasFragment() ) {
1489 $text .= '#' . $this->getFragment();
1491 return $text;
1495 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1497 * @par Example:
1498 * @code
1499 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1500 * # returns: 'Foo'
1501 * @endcode
1503 * @return string Root name
1504 * @since 1.20
1506 public function getRootText() {
1507 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1508 return $this->getText();
1511 return strtok( $this->getText(), '/' );
1515 * Get the root page name title, i.e. the leftmost part before any slashes
1517 * @par Example:
1518 * @code
1519 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1520 * # returns: Title{User:Foo}
1521 * @endcode
1523 * @return Title Root title
1524 * @since 1.20
1526 public function getRootTitle() {
1527 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1531 * Get the base page name without a namespace, i.e. the part before the subpage name
1533 * @par Example:
1534 * @code
1535 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1536 * # returns: 'Foo/Bar'
1537 * @endcode
1539 * @return string Base name
1541 public function getBaseText() {
1542 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1543 return $this->getText();
1546 $parts = explode( '/', $this->getText() );
1547 # Don't discard the real title if there's no subpage involved
1548 if ( count( $parts ) > 1 ) {
1549 unset( $parts[count( $parts ) - 1] );
1551 return implode( '/', $parts );
1555 * Get the base page name title, i.e. the part before the subpage name
1557 * @par Example:
1558 * @code
1559 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1560 * # returns: Title{User:Foo/Bar}
1561 * @endcode
1563 * @return Title Base title
1564 * @since 1.20
1566 public function getBaseTitle() {
1567 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1571 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1573 * @par Example:
1574 * @code
1575 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1576 * # returns: "Baz"
1577 * @endcode
1579 * @return string Subpage name
1581 public function getSubpageText() {
1582 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1583 return $this->mTextform;
1585 $parts = explode( '/', $this->mTextform );
1586 return $parts[count( $parts ) - 1];
1590 * Get the title for a subpage of the current page
1592 * @par Example:
1593 * @code
1594 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1595 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1596 * @endcode
1598 * @param string $text The subpage name to add to the title
1599 * @return Title Subpage title
1600 * @since 1.20
1602 public function getSubpage( $text ) {
1603 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1607 * Get a URL-encoded form of the subpage text
1609 * @return string URL-encoded subpage name
1611 public function getSubpageUrlForm() {
1612 $text = $this->getSubpageText();
1613 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1614 return $text;
1618 * Get a URL-encoded title (not an actual URL) including interwiki
1620 * @return string The URL-encoded form
1622 public function getPrefixedURL() {
1623 $s = $this->prefix( $this->mDbkeyform );
1624 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1625 return $s;
1629 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1630 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1631 * second argument named variant. This was deprecated in favor
1632 * of passing an array of option with a "variant" key
1633 * Once $query2 is removed for good, this helper can be dropped
1634 * and the wfArrayToCgi moved to getLocalURL();
1636 * @since 1.19 (r105919)
1637 * @param array|string $query
1638 * @param bool $query2
1639 * @return string
1641 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1642 if ( $query2 !== false ) {
1643 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1644 "method called with a second parameter is deprecated. Add your " .
1645 "parameter to an array passed as the first parameter.", "1.19" );
1647 if ( is_array( $query ) ) {
1648 $query = wfArrayToCgi( $query );
1650 if ( $query2 ) {
1651 if ( is_string( $query2 ) ) {
1652 // $query2 is a string, we will consider this to be
1653 // a deprecated $variant argument and add it to the query
1654 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1655 } else {
1656 $query2 = wfArrayToCgi( $query2 );
1658 // If we have $query content add a & to it first
1659 if ( $query ) {
1660 $query .= '&';
1662 // Now append the queries together
1663 $query .= $query2;
1665 return $query;
1669 * Get a real URL referring to this title, with interwiki link and
1670 * fragment
1672 * @see self::getLocalURL for the arguments.
1673 * @see wfExpandUrl
1674 * @param array|string $query
1675 * @param bool $query2
1676 * @param string $proto Protocol type to use in URL
1677 * @return string The URL
1679 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1680 $query = self::fixUrlQueryArgs( $query, $query2 );
1682 # Hand off all the decisions on urls to getLocalURL
1683 $url = $this->getLocalURL( $query );
1685 # Expand the url to make it a full url. Note that getLocalURL has the
1686 # potential to output full urls for a variety of reasons, so we use
1687 # wfExpandUrl instead of simply prepending $wgServer
1688 $url = wfExpandUrl( $url, $proto );
1690 # Finally, add the fragment.
1691 $url .= $this->getFragmentForURL();
1693 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1694 return $url;
1698 * Get a URL with no fragment or server name (relative URL) from a Title object.
1699 * If this page is generated with action=render, however,
1700 * $wgServer is prepended to make an absolute URL.
1702 * @see self::getFullURL to always get an absolute URL.
1703 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1704 * valid to link, locally, to the current Title.
1705 * @see self::newFromText to produce a Title object.
1707 * @param string|array $query An optional query string,
1708 * not used for interwiki links. Can be specified as an associative array as well,
1709 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1710 * Some query patterns will trigger various shorturl path replacements.
1711 * @param array $query2 An optional secondary query array. This one MUST
1712 * be an array. If a string is passed it will be interpreted as a deprecated
1713 * variant argument and urlencoded into a variant= argument.
1714 * This second query argument will be added to the $query
1715 * The second parameter is deprecated since 1.19. Pass it as a key,value
1716 * pair in the first parameter array instead.
1718 * @return string String of the URL.
1720 public function getLocalURL( $query = '', $query2 = false ) {
1721 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1723 $query = self::fixUrlQueryArgs( $query, $query2 );
1725 $interwiki = Interwiki::fetch( $this->mInterwiki );
1726 if ( $interwiki ) {
1727 $namespace = $this->getNsText();
1728 if ( $namespace != '' ) {
1729 # Can this actually happen? Interwikis shouldn't be parsed.
1730 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1731 $namespace .= ':';
1733 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1734 $url = wfAppendQuery( $url, $query );
1735 } else {
1736 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1737 if ( $query == '' ) {
1738 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1739 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1740 } else {
1741 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1742 $url = false;
1743 $matches = array();
1745 if ( !empty( $wgActionPaths )
1746 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1748 $action = urldecode( $matches[2] );
1749 if ( isset( $wgActionPaths[$action] ) ) {
1750 $query = $matches[1];
1751 if ( isset( $matches[4] ) ) {
1752 $query .= $matches[4];
1754 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1755 if ( $query != '' ) {
1756 $url = wfAppendQuery( $url, $query );
1761 if ( $url === false
1762 && $wgVariantArticlePath
1763 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1764 && $this->getPageLanguage()->hasVariants()
1765 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1767 $variant = urldecode( $matches[1] );
1768 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1769 // Only do the variant replacement if the given variant is a valid
1770 // variant for the page's language.
1771 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1772 $url = str_replace( '$1', $dbkey, $url );
1776 if ( $url === false ) {
1777 if ( $query == '-' ) {
1778 $query = '';
1780 $url = "{$wgScript}?title={$dbkey}&{$query}";
1784 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1786 // @todo FIXME: This causes breakage in various places when we
1787 // actually expected a local URL and end up with dupe prefixes.
1788 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1789 $url = $wgServer . $url;
1792 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1793 return $url;
1797 * Get a URL that's the simplest URL that will be valid to link, locally,
1798 * to the current Title. It includes the fragment, but does not include
1799 * the server unless action=render is used (or the link is external). If
1800 * there's a fragment but the prefixed text is empty, we just return a link
1801 * to the fragment.
1803 * The result obviously should not be URL-escaped, but does need to be
1804 * HTML-escaped if it's being output in HTML.
1806 * @param array $query
1807 * @param bool $query2
1808 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1809 * @see self::getLocalURL for the arguments.
1810 * @return string The URL
1812 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1813 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1814 $ret = $this->getFullURL( $query, $query2, $proto );
1815 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1816 $ret = $this->getFragmentForURL();
1817 } else {
1818 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1820 return $ret;
1824 * Get the URL form for an internal link.
1825 * - Used in various Squid-related code, in case we have a different
1826 * internal hostname for the server from the exposed one.
1828 * This uses $wgInternalServer to qualify the path, or $wgServer
1829 * if $wgInternalServer is not set. If the server variable used is
1830 * protocol-relative, the URL will be expanded to http://
1832 * @see self::getLocalURL for the arguments.
1833 * @return string The URL
1835 public function getInternalURL( $query = '', $query2 = false ) {
1836 global $wgInternalServer, $wgServer;
1837 $query = self::fixUrlQueryArgs( $query, $query2 );
1838 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1839 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1840 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1841 return $url;
1845 * Get the URL for a canonical link, for use in things like IRC and
1846 * e-mail notifications. Uses $wgCanonicalServer and the
1847 * GetCanonicalURL hook.
1849 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1851 * @see self::getLocalURL for the arguments.
1852 * @return string The URL
1853 * @since 1.18
1855 public function getCanonicalURL( $query = '', $query2 = false ) {
1856 $query = self::fixUrlQueryArgs( $query, $query2 );
1857 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1858 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1859 return $url;
1863 * Get the edit URL for this Title
1865 * @return string The URL, or a null string if this is an interwiki link
1867 public function getEditURL() {
1868 if ( $this->isExternal() ) {
1869 return '';
1871 $s = $this->getLocalURL( 'action=edit' );
1873 return $s;
1877 * Is $wgUser watching this page?
1879 * @deprecated since 1.20; use User::isWatched() instead.
1880 * @return bool
1882 public function userIsWatching() {
1883 global $wgUser;
1885 if ( is_null( $this->mWatched ) ) {
1886 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1887 $this->mWatched = false;
1888 } else {
1889 $this->mWatched = $wgUser->isWatched( $this );
1892 return $this->mWatched;
1896 * Can $user perform $action on this page?
1897 * This skips potentially expensive cascading permission checks
1898 * as well as avoids expensive error formatting
1900 * Suitable for use for nonessential UI controls in common cases, but
1901 * _not_ for functional access control.
1903 * May provide false positives, but should never provide a false negative.
1905 * @param string $action Action that permission needs to be checked for
1906 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1907 * @return bool
1909 public function quickUserCan( $action, $user = null ) {
1910 return $this->userCan( $action, $user, false );
1914 * Can $user perform $action on this page?
1916 * @param string $action Action that permission needs to be checked for
1917 * @param User $user User to check (since 1.19); $wgUser will be used if not
1918 * provided.
1919 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1920 * @return bool
1922 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1923 if ( !$user instanceof User ) {
1924 global $wgUser;
1925 $user = $wgUser;
1928 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1932 * Can $user perform $action on this page?
1934 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1936 * @param string $action Action that permission needs to be checked for
1937 * @param User $user User to check
1938 * @param string $rigor One of (quick,full,secure)
1939 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1940 * - full : does cheap and expensive checks possibly from a slave
1941 * - secure : does cheap and expensive checks, using the master as needed
1942 * @param bool $short Set this to true to stop after the first permission error.
1943 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1944 * whose corresponding errors may be ignored.
1945 * @return array Array of arguments to wfMessage to explain permissions problems.
1947 public function getUserPermissionsErrors(
1948 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1950 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1952 // Remove the errors being ignored.
1953 foreach ( $errors as $index => $error ) {
1954 $error_key = is_array( $error ) ? $error[0] : $error;
1956 if ( in_array( $error_key, $ignoreErrors ) ) {
1957 unset( $errors[$index] );
1961 return $errors;
1965 * Permissions checks that fail most often, and which are easiest to test.
1967 * @param string $action The action to check
1968 * @param User $user User to check
1969 * @param array $errors List of current errors
1970 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1971 * @param bool $short Short circuit on first error
1973 * @return array List of errors
1975 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1976 if ( !Hooks::run( 'TitleQuickPermissions',
1977 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1979 return $errors;
1982 if ( $action == 'create' ) {
1983 if (
1984 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1985 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1987 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1989 } elseif ( $action == 'move' ) {
1990 if ( !$user->isAllowed( 'move-rootuserpages' )
1991 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1992 // Show user page-specific message only if the user can move other pages
1993 $errors[] = array( 'cant-move-user-page' );
1996 // Check if user is allowed to move files if it's a file
1997 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1998 $errors[] = array( 'movenotallowedfile' );
2001 // Check if user is allowed to move category pages if it's a category page
2002 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2003 $errors[] = array( 'cant-move-category-page' );
2006 if ( !$user->isAllowed( 'move' ) ) {
2007 // User can't move anything
2008 $userCanMove = User::groupHasPermission( 'user', 'move' );
2009 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2010 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2011 // custom message if logged-in users without any special rights can move
2012 $errors[] = array( 'movenologintext' );
2013 } else {
2014 $errors[] = array( 'movenotallowed' );
2017 } elseif ( $action == 'move-target' ) {
2018 if ( !$user->isAllowed( 'move' ) ) {
2019 // User can't move anything
2020 $errors[] = array( 'movenotallowed' );
2021 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2022 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2023 // Show user page-specific message only if the user can move other pages
2024 $errors[] = array( 'cant-move-to-user-page' );
2025 } elseif ( !$user->isAllowed( 'move-categorypages' )
2026 && $this->mNamespace == NS_CATEGORY ) {
2027 // Show category page-specific message only if the user can move other pages
2028 $errors[] = array( 'cant-move-to-category-page' );
2030 } elseif ( !$user->isAllowed( $action ) ) {
2031 $errors[] = $this->missingPermissionError( $action, $short );
2034 return $errors;
2038 * Add the resulting error code to the errors array
2040 * @param array $errors List of current errors
2041 * @param array $result Result of errors
2043 * @return array List of errors
2045 private function resultToError( $errors, $result ) {
2046 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2047 // A single array representing an error
2048 $errors[] = $result;
2049 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2050 // A nested array representing multiple errors
2051 $errors = array_merge( $errors, $result );
2052 } elseif ( $result !== '' && is_string( $result ) ) {
2053 // A string representing a message-id
2054 $errors[] = array( $result );
2055 } elseif ( $result === false ) {
2056 // a generic "We don't want them to do that"
2057 $errors[] = array( 'badaccess-group0' );
2059 return $errors;
2063 * Check various permission hooks
2065 * @param string $action The action to check
2066 * @param User $user User to check
2067 * @param array $errors List of current errors
2068 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2069 * @param bool $short Short circuit on first error
2071 * @return array List of errors
2073 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2074 // Use getUserPermissionsErrors instead
2075 $result = '';
2076 if ( !Hooks::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2077 return $result ? array() : array( array( 'badaccess-group0' ) );
2079 // Check getUserPermissionsErrors hook
2080 if ( !Hooks::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2081 $errors = $this->resultToError( $errors, $result );
2083 // Check getUserPermissionsErrorsExpensive hook
2084 if (
2085 $rigor !== 'quick'
2086 && !( $short && count( $errors ) > 0 )
2087 && !Hooks::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2089 $errors = $this->resultToError( $errors, $result );
2092 return $errors;
2096 * Check permissions on special pages & namespaces
2098 * @param string $action The action to check
2099 * @param User $user User to check
2100 * @param array $errors List of current errors
2101 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2102 * @param bool $short Short circuit on first error
2104 * @return array List of errors
2106 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2107 # Only 'createaccount' can be performed on special pages,
2108 # which don't actually exist in the DB.
2109 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2110 $errors[] = array( 'ns-specialprotected' );
2113 # Check $wgNamespaceProtection for restricted namespaces
2114 if ( $this->isNamespaceProtected( $user ) ) {
2115 $ns = $this->mNamespace == NS_MAIN ?
2116 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2117 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2118 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2121 return $errors;
2125 * Check CSS/JS sub-page permissions
2127 * @param string $action The action to check
2128 * @param User $user User to check
2129 * @param array $errors List of current errors
2130 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2131 * @param bool $short Short circuit on first error
2133 * @return array List of errors
2135 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2136 # Protect css/js subpages of user pages
2137 # XXX: this might be better using restrictions
2138 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2139 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2140 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2141 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2142 $errors[] = array( 'mycustomcssprotected', $action );
2143 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2144 $errors[] = array( 'mycustomjsprotected', $action );
2146 } else {
2147 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2148 $errors[] = array( 'customcssprotected', $action );
2149 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2150 $errors[] = array( 'customjsprotected', $action );
2155 return $errors;
2159 * Check against page_restrictions table requirements on this
2160 * page. The user must possess all required rights for this
2161 * action.
2163 * @param string $action The action to check
2164 * @param User $user User to check
2165 * @param array $errors List of current errors
2166 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2167 * @param bool $short Short circuit on first error
2169 * @return array List of errors
2171 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2172 foreach ( $this->getRestrictions( $action ) as $right ) {
2173 // Backwards compatibility, rewrite sysop -> editprotected
2174 if ( $right == 'sysop' ) {
2175 $right = 'editprotected';
2177 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2178 if ( $right == 'autoconfirmed' ) {
2179 $right = 'editsemiprotected';
2181 if ( $right == '' ) {
2182 continue;
2184 if ( !$user->isAllowed( $right ) ) {
2185 $errors[] = array( 'protectedpagetext', $right, $action );
2186 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2187 $errors[] = array( 'protectedpagetext', 'protect', $action );
2191 return $errors;
2195 * Check restrictions on cascading pages.
2197 * @param string $action The action to check
2198 * @param User $user User to check
2199 * @param array $errors List of current errors
2200 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2201 * @param bool $short Short circuit on first error
2203 * @return array List of errors
2205 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2206 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2207 # We /could/ use the protection level on the source page, but it's
2208 # fairly ugly as we have to establish a precedence hierarchy for pages
2209 # included by multiple cascade-protected pages. So just restrict
2210 # it to people with 'protect' permission, as they could remove the
2211 # protection anyway.
2212 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2213 # Cascading protection depends on more than this page...
2214 # Several cascading protected pages may include this page...
2215 # Check each cascading level
2216 # This is only for protection restrictions, not for all actions
2217 if ( isset( $restrictions[$action] ) ) {
2218 foreach ( $restrictions[$action] as $right ) {
2219 // Backwards compatibility, rewrite sysop -> editprotected
2220 if ( $right == 'sysop' ) {
2221 $right = 'editprotected';
2223 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2224 if ( $right == 'autoconfirmed' ) {
2225 $right = 'editsemiprotected';
2227 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2228 $pages = '';
2229 foreach ( $cascadingSources as $page ) {
2230 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2232 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2238 return $errors;
2242 * Check action permissions not already checked in checkQuickPermissions
2244 * @param string $action The action to check
2245 * @param User $user User to check
2246 * @param array $errors List of current errors
2247 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2248 * @param bool $short Short circuit on first error
2250 * @return array List of errors
2252 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2253 global $wgDeleteRevisionsLimit, $wgLang;
2255 if ( $action == 'protect' ) {
2256 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2257 // If they can't edit, they shouldn't protect.
2258 $errors[] = array( 'protect-cantedit' );
2260 } elseif ( $action == 'create' ) {
2261 $title_protection = $this->getTitleProtection();
2262 if ( $title_protection ) {
2263 if ( $title_protection['permission'] == ''
2264 || !$user->isAllowed( $title_protection['permission'] )
2266 $errors[] = array(
2267 'titleprotected',
2268 User::whoIs( $title_protection['user'] ),
2269 $title_protection['reason']
2273 } elseif ( $action == 'move' ) {
2274 // Check for immobile pages
2275 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2276 // Specific message for this case
2277 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2278 } elseif ( !$this->isMovable() ) {
2279 // Less specific message for rarer cases
2280 $errors[] = array( 'immobile-source-page' );
2282 } elseif ( $action == 'move-target' ) {
2283 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2284 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2285 } elseif ( !$this->isMovable() ) {
2286 $errors[] = array( 'immobile-target-page' );
2288 } elseif ( $action == 'delete' ) {
2289 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2290 if ( !$tempErrors ) {
2291 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2292 $user, $tempErrors, $rigor, true );
2294 if ( $tempErrors ) {
2295 // If protection keeps them from editing, they shouldn't be able to delete.
2296 $errors[] = array( 'deleteprotected' );
2298 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2299 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2301 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2304 return $errors;
2308 * Check that the user isn't blocked from editing.
2310 * @param string $action The action to check
2311 * @param User $user User to check
2312 * @param array $errors List of current errors
2313 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2314 * @param bool $short Short circuit on first error
2316 * @return array List of errors
2318 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2319 // Account creation blocks handled at userlogin.
2320 // Unblocking handled in SpecialUnblock
2321 if ( $rigor === 'quick' || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2322 return $errors;
2325 global $wgEmailConfirmToEdit;
2327 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2328 $errors[] = array( 'confirmedittext' );
2331 $useSlave = ( $rigor !== 'secure' );
2332 if ( ( $action == 'edit' || $action == 'create' )
2333 && !$user->isBlockedFrom( $this, $useSlave )
2335 // Don't block the user from editing their own talk page unless they've been
2336 // explicitly blocked from that too.
2337 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2338 // @todo FIXME: Pass the relevant context into this function.
2339 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2342 return $errors;
2346 * Check that the user is allowed to read this page.
2348 * @param string $action The action to check
2349 * @param User $user User to check
2350 * @param array $errors List of current errors
2351 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2352 * @param bool $short Short circuit on first error
2354 * @return array List of errors
2356 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2357 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2359 $whitelisted = false;
2360 if ( User::isEveryoneAllowed( 'read' ) ) {
2361 # Shortcut for public wikis, allows skipping quite a bit of code
2362 $whitelisted = true;
2363 } elseif ( $user->isAllowed( 'read' ) ) {
2364 # If the user is allowed to read pages, he is allowed to read all pages
2365 $whitelisted = true;
2366 } elseif ( $this->isSpecial( 'Userlogin' )
2367 || $this->isSpecial( 'ChangePassword' )
2368 || $this->isSpecial( 'PasswordReset' )
2370 # Always grant access to the login page.
2371 # Even anons need to be able to log in.
2372 $whitelisted = true;
2373 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2374 # Time to check the whitelist
2375 # Only do these checks is there's something to check against
2376 $name = $this->getPrefixedText();
2377 $dbName = $this->getPrefixedDBkey();
2379 // Check for explicit whitelisting with and without underscores
2380 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2381 $whitelisted = true;
2382 } elseif ( $this->getNamespace() == NS_MAIN ) {
2383 # Old settings might have the title prefixed with
2384 # a colon for main-namespace pages
2385 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2386 $whitelisted = true;
2388 } elseif ( $this->isSpecialPage() ) {
2389 # If it's a special page, ditch the subpage bit and check again
2390 $name = $this->getDBkey();
2391 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2392 if ( $name ) {
2393 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2394 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2395 $whitelisted = true;
2401 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2402 $name = $this->getPrefixedText();
2403 // Check for regex whitelisting
2404 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2405 if ( preg_match( $listItem, $name ) ) {
2406 $whitelisted = true;
2407 break;
2412 if ( !$whitelisted ) {
2413 # If the title is not whitelisted, give extensions a chance to do so...
2414 Hooks::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2415 if ( !$whitelisted ) {
2416 $errors[] = $this->missingPermissionError( $action, $short );
2420 return $errors;
2424 * Get a description array when the user doesn't have the right to perform
2425 * $action (i.e. when User::isAllowed() returns false)
2427 * @param string $action The action to check
2428 * @param bool $short Short circuit on first error
2429 * @return array List of errors
2431 private function missingPermissionError( $action, $short ) {
2432 // We avoid expensive display logic for quickUserCan's and such
2433 if ( $short ) {
2434 return array( 'badaccess-group0' );
2437 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2438 User::getGroupsWithPermission( $action ) );
2440 if ( count( $groups ) ) {
2441 global $wgLang;
2442 return array(
2443 'badaccess-groups',
2444 $wgLang->commaList( $groups ),
2445 count( $groups )
2447 } else {
2448 return array( 'badaccess-group0' );
2453 * Can $user perform $action on this page? This is an internal function,
2454 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2455 * checks on wfReadOnly() and blocks)
2457 * @param string $action Action that permission needs to be checked for
2458 * @param User $user User to check
2459 * @param string $rigor One of (quick,full,secure)
2460 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2461 * - full : does cheap and expensive checks possibly from a slave
2462 * - secure : does cheap and expensive checks, using the master as needed
2463 * @param bool $short Set this to true to stop after the first permission error.
2464 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2466 protected function getUserPermissionsErrorsInternal(
2467 $action, $user, $rigor = 'secure', $short = false
2469 if ( $rigor === true ) {
2470 $rigor = 'secure'; // b/c
2471 } elseif ( $rigor === false ) {
2472 $rigor = 'quick'; // b/c
2473 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2474 throw new Exception( "Invalid rigor parameter '$rigor'." );
2477 # Read has special handling
2478 if ( $action == 'read' ) {
2479 $checks = array(
2480 'checkPermissionHooks',
2481 'checkReadPermissions',
2483 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2484 # here as it will lead to duplicate error messages. This is okay to do
2485 # since anywhere that checks for create will also check for edit, and
2486 # those checks are called for edit.
2487 } elseif ( $action == 'create' ) {
2488 $checks = array(
2489 'checkQuickPermissions',
2490 'checkPermissionHooks',
2491 'checkPageRestrictions',
2492 'checkCascadingSourcesRestrictions',
2493 'checkActionPermissions',
2494 'checkUserBlock'
2496 } else {
2497 $checks = array(
2498 'checkQuickPermissions',
2499 'checkPermissionHooks',
2500 'checkSpecialsAndNSPermissions',
2501 'checkCSSandJSPermissions',
2502 'checkPageRestrictions',
2503 'checkCascadingSourcesRestrictions',
2504 'checkActionPermissions',
2505 'checkUserBlock'
2509 $errors = array();
2510 while ( count( $checks ) > 0 &&
2511 !( $short && count( $errors ) > 0 ) ) {
2512 $method = array_shift( $checks );
2513 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2516 return $errors;
2520 * Get a filtered list of all restriction types supported by this wiki.
2521 * @param bool $exists True to get all restriction types that apply to
2522 * titles that do exist, False for all restriction types that apply to
2523 * titles that do not exist
2524 * @return array
2526 public static function getFilteredRestrictionTypes( $exists = true ) {
2527 global $wgRestrictionTypes;
2528 $types = $wgRestrictionTypes;
2529 if ( $exists ) {
2530 # Remove the create restriction for existing titles
2531 $types = array_diff( $types, array( 'create' ) );
2532 } else {
2533 # Only the create and upload restrictions apply to non-existing titles
2534 $types = array_intersect( $types, array( 'create', 'upload' ) );
2536 return $types;
2540 * Returns restriction types for the current Title
2542 * @return array Applicable restriction types
2544 public function getRestrictionTypes() {
2545 if ( $this->isSpecialPage() ) {
2546 return array();
2549 $types = self::getFilteredRestrictionTypes( $this->exists() );
2551 if ( $this->getNamespace() != NS_FILE ) {
2552 # Remove the upload restriction for non-file titles
2553 $types = array_diff( $types, array( 'upload' ) );
2556 Hooks::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2558 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2559 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2561 return $types;
2565 * Is this title subject to title protection?
2566 * Title protection is the one applied against creation of such title.
2568 * @return array|bool An associative array representing any existent title
2569 * protection, or false if there's none.
2571 public function getTitleProtection() {
2572 // Can't protect pages in special namespaces
2573 if ( $this->getNamespace() < 0 ) {
2574 return false;
2577 // Can't protect pages that exist.
2578 if ( $this->exists() ) {
2579 return false;
2582 if ( $this->mTitleProtection === null ) {
2583 $dbr = wfGetDB( DB_SLAVE );
2584 $res = $dbr->select(
2585 'protected_titles',
2586 array(
2587 'user' => 'pt_user',
2588 'reason' => 'pt_reason',
2589 'expiry' => 'pt_expiry',
2590 'permission' => 'pt_create_perm'
2592 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2593 __METHOD__
2596 // fetchRow returns false if there are no rows.
2597 $row = $dbr->fetchRow( $res );
2598 if ( $row ) {
2599 if ( $row['permission'] == 'sysop' ) {
2600 $row['permission'] = 'editprotected'; // B/C
2602 if ( $row['permission'] == 'autoconfirmed' ) {
2603 $row['permission'] = 'editsemiprotected'; // B/C
2605 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2607 $this->mTitleProtection = $row;
2609 return $this->mTitleProtection;
2613 * Remove any title protection due to page existing
2615 public function deleteTitleProtection() {
2616 $dbw = wfGetDB( DB_MASTER );
2618 $dbw->delete(
2619 'protected_titles',
2620 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2621 __METHOD__
2623 $this->mTitleProtection = false;
2627 * Is this page "semi-protected" - the *only* protection levels are listed
2628 * in $wgSemiprotectedRestrictionLevels?
2630 * @param string $action Action to check (default: edit)
2631 * @return bool
2633 public function isSemiProtected( $action = 'edit' ) {
2634 global $wgSemiprotectedRestrictionLevels;
2636 $restrictions = $this->getRestrictions( $action );
2637 $semi = $wgSemiprotectedRestrictionLevels;
2638 if ( !$restrictions || !$semi ) {
2639 // Not protected, or all protection is full protection
2640 return false;
2643 // Remap autoconfirmed to editsemiprotected for BC
2644 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2645 $semi[$key] = 'editsemiprotected';
2647 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2648 $restrictions[$key] = 'editsemiprotected';
2651 return !array_diff( $restrictions, $semi );
2655 * Does the title correspond to a protected article?
2657 * @param string $action The action the page is protected from,
2658 * by default checks all actions.
2659 * @return bool
2661 public function isProtected( $action = '' ) {
2662 global $wgRestrictionLevels;
2664 $restrictionTypes = $this->getRestrictionTypes();
2666 # Special pages have inherent protection
2667 if ( $this->isSpecialPage() ) {
2668 return true;
2671 # Check regular protection levels
2672 foreach ( $restrictionTypes as $type ) {
2673 if ( $action == $type || $action == '' ) {
2674 $r = $this->getRestrictions( $type );
2675 foreach ( $wgRestrictionLevels as $level ) {
2676 if ( in_array( $level, $r ) && $level != '' ) {
2677 return true;
2683 return false;
2687 * Determines if $user is unable to edit this page because it has been protected
2688 * by $wgNamespaceProtection.
2690 * @param User $user User object to check permissions
2691 * @return bool
2693 public function isNamespaceProtected( User $user ) {
2694 global $wgNamespaceProtection;
2696 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2697 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2698 if ( $right != '' && !$user->isAllowed( $right ) ) {
2699 return true;
2703 return false;
2707 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2709 * @return bool If the page is subject to cascading restrictions.
2711 public function isCascadeProtected() {
2712 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2713 return ( $sources > 0 );
2717 * Determines whether cascading protection sources have already been loaded from
2718 * the database.
2720 * @param bool $getPages True to check if the pages are loaded, or false to check
2721 * if the status is loaded.
2722 * @return bool Whether or not the specified information has been loaded
2723 * @since 1.23
2725 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2726 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2730 * Cascading protection: Get the source of any cascading restrictions on this page.
2732 * @param bool $getPages Whether or not to retrieve the actual pages
2733 * that the restrictions have come from and the actual restrictions
2734 * themselves.
2735 * @return array Two elements: First is an array of Title objects of the
2736 * pages from which cascading restrictions have come, false for
2737 * none, or true if such restrictions exist but $getPages was not
2738 * set. Second is an array like that returned by
2739 * Title::getAllRestrictions(), or an empty array if $getPages is
2740 * false.
2742 public function getCascadeProtectionSources( $getPages = true ) {
2743 $pagerestrictions = array();
2745 if ( $this->mCascadeSources !== null && $getPages ) {
2746 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2747 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2748 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2751 $dbr = wfGetDB( DB_SLAVE );
2753 if ( $this->getNamespace() == NS_FILE ) {
2754 $tables = array( 'imagelinks', 'page_restrictions' );
2755 $where_clauses = array(
2756 'il_to' => $this->getDBkey(),
2757 'il_from=pr_page',
2758 'pr_cascade' => 1
2760 } else {
2761 $tables = array( 'templatelinks', 'page_restrictions' );
2762 $where_clauses = array(
2763 'tl_namespace' => $this->getNamespace(),
2764 'tl_title' => $this->getDBkey(),
2765 'tl_from=pr_page',
2766 'pr_cascade' => 1
2770 if ( $getPages ) {
2771 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2772 'pr_expiry', 'pr_type', 'pr_level' );
2773 $where_clauses[] = 'page_id=pr_page';
2774 $tables[] = 'page';
2775 } else {
2776 $cols = array( 'pr_expiry' );
2779 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2781 $sources = $getPages ? array() : false;
2782 $now = wfTimestampNow();
2784 foreach ( $res as $row ) {
2785 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2786 if ( $expiry > $now ) {
2787 if ( $getPages ) {
2788 $page_id = $row->pr_page;
2789 $page_ns = $row->page_namespace;
2790 $page_title = $row->page_title;
2791 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2792 # Add groups needed for each restriction type if its not already there
2793 # Make sure this restriction type still exists
2795 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2796 $pagerestrictions[$row->pr_type] = array();
2799 if (
2800 isset( $pagerestrictions[$row->pr_type] )
2801 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2803 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2805 } else {
2806 $sources = true;
2811 if ( $getPages ) {
2812 $this->mCascadeSources = $sources;
2813 $this->mCascadingRestrictions = $pagerestrictions;
2814 } else {
2815 $this->mHasCascadingRestrictions = $sources;
2818 return array( $sources, $pagerestrictions );
2822 * Accessor for mRestrictionsLoaded
2824 * @return bool Whether or not the page's restrictions have already been
2825 * loaded from the database
2826 * @since 1.23
2828 public function areRestrictionsLoaded() {
2829 return $this->mRestrictionsLoaded;
2833 * Accessor/initialisation for mRestrictions
2835 * @param string $action Action that permission needs to be checked for
2836 * @return array Restriction levels needed to take the action. All levels are
2837 * required. Note that restriction levels are normally user rights, but 'sysop'
2838 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2839 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2841 public function getRestrictions( $action ) {
2842 if ( !$this->mRestrictionsLoaded ) {
2843 $this->loadRestrictions();
2845 return isset( $this->mRestrictions[$action] )
2846 ? $this->mRestrictions[$action]
2847 : array();
2851 * Accessor/initialisation for mRestrictions
2853 * @return array Keys are actions, values are arrays as returned by
2854 * Title::getRestrictions()
2855 * @since 1.23
2857 public function getAllRestrictions() {
2858 if ( !$this->mRestrictionsLoaded ) {
2859 $this->loadRestrictions();
2861 return $this->mRestrictions;
2865 * Get the expiry time for the restriction against a given action
2867 * @param string $action
2868 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2869 * or not protected at all, or false if the action is not recognised.
2871 public function getRestrictionExpiry( $action ) {
2872 if ( !$this->mRestrictionsLoaded ) {
2873 $this->loadRestrictions();
2875 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2879 * Returns cascading restrictions for the current article
2881 * @return bool
2883 function areRestrictionsCascading() {
2884 if ( !$this->mRestrictionsLoaded ) {
2885 $this->loadRestrictions();
2888 return $this->mCascadeRestriction;
2892 * Loads a string into mRestrictions array
2894 * @param ResultWrapper $res Resource restrictions as an SQL result.
2895 * @param string $oldFashionedRestrictions Comma-separated list of page
2896 * restrictions from page table (pre 1.10)
2898 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2899 $rows = array();
2901 foreach ( $res as $row ) {
2902 $rows[] = $row;
2905 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2909 * Compiles list of active page restrictions from both page table (pre 1.10)
2910 * and page_restrictions table for this existing page.
2911 * Public for usage by LiquidThreads.
2913 * @param array $rows Array of db result objects
2914 * @param string $oldFashionedRestrictions Comma-separated list of page
2915 * restrictions from page table (pre 1.10)
2917 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2918 $dbr = wfGetDB( DB_SLAVE );
2920 $restrictionTypes = $this->getRestrictionTypes();
2922 foreach ( $restrictionTypes as $type ) {
2923 $this->mRestrictions[$type] = array();
2924 $this->mRestrictionsExpiry[$type] = 'infinity';
2927 $this->mCascadeRestriction = false;
2929 # Backwards-compatibility: also load the restrictions from the page record (old format).
2930 if ( $oldFashionedRestrictions !== null ) {
2931 $this->mOldRestrictions = $oldFashionedRestrictions;
2934 if ( $this->mOldRestrictions === false ) {
2935 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2936 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2939 if ( $this->mOldRestrictions != '' ) {
2940 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2941 $temp = explode( '=', trim( $restrict ) );
2942 if ( count( $temp ) == 1 ) {
2943 // old old format should be treated as edit/move restriction
2944 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2945 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2946 } else {
2947 $restriction = trim( $temp[1] );
2948 if ( $restriction != '' ) { //some old entries are empty
2949 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2955 if ( count( $rows ) ) {
2956 # Current system - load second to make them override.
2957 $now = wfTimestampNow();
2959 # Cycle through all the restrictions.
2960 foreach ( $rows as $row ) {
2962 // Don't take care of restrictions types that aren't allowed
2963 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2964 continue;
2967 // This code should be refactored, now that it's being used more generally,
2968 // But I don't really see any harm in leaving it in Block for now -werdna
2969 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2971 // Only apply the restrictions if they haven't expired!
2972 if ( !$expiry || $expiry > $now ) {
2973 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2974 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2976 $this->mCascadeRestriction |= $row->pr_cascade;
2981 $this->mRestrictionsLoaded = true;
2985 * Load restrictions from the page_restrictions table
2987 * @param string $oldFashionedRestrictions Comma-separated list of page
2988 * restrictions from page table (pre 1.10)
2990 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2991 if ( !$this->mRestrictionsLoaded ) {
2992 $dbr = wfGetDB( DB_SLAVE );
2993 if ( $this->exists() ) {
2994 $res = $dbr->select(
2995 'page_restrictions',
2996 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2997 array( 'pr_page' => $this->getArticleID() ),
2998 __METHOD__
3001 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
3002 } else {
3003 $title_protection = $this->getTitleProtection();
3005 if ( $title_protection ) {
3006 $now = wfTimestampNow();
3007 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
3009 if ( !$expiry || $expiry > $now ) {
3010 // Apply the restrictions
3011 $this->mRestrictionsExpiry['create'] = $expiry;
3012 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['permission'] ) );
3013 } else { // Get rid of the old restrictions
3014 $this->mTitleProtection = false;
3016 } else {
3017 $this->mRestrictionsExpiry['create'] = 'infinity';
3019 $this->mRestrictionsLoaded = true;
3025 * Flush the protection cache in this object and force reload from the database.
3026 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3028 public function flushRestrictions() {
3029 $this->mRestrictionsLoaded = false;
3030 $this->mTitleProtection = null;
3034 * Purge expired restrictions from the page_restrictions table
3036 static function purgeExpiredRestrictions() {
3037 if ( wfReadOnly() ) {
3038 return;
3041 $method = __METHOD__;
3042 $dbw = wfGetDB( DB_MASTER );
3043 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3044 $dbw->delete(
3045 'page_restrictions',
3046 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3047 $method
3049 $dbw->delete(
3050 'protected_titles',
3051 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3052 $method
3054 } );
3058 * Does this have subpages? (Warning, usually requires an extra DB query.)
3060 * @return bool
3062 public function hasSubpages() {
3063 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3064 # Duh
3065 return false;
3068 # We dynamically add a member variable for the purpose of this method
3069 # alone to cache the result. There's no point in having it hanging
3070 # around uninitialized in every Title object; therefore we only add it
3071 # if needed and don't declare it statically.
3072 if ( $this->mHasSubpages === null ) {
3073 $this->mHasSubpages = false;
3074 $subpages = $this->getSubpages( 1 );
3075 if ( $subpages instanceof TitleArray ) {
3076 $this->mHasSubpages = (bool)$subpages->count();
3080 return $this->mHasSubpages;
3084 * Get all subpages of this page.
3086 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3087 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3088 * doesn't allow subpages
3090 public function getSubpages( $limit = -1 ) {
3091 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3092 return array();
3095 $dbr = wfGetDB( DB_SLAVE );
3096 $conds['page_namespace'] = $this->getNamespace();
3097 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3098 $options = array();
3099 if ( $limit > -1 ) {
3100 $options['LIMIT'] = $limit;
3102 $this->mSubpages = TitleArray::newFromResult(
3103 $dbr->select( 'page',
3104 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3105 $conds,
3106 __METHOD__,
3107 $options
3110 return $this->mSubpages;
3114 * Is there a version of this page in the deletion archive?
3116 * @return int The number of archived revisions
3118 public function isDeleted() {
3119 if ( $this->getNamespace() < 0 ) {
3120 $n = 0;
3121 } else {
3122 $dbr = wfGetDB( DB_SLAVE );
3124 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3125 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3126 __METHOD__
3128 if ( $this->getNamespace() == NS_FILE ) {
3129 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3130 array( 'fa_name' => $this->getDBkey() ),
3131 __METHOD__
3135 return (int)$n;
3139 * Is there a version of this page in the deletion archive?
3141 * @return bool
3143 public function isDeletedQuick() {
3144 if ( $this->getNamespace() < 0 ) {
3145 return false;
3147 $dbr = wfGetDB( DB_SLAVE );
3148 $deleted = (bool)$dbr->selectField( 'archive', '1',
3149 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3150 __METHOD__
3152 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3153 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3154 array( 'fa_name' => $this->getDBkey() ),
3155 __METHOD__
3158 return $deleted;
3162 * Get the article ID for this Title from the link cache,
3163 * adding it if necessary
3165 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3166 * for update
3167 * @return int The ID
3169 public function getArticleID( $flags = 0 ) {
3170 if ( $this->getNamespace() < 0 ) {
3171 $this->mArticleID = 0;
3172 return $this->mArticleID;
3174 $linkCache = LinkCache::singleton();
3175 if ( $flags & self::GAID_FOR_UPDATE ) {
3176 $oldUpdate = $linkCache->forUpdate( true );
3177 $linkCache->clearLink( $this );
3178 $this->mArticleID = $linkCache->addLinkObj( $this );
3179 $linkCache->forUpdate( $oldUpdate );
3180 } else {
3181 if ( -1 == $this->mArticleID ) {
3182 $this->mArticleID = $linkCache->addLinkObj( $this );
3185 return $this->mArticleID;
3189 * Is this an article that is a redirect page?
3190 * Uses link cache, adding it if necessary
3192 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3193 * @return bool
3195 public function isRedirect( $flags = 0 ) {
3196 if ( !is_null( $this->mRedirect ) ) {
3197 return $this->mRedirect;
3199 if ( !$this->getArticleID( $flags ) ) {
3200 $this->mRedirect = false;
3201 return $this->mRedirect;
3204 $linkCache = LinkCache::singleton();
3205 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3206 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3207 if ( $cached === null ) {
3208 # Trust LinkCache's state over our own
3209 # LinkCache is telling us that the page doesn't exist, despite there being cached
3210 # data relating to an existing page in $this->mArticleID. Updaters should clear
3211 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3212 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3213 # LinkCache to refresh its data from the master.
3214 $this->mRedirect = false;
3215 return $this->mRedirect;
3218 $this->mRedirect = (bool)$cached;
3220 return $this->mRedirect;
3224 * What is the length of this page?
3225 * Uses link cache, adding it if necessary
3227 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3228 * @return int
3230 public function getLength( $flags = 0 ) {
3231 if ( $this->mLength != -1 ) {
3232 return $this->mLength;
3234 if ( !$this->getArticleID( $flags ) ) {
3235 $this->mLength = 0;
3236 return $this->mLength;
3238 $linkCache = LinkCache::singleton();
3239 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3240 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3241 if ( $cached === null ) {
3242 # Trust LinkCache's state over our own, as for isRedirect()
3243 $this->mLength = 0;
3244 return $this->mLength;
3247 $this->mLength = intval( $cached );
3249 return $this->mLength;
3253 * What is the page_latest field for this page?
3255 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3256 * @return int Int or 0 if the page doesn't exist
3258 public function getLatestRevID( $flags = 0 ) {
3259 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3260 return intval( $this->mLatestID );
3262 if ( !$this->getArticleID( $flags ) ) {
3263 $this->mLatestID = 0;
3264 return $this->mLatestID;
3266 $linkCache = LinkCache::singleton();
3267 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3268 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3269 if ( $cached === null ) {
3270 # Trust LinkCache's state over our own, as for isRedirect()
3271 $this->mLatestID = 0;
3272 return $this->mLatestID;
3275 $this->mLatestID = intval( $cached );
3277 return $this->mLatestID;
3281 * This clears some fields in this object, and clears any associated
3282 * keys in the "bad links" section of the link cache.
3284 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3285 * loading of the new page_id. It's also called from
3286 * WikiPage::doDeleteArticleReal()
3288 * @param int $newid The new Article ID
3290 public function resetArticleID( $newid ) {
3291 $linkCache = LinkCache::singleton();
3292 $linkCache->clearLink( $this );
3294 if ( $newid === false ) {
3295 $this->mArticleID = -1;
3296 } else {
3297 $this->mArticleID = intval( $newid );
3299 $this->mRestrictionsLoaded = false;
3300 $this->mRestrictions = array();
3301 $this->mOldRestrictions = false;
3302 $this->mRedirect = null;
3303 $this->mLength = -1;
3304 $this->mLatestID = false;
3305 $this->mContentModel = false;
3306 $this->mEstimateRevisions = null;
3307 $this->mPageLanguage = false;
3308 $this->mDbPageLanguage = null;
3309 $this->mIsBigDeletion = null;
3312 public static function clearCaches() {
3313 $linkCache = LinkCache::singleton();
3314 $linkCache->clear();
3316 $titleCache = self::getTitleCache();
3317 $titleCache->clear();
3321 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3323 * @param string $text Containing title to capitalize
3324 * @param int $ns Namespace index, defaults to NS_MAIN
3325 * @return string Containing capitalized title
3327 public static function capitalize( $text, $ns = NS_MAIN ) {
3328 global $wgContLang;
3330 if ( MWNamespace::isCapitalized( $ns ) ) {
3331 return $wgContLang->ucfirst( $text );
3332 } else {
3333 return $text;
3338 * Secure and split - main initialisation function for this object
3340 * Assumes that mDbkeyform has been set, and is urldecoded
3341 * and uses underscores, but not otherwise munged. This function
3342 * removes illegal characters, splits off the interwiki and
3343 * namespace prefixes, sets the other forms, and canonicalizes
3344 * everything.
3346 * @throws MalformedTitleException On invalid titles
3347 * @return bool True on success
3349 private function secureAndSplit() {
3350 # Initialisation
3351 $this->mInterwiki = '';
3352 $this->mFragment = '';
3353 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3355 $dbkey = $this->mDbkeyform;
3357 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3358 // the parsing code with Title, while avoiding massive refactoring.
3359 // @todo: get rid of secureAndSplit, refactor parsing code.
3360 $titleParser = self::getTitleParser();
3361 // MalformedTitleException can be thrown here
3362 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3364 # Fill fields
3365 $this->setFragment( '#' . $parts['fragment'] );
3366 $this->mInterwiki = $parts['interwiki'];
3367 $this->mLocalInterwiki = $parts['local_interwiki'];
3368 $this->mNamespace = $parts['namespace'];
3369 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3371 $this->mDbkeyform = $parts['dbkey'];
3372 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3373 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3375 # We already know that some pages won't be in the database!
3376 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3377 $this->mArticleID = 0;
3380 return true;
3384 * Get an array of Title objects linking to this Title
3385 * Also stores the IDs in the link cache.
3387 * WARNING: do not use this function on arbitrary user-supplied titles!
3388 * On heavily-used templates it will max out the memory.
3390 * @param array $options May be FOR UPDATE
3391 * @param string $table Table name
3392 * @param string $prefix Fields prefix
3393 * @return Title[] Array of Title objects linking here
3395 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3396 if ( count( $options ) > 0 ) {
3397 $db = wfGetDB( DB_MASTER );
3398 } else {
3399 $db = wfGetDB( DB_SLAVE );
3402 $res = $db->select(
3403 array( 'page', $table ),
3404 self::getSelectFields(),
3405 array(
3406 "{$prefix}_from=page_id",
3407 "{$prefix}_namespace" => $this->getNamespace(),
3408 "{$prefix}_title" => $this->getDBkey() ),
3409 __METHOD__,
3410 $options
3413 $retVal = array();
3414 if ( $res->numRows() ) {
3415 $linkCache = LinkCache::singleton();
3416 foreach ( $res as $row ) {
3417 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3418 if ( $titleObj ) {
3419 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3420 $retVal[] = $titleObj;
3424 return $retVal;
3428 * Get an array of Title objects using this Title as a template
3429 * Also stores the IDs in the link cache.
3431 * WARNING: do not use this function on arbitrary user-supplied titles!
3432 * On heavily-used templates it will max out the memory.
3434 * @param array $options May be FOR UPDATE
3435 * @return Title[] Array of Title the Title objects linking here
3437 public function getTemplateLinksTo( $options = array() ) {
3438 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3442 * Get an array of Title objects linked from this Title
3443 * Also stores the IDs in the link cache.
3445 * WARNING: do not use this function on arbitrary user-supplied titles!
3446 * On heavily-used templates it will max out the memory.
3448 * @param array $options May be FOR UPDATE
3449 * @param string $table Table name
3450 * @param string $prefix Fields prefix
3451 * @return array Array of Title objects linking here
3453 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3454 $id = $this->getArticleID();
3456 # If the page doesn't exist; there can't be any link from this page
3457 if ( !$id ) {
3458 return array();
3461 if ( count( $options ) > 0 ) {
3462 $db = wfGetDB( DB_MASTER );
3463 } else {
3464 $db = wfGetDB( DB_SLAVE );
3467 $blNamespace = "{$prefix}_namespace";
3468 $blTitle = "{$prefix}_title";
3470 $res = $db->select(
3471 array( $table, 'page' ),
3472 array_merge(
3473 array( $blNamespace, $blTitle ),
3474 WikiPage::selectFields()
3476 array( "{$prefix}_from" => $id ),
3477 __METHOD__,
3478 $options,
3479 array( 'page' => array(
3480 'LEFT JOIN',
3481 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3485 $retVal = array();
3486 $linkCache = LinkCache::singleton();
3487 foreach ( $res as $row ) {
3488 if ( $row->page_id ) {
3489 $titleObj = Title::newFromRow( $row );
3490 } else {
3491 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3492 $linkCache->addBadLinkObj( $titleObj );
3494 $retVal[] = $titleObj;
3497 return $retVal;
3501 * Get an array of Title objects used on this Title as a template
3502 * Also stores the IDs in the link cache.
3504 * WARNING: do not use this function on arbitrary user-supplied titles!
3505 * On heavily-used templates it will max out the memory.
3507 * @param array $options May be FOR UPDATE
3508 * @return Title[] Array of Title the Title objects used here
3510 public function getTemplateLinksFrom( $options = array() ) {
3511 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3515 * Get an array of Title objects referring to non-existent articles linked
3516 * from this page.
3518 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3519 * should use redirect table in this case).
3520 * @return Title[] Array of Title the Title objects
3522 public function getBrokenLinksFrom() {
3523 if ( $this->getArticleID() == 0 ) {
3524 # All links from article ID 0 are false positives
3525 return array();
3528 $dbr = wfGetDB( DB_SLAVE );
3529 $res = $dbr->select(
3530 array( 'page', 'pagelinks' ),
3531 array( 'pl_namespace', 'pl_title' ),
3532 array(
3533 'pl_from' => $this->getArticleID(),
3534 'page_namespace IS NULL'
3536 __METHOD__, array(),
3537 array(
3538 'page' => array(
3539 'LEFT JOIN',
3540 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3545 $retVal = array();
3546 foreach ( $res as $row ) {
3547 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3549 return $retVal;
3553 * Get a list of URLs to purge from the Squid cache when this
3554 * page changes
3556 * @return string[] Array of String the URLs
3558 public function getSquidURLs() {
3559 $urls = array(
3560 $this->getInternalURL(),
3561 $this->getInternalURL( 'action=history' )
3564 $pageLang = $this->getPageLanguage();
3565 if ( $pageLang->hasVariants() ) {
3566 $variants = $pageLang->getVariants();
3567 foreach ( $variants as $vCode ) {
3568 $urls[] = $this->getInternalURL( '', $vCode );
3572 // If we are looking at a css/js user subpage, purge the action=raw.
3573 if ( $this->isJsSubpage() ) {
3574 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3575 } elseif ( $this->isCssSubpage() ) {
3576 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3579 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3580 return $urls;
3584 * Purge all applicable Squid URLs
3586 public function purgeSquid() {
3587 global $wgUseSquid;
3588 if ( $wgUseSquid ) {
3589 $urls = $this->getSquidURLs();
3590 $u = new SquidUpdate( $urls );
3591 $u->doUpdate();
3596 * Move this page without authentication
3598 * @deprecated since 1.25 use MovePage class instead
3599 * @param Title $nt The new page Title
3600 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3602 public function moveNoAuth( &$nt ) {
3603 wfDeprecated( __METHOD__, '1.25' );
3604 return $this->moveTo( $nt, false );
3608 * Check whether a given move operation would be valid.
3609 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3611 * @deprecated since 1.25, use MovePage's methods instead
3612 * @param Title $nt The new title
3613 * @param bool $auth Whether to check user permissions (uses $wgUser)
3614 * @param string $reason Is the log summary of the move, used for spam checking
3615 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3617 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3618 global $wgUser;
3620 if ( !( $nt instanceof Title ) ) {
3621 // Normally we'd add this to $errors, but we'll get
3622 // lots of syntax errors if $nt is not an object
3623 return array( array( 'badtitletext' ) );
3626 $mp = new MovePage( $this, $nt );
3627 $errors = $mp->isValidMove()->getErrorsArray();
3628 if ( $auth ) {
3629 $errors = wfMergeErrorArrays(
3630 $errors,
3631 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3635 return $errors ?: true;
3639 * Check if the requested move target is a valid file move target
3640 * @todo move this to MovePage
3641 * @param Title $nt Target title
3642 * @return array List of errors
3644 protected function validateFileMoveOperation( $nt ) {
3645 global $wgUser;
3647 $errors = array();
3649 $destFile = wfLocalFile( $nt );
3650 $destFile->load( File::READ_LATEST );
3651 if ( !$wgUser->isAllowed( 'reupload-shared' )
3652 && !$destFile->exists() && wfFindFile( $nt )
3654 $errors[] = array( 'file-exists-sharedrepo' );
3657 return $errors;
3661 * Move a title to a new location
3663 * @deprecated since 1.25, use the MovePage class instead
3664 * @param Title $nt The new title
3665 * @param bool $auth Indicates whether $wgUser's permissions
3666 * should be checked
3667 * @param string $reason The reason for the move
3668 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3669 * Ignored if the user doesn't have the suppressredirect right.
3670 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3672 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3673 global $wgUser;
3674 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3675 if ( is_array( $err ) ) {
3676 // Auto-block user's IP if the account was "hard" blocked
3677 $wgUser->spreadAnyEditBlock();
3678 return $err;
3680 // Check suppressredirect permission
3681 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3682 $createRedirect = true;
3685 $mp = new MovePage( $this, $nt );
3686 $status = $mp->move( $wgUser, $reason, $createRedirect );
3687 if ( $status->isOK() ) {
3688 return true;
3689 } else {
3690 return $status->getErrorsArray();
3695 * Move this page's subpages to be subpages of $nt
3697 * @param Title $nt Move target
3698 * @param bool $auth Whether $wgUser's permissions should be checked
3699 * @param string $reason The reason for the move
3700 * @param bool $createRedirect Whether to create redirects from the old subpages to
3701 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3702 * @return array Array with old page titles as keys, and strings (new page titles) or
3703 * arrays (errors) as values, or an error array with numeric indices if no pages
3704 * were moved
3706 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3707 global $wgMaximumMovedPages;
3708 // Check permissions
3709 if ( !$this->userCan( 'move-subpages' ) ) {
3710 return array( 'cant-move-subpages' );
3712 // Do the source and target namespaces support subpages?
3713 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3714 return array( 'namespace-nosubpages',
3715 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3717 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3718 return array( 'namespace-nosubpages',
3719 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3722 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3723 $retval = array();
3724 $count = 0;
3725 foreach ( $subpages as $oldSubpage ) {
3726 $count++;
3727 if ( $count > $wgMaximumMovedPages ) {
3728 $retval[$oldSubpage->getPrefixedText()] =
3729 array( 'movepage-max-pages',
3730 $wgMaximumMovedPages );
3731 break;
3734 // We don't know whether this function was called before
3735 // or after moving the root page, so check both
3736 // $this and $nt
3737 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3738 || $oldSubpage->getArticleID() == $nt->getArticleID()
3740 // When moving a page to a subpage of itself,
3741 // don't move it twice
3742 continue;
3744 $newPageName = preg_replace(
3745 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3746 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3747 $oldSubpage->getDBkey() );
3748 if ( $oldSubpage->isTalkPage() ) {
3749 $newNs = $nt->getTalkPage()->getNamespace();
3750 } else {
3751 $newNs = $nt->getSubjectPage()->getNamespace();
3753 # Bug 14385: we need makeTitleSafe because the new page names may
3754 # be longer than 255 characters.
3755 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3757 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3758 if ( $success === true ) {
3759 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3760 } else {
3761 $retval[$oldSubpage->getPrefixedText()] = $success;
3764 return $retval;
3768 * Checks if this page is just a one-rev redirect.
3769 * Adds lock, so don't use just for light purposes.
3771 * @return bool
3773 public function isSingleRevRedirect() {
3774 global $wgContentHandlerUseDB;
3776 $dbw = wfGetDB( DB_MASTER );
3778 # Is it a redirect?
3779 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3780 if ( $wgContentHandlerUseDB ) {
3781 $fields[] = 'page_content_model';
3784 $row = $dbw->selectRow( 'page',
3785 $fields,
3786 $this->pageCond(),
3787 __METHOD__,
3788 array( 'FOR UPDATE' )
3790 # Cache some fields we may want
3791 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3792 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3793 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3794 $this->mContentModel = $row && isset( $row->page_content_model )
3795 ? strval( $row->page_content_model )
3796 : false;
3798 if ( !$this->mRedirect ) {
3799 return false;
3801 # Does the article have a history?
3802 $row = $dbw->selectField( array( 'page', 'revision' ),
3803 'rev_id',
3804 array( 'page_namespace' => $this->getNamespace(),
3805 'page_title' => $this->getDBkey(),
3806 'page_id=rev_page',
3807 'page_latest != rev_id'
3809 __METHOD__,
3810 array( 'FOR UPDATE' )
3812 # Return true if there was no history
3813 return ( $row === false );
3817 * Checks if $this can be moved to a given Title
3818 * - Selects for update, so don't call it unless you mean business
3820 * @deprecated since 1.25, use MovePage's methods instead
3821 * @param Title $nt The new title to check
3822 * @return bool
3824 public function isValidMoveTarget( $nt ) {
3825 # Is it an existing file?
3826 if ( $nt->getNamespace() == NS_FILE ) {
3827 $file = wfLocalFile( $nt );
3828 $file->load( File::READ_LATEST );
3829 if ( $file->exists() ) {
3830 wfDebug( __METHOD__ . ": file exists\n" );
3831 return false;
3834 # Is it a redirect with no history?
3835 if ( !$nt->isSingleRevRedirect() ) {
3836 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3837 return false;
3839 # Get the article text
3840 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3841 if ( !is_object( $rev ) ) {
3842 return false;
3844 $content = $rev->getContent();
3845 # Does the redirect point to the source?
3846 # Or is it a broken self-redirect, usually caused by namespace collisions?
3847 $redirTitle = $content ? $content->getRedirectTarget() : null;
3849 if ( $redirTitle ) {
3850 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3851 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3852 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3853 return false;
3854 } else {
3855 return true;
3857 } else {
3858 # Fail safe (not a redirect after all. strange.)
3859 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3860 " is a redirect, but it doesn't contain a valid redirect.\n" );
3861 return false;
3866 * Get categories to which this Title belongs and return an array of
3867 * categories' names.
3869 * @return array Array of parents in the form:
3870 * $parent => $currentarticle
3872 public function getParentCategories() {
3873 global $wgContLang;
3875 $data = array();
3877 $titleKey = $this->getArticleID();
3879 if ( $titleKey === 0 ) {
3880 return $data;
3883 $dbr = wfGetDB( DB_SLAVE );
3885 $res = $dbr->select(
3886 'categorylinks',
3887 'cl_to',
3888 array( 'cl_from' => $titleKey ),
3889 __METHOD__
3892 if ( $res->numRows() > 0 ) {
3893 foreach ( $res as $row ) {
3894 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3895 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3898 return $data;
3902 * Get a tree of parent categories
3904 * @param array $children Array with the children in the keys, to check for circular refs
3905 * @return array Tree of parent categories
3907 public function getParentCategoryTree( $children = array() ) {
3908 $stack = array();
3909 $parents = $this->getParentCategories();
3911 if ( $parents ) {
3912 foreach ( $parents as $parent => $current ) {
3913 if ( array_key_exists( $parent, $children ) ) {
3914 # Circular reference
3915 $stack[$parent] = array();
3916 } else {
3917 $nt = Title::newFromText( $parent );
3918 if ( $nt ) {
3919 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3925 return $stack;
3929 * Get an associative array for selecting this title from
3930 * the "page" table
3932 * @return array Array suitable for the $where parameter of DB::select()
3934 public function pageCond() {
3935 if ( $this->mArticleID > 0 ) {
3936 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3937 return array( 'page_id' => $this->mArticleID );
3938 } else {
3939 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3944 * Get the revision ID of the previous revision
3946 * @param int $revId Revision ID. Get the revision that was before this one.
3947 * @param int $flags Title::GAID_FOR_UPDATE
3948 * @return int|bool Old revision ID, or false if none exists
3950 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3951 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3952 $revId = $db->selectField( 'revision', 'rev_id',
3953 array(
3954 'rev_page' => $this->getArticleID( $flags ),
3955 'rev_id < ' . intval( $revId )
3957 __METHOD__,
3958 array( 'ORDER BY' => 'rev_id DESC' )
3961 if ( $revId === false ) {
3962 return false;
3963 } else {
3964 return intval( $revId );
3969 * Get the revision ID of the next revision
3971 * @param int $revId Revision ID. Get the revision that was after this one.
3972 * @param int $flags Title::GAID_FOR_UPDATE
3973 * @return int|bool Next revision ID, or false if none exists
3975 public function getNextRevisionID( $revId, $flags = 0 ) {
3976 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3977 $revId = $db->selectField( 'revision', 'rev_id',
3978 array(
3979 'rev_page' => $this->getArticleID( $flags ),
3980 'rev_id > ' . intval( $revId )
3982 __METHOD__,
3983 array( 'ORDER BY' => 'rev_id' )
3986 if ( $revId === false ) {
3987 return false;
3988 } else {
3989 return intval( $revId );
3994 * Get the first revision of the page
3996 * @param int $flags Title::GAID_FOR_UPDATE
3997 * @return Revision|null If page doesn't exist
3999 public function getFirstRevision( $flags = 0 ) {
4000 $pageId = $this->getArticleID( $flags );
4001 if ( $pageId ) {
4002 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4003 $row = $db->selectRow( 'revision', Revision::selectFields(),
4004 array( 'rev_page' => $pageId ),
4005 __METHOD__,
4006 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4008 if ( $row ) {
4009 return new Revision( $row );
4012 return null;
4016 * Get the oldest revision timestamp of this page
4018 * @param int $flags Title::GAID_FOR_UPDATE
4019 * @return string MW timestamp
4021 public function getEarliestRevTime( $flags = 0 ) {
4022 $rev = $this->getFirstRevision( $flags );
4023 return $rev ? $rev->getTimestamp() : null;
4027 * Check if this is a new page
4029 * @return bool
4031 public function isNewPage() {
4032 $dbr = wfGetDB( DB_SLAVE );
4033 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4037 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4039 * @return bool
4041 public function isBigDeletion() {
4042 global $wgDeleteRevisionsLimit;
4044 if ( !$wgDeleteRevisionsLimit ) {
4045 return false;
4048 if ( $this->mIsBigDeletion === null ) {
4049 $dbr = wfGetDB( DB_SLAVE );
4051 $revCount = $dbr->selectRowCount(
4052 'revision',
4053 '1',
4054 array( 'rev_page' => $this->getArticleID() ),
4055 __METHOD__,
4056 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4059 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4062 return $this->mIsBigDeletion;
4066 * Get the approximate revision count of this page.
4068 * @return int
4070 public function estimateRevisionCount() {
4071 if ( !$this->exists() ) {
4072 return 0;
4075 if ( $this->mEstimateRevisions === null ) {
4076 $dbr = wfGetDB( DB_SLAVE );
4077 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4078 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4081 return $this->mEstimateRevisions;
4085 * Get the number of revisions between the given revision.
4086 * Used for diffs and other things that really need it.
4088 * @param int|Revision $old Old revision or rev ID (first before range)
4089 * @param int|Revision $new New revision or rev ID (first after range)
4090 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4091 * @return int Number of revisions between these revisions.
4093 public function countRevisionsBetween( $old, $new, $max = null ) {
4094 if ( !( $old instanceof Revision ) ) {
4095 $old = Revision::newFromTitle( $this, (int)$old );
4097 if ( !( $new instanceof Revision ) ) {
4098 $new = Revision::newFromTitle( $this, (int)$new );
4100 if ( !$old || !$new ) {
4101 return 0; // nothing to compare
4103 $dbr = wfGetDB( DB_SLAVE );
4104 $conds = array(
4105 'rev_page' => $this->getArticleID(),
4106 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4107 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4109 if ( $max !== null ) {
4110 return $dbr->selectRowCount( 'revision', '1',
4111 $conds,
4112 __METHOD__,
4113 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4115 } else {
4116 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4121 * Get the authors between the given revisions or revision IDs.
4122 * Used for diffs and other things that really need it.
4124 * @since 1.23
4126 * @param int|Revision $old Old revision or rev ID (first before range by default)
4127 * @param int|Revision $new New revision or rev ID (first after range by default)
4128 * @param int $limit Maximum number of authors
4129 * @param string|array $options (Optional): Single option, or an array of options:
4130 * 'include_old' Include $old in the range; $new is excluded.
4131 * 'include_new' Include $new in the range; $old is excluded.
4132 * 'include_both' Include both $old and $new in the range.
4133 * Unknown option values are ignored.
4134 * @return array|null Names of revision authors in the range; null if not both revisions exist
4136 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4137 if ( !( $old instanceof Revision ) ) {
4138 $old = Revision::newFromTitle( $this, (int)$old );
4140 if ( !( $new instanceof Revision ) ) {
4141 $new = Revision::newFromTitle( $this, (int)$new );
4143 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4144 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4145 // in the sanity check below?
4146 if ( !$old || !$new ) {
4147 return null; // nothing to compare
4149 $authors = array();
4150 $old_cmp = '>';
4151 $new_cmp = '<';
4152 $options = (array)$options;
4153 if ( in_array( 'include_old', $options ) ) {
4154 $old_cmp = '>=';
4156 if ( in_array( 'include_new', $options ) ) {
4157 $new_cmp = '<=';
4159 if ( in_array( 'include_both', $options ) ) {
4160 $old_cmp = '>=';
4161 $new_cmp = '<=';
4163 // No DB query needed if $old and $new are the same or successive revisions:
4164 if ( $old->getId() === $new->getId() ) {
4165 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4166 array() :
4167 array( $old->getUserText( Revision::RAW ) );
4168 } elseif ( $old->getId() === $new->getParentId() ) {
4169 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4170 $authors[] = $old->getUserText( Revision::RAW );
4171 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4172 $authors[] = $new->getUserText( Revision::RAW );
4174 } elseif ( $old_cmp === '>=' ) {
4175 $authors[] = $old->getUserText( Revision::RAW );
4176 } elseif ( $new_cmp === '<=' ) {
4177 $authors[] = $new->getUserText( Revision::RAW );
4179 return $authors;
4181 $dbr = wfGetDB( DB_SLAVE );
4182 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4183 array(
4184 'rev_page' => $this->getArticleID(),
4185 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4186 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4187 ), __METHOD__,
4188 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4190 foreach ( $res as $row ) {
4191 $authors[] = $row->rev_user_text;
4193 return $authors;
4197 * Get the number of authors between the given revisions or revision IDs.
4198 * Used for diffs and other things that really need it.
4200 * @param int|Revision $old Old revision or rev ID (first before range by default)
4201 * @param int|Revision $new New revision or rev ID (first after range by default)
4202 * @param int $limit Maximum number of authors
4203 * @param string|array $options (Optional): Single option, or an array of options:
4204 * 'include_old' Include $old in the range; $new is excluded.
4205 * 'include_new' Include $new in the range; $old is excluded.
4206 * 'include_both' Include both $old and $new in the range.
4207 * Unknown option values are ignored.
4208 * @return int Number of revision authors in the range; zero if not both revisions exist
4210 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4211 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4212 return $authors ? count( $authors ) : 0;
4216 * Compare with another title.
4218 * @param Title $title
4219 * @return bool
4221 public function equals( Title $title ) {
4222 // Note: === is necessary for proper matching of number-like titles.
4223 return $this->getInterwiki() === $title->getInterwiki()
4224 && $this->getNamespace() == $title->getNamespace()
4225 && $this->getDBkey() === $title->getDBkey();
4229 * Check if this title is a subpage of another title
4231 * @param Title $title
4232 * @return bool
4234 public function isSubpageOf( Title $title ) {
4235 return $this->getInterwiki() === $title->getInterwiki()
4236 && $this->getNamespace() == $title->getNamespace()
4237 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4241 * Check if page exists. For historical reasons, this function simply
4242 * checks for the existence of the title in the page table, and will
4243 * thus return false for interwiki links, special pages and the like.
4244 * If you want to know if a title can be meaningfully viewed, you should
4245 * probably call the isKnown() method instead.
4247 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4248 * from master/for update
4249 * @return bool
4251 public function exists( $flags = 0 ) {
4252 $exists = $this->getArticleID( $flags ) != 0;
4253 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4254 return $exists;
4258 * Should links to this title be shown as potentially viewable (i.e. as
4259 * "bluelinks"), even if there's no record by this title in the page
4260 * table?
4262 * This function is semi-deprecated for public use, as well as somewhat
4263 * misleadingly named. You probably just want to call isKnown(), which
4264 * calls this function internally.
4266 * (ISSUE: Most of these checks are cheap, but the file existence check
4267 * can potentially be quite expensive. Including it here fixes a lot of
4268 * existing code, but we might want to add an optional parameter to skip
4269 * it and any other expensive checks.)
4271 * @return bool
4273 public function isAlwaysKnown() {
4274 $isKnown = null;
4277 * Allows overriding default behavior for determining if a page exists.
4278 * If $isKnown is kept as null, regular checks happen. If it's
4279 * a boolean, this value is returned by the isKnown method.
4281 * @since 1.20
4283 * @param Title $title
4284 * @param bool|null $isKnown
4286 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4288 if ( !is_null( $isKnown ) ) {
4289 return $isKnown;
4292 if ( $this->isExternal() ) {
4293 return true; // any interwiki link might be viewable, for all we know
4296 switch ( $this->mNamespace ) {
4297 case NS_MEDIA:
4298 case NS_FILE:
4299 // file exists, possibly in a foreign repo
4300 return (bool)wfFindFile( $this );
4301 case NS_SPECIAL:
4302 // valid special page
4303 return SpecialPageFactory::exists( $this->getDBkey() );
4304 case NS_MAIN:
4305 // selflink, possibly with fragment
4306 return $this->mDbkeyform == '';
4307 case NS_MEDIAWIKI:
4308 // known system message
4309 return $this->hasSourceText() !== false;
4310 default:
4311 return false;
4316 * Does this title refer to a page that can (or might) be meaningfully
4317 * viewed? In particular, this function may be used to determine if
4318 * links to the title should be rendered as "bluelinks" (as opposed to
4319 * "redlinks" to non-existent pages).
4320 * Adding something else to this function will cause inconsistency
4321 * since LinkHolderArray calls isAlwaysKnown() and does its own
4322 * page existence check.
4324 * @return bool
4326 public function isKnown() {
4327 return $this->isAlwaysKnown() || $this->exists();
4331 * Does this page have source text?
4333 * @return bool
4335 public function hasSourceText() {
4336 if ( $this->exists() ) {
4337 return true;
4340 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4341 // If the page doesn't exist but is a known system message, default
4342 // message content will be displayed, same for language subpages-
4343 // Use always content language to avoid loading hundreds of languages
4344 // to get the link color.
4345 global $wgContLang;
4346 list( $name, ) = MessageCache::singleton()->figureMessage(
4347 $wgContLang->lcfirst( $this->getText() )
4349 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4350 return $message->exists();
4353 return false;
4357 * Get the default message text or false if the message doesn't exist
4359 * @return string|bool
4361 public function getDefaultMessageText() {
4362 global $wgContLang;
4364 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4365 return false;
4368 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4369 $wgContLang->lcfirst( $this->getText() )
4371 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4373 if ( $message->exists() ) {
4374 return $message->plain();
4375 } else {
4376 return false;
4381 * Updates page_touched for this page; called from LinksUpdate.php
4383 * @param integer $purgeTime TS_MW timestamp [optional]
4384 * @return bool True if the update succeeded
4386 public function invalidateCache( $purgeTime = null ) {
4387 if ( wfReadOnly() ) {
4388 return false;
4391 if ( $this->mArticleID === 0 ) {
4392 return true; // avoid gap locking if we know it's not there
4395 $method = __METHOD__;
4396 $dbw = wfGetDB( DB_MASTER );
4397 $conds = $this->pageCond();
4398 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4399 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4401 $dbw->update(
4402 'page',
4403 array( 'page_touched' => $dbTimestamp ),
4404 $conds + array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4405 $method
4407 } );
4409 return true;
4413 * Update page_touched timestamps and send squid purge messages for
4414 * pages linking to this title. May be sent to the job queue depending
4415 * on the number of links. Typically called on create and delete.
4417 public function touchLinks() {
4418 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4419 $u->doUpdate();
4421 if ( $this->getNamespace() == NS_CATEGORY ) {
4422 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4423 $u->doUpdate();
4428 * Get the last touched timestamp
4430 * @param DatabaseBase $db Optional db
4431 * @return string Last-touched timestamp
4433 public function getTouched( $db = null ) {
4434 if ( $db === null ) {
4435 $db = wfGetDB( DB_SLAVE );
4437 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4438 return $touched;
4442 * Get the timestamp when this page was updated since the user last saw it.
4444 * @param User $user
4445 * @return string|null
4447 public function getNotificationTimestamp( $user = null ) {
4448 global $wgUser;
4450 // Assume current user if none given
4451 if ( !$user ) {
4452 $user = $wgUser;
4454 // Check cache first
4455 $uid = $user->getId();
4456 if ( !$uid ) {
4457 return false;
4459 // avoid isset here, as it'll return false for null entries
4460 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4461 return $this->mNotificationTimestamp[$uid];
4463 // Don't cache too much!
4464 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4465 $this->mNotificationTimestamp = array();
4468 $watchedItem = WatchedItem::fromUserTitle( $user, $this );
4469 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4471 return $this->mNotificationTimestamp[$uid];
4475 * Generate strings used for xml 'id' names in monobook tabs
4477 * @param string $prepend Defaults to 'nstab-'
4478 * @return string XML 'id' name
4480 public function getNamespaceKey( $prepend = 'nstab-' ) {
4481 global $wgContLang;
4482 // Gets the subject namespace if this title
4483 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4484 // Checks if canonical namespace name exists for namespace
4485 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4486 // Uses canonical namespace name
4487 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4488 } else {
4489 // Uses text of namespace
4490 $namespaceKey = $this->getSubjectNsText();
4492 // Makes namespace key lowercase
4493 $namespaceKey = $wgContLang->lc( $namespaceKey );
4494 // Uses main
4495 if ( $namespaceKey == '' ) {
4496 $namespaceKey = 'main';
4498 // Changes file to image for backwards compatibility
4499 if ( $namespaceKey == 'file' ) {
4500 $namespaceKey = 'image';
4502 return $prepend . $namespaceKey;
4506 * Get all extant redirects to this Title
4508 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4509 * @return Title[] Array of Title redirects to this title
4511 public function getRedirectsHere( $ns = null ) {
4512 $redirs = array();
4514 $dbr = wfGetDB( DB_SLAVE );
4515 $where = array(
4516 'rd_namespace' => $this->getNamespace(),
4517 'rd_title' => $this->getDBkey(),
4518 'rd_from = page_id'
4520 if ( $this->isExternal() ) {
4521 $where['rd_interwiki'] = $this->getInterwiki();
4522 } else {
4523 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4525 if ( !is_null( $ns ) ) {
4526 $where['page_namespace'] = $ns;
4529 $res = $dbr->select(
4530 array( 'redirect', 'page' ),
4531 array( 'page_namespace', 'page_title' ),
4532 $where,
4533 __METHOD__
4536 foreach ( $res as $row ) {
4537 $redirs[] = self::newFromRow( $row );
4539 return $redirs;
4543 * Check if this Title is a valid redirect target
4545 * @return bool
4547 public function isValidRedirectTarget() {
4548 global $wgInvalidRedirectTargets;
4550 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4551 if ( $this->isSpecial( 'Userlogout' ) ) {
4552 return false;
4555 foreach ( $wgInvalidRedirectTargets as $target ) {
4556 if ( $this->isSpecial( $target ) ) {
4557 return false;
4561 return true;
4565 * Get a backlink cache object
4567 * @return BacklinkCache
4569 public function getBacklinkCache() {
4570 return BacklinkCache::get( $this );
4574 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4576 * @return bool
4578 public function canUseNoindex() {
4579 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4581 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4582 ? $wgContentNamespaces
4583 : $wgExemptFromUserRobotsControl;
4585 return !in_array( $this->mNamespace, $bannedNamespaces );
4590 * Returns the raw sort key to be used for categories, with the specified
4591 * prefix. This will be fed to Collation::getSortKey() to get a
4592 * binary sortkey that can be used for actual sorting.
4594 * @param string $prefix The prefix to be used, specified using
4595 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4596 * prefix.
4597 * @return string
4599 public function getCategorySortkey( $prefix = '' ) {
4600 $unprefixed = $this->getText();
4602 // Anything that uses this hook should only depend
4603 // on the Title object passed in, and should probably
4604 // tell the users to run updateCollations.php --force
4605 // in order to re-sort existing category relations.
4606 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4607 if ( $prefix !== '' ) {
4608 # Separate with a line feed, so the unprefixed part is only used as
4609 # a tiebreaker when two pages have the exact same prefix.
4610 # In UCA, tab is the only character that can sort above LF
4611 # so we strip both of them from the original prefix.
4612 $prefix = strtr( $prefix, "\n\t", ' ' );
4613 return "$prefix\n$unprefixed";
4615 return $unprefixed;
4619 * Get the language in which the content of this page is written in
4620 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4621 * e.g. $wgLang (such as special pages, which are in the user language).
4623 * @since 1.18
4624 * @return Language
4626 public function getPageLanguage() {
4627 global $wgLang, $wgLanguageCode;
4628 if ( $this->isSpecialPage() ) {
4629 // special pages are in the user language
4630 return $wgLang;
4633 // Checking if DB language is set
4634 if ( $this->mDbPageLanguage ) {
4635 return wfGetLangObj( $this->mDbPageLanguage );
4638 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4639 // Note that this may depend on user settings, so the cache should
4640 // be only per-request.
4641 // NOTE: ContentHandler::getPageLanguage() may need to load the
4642 // content to determine the page language!
4643 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4644 // tests.
4645 $contentHandler = ContentHandler::getForTitle( $this );
4646 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4647 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4648 } else {
4649 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4652 return $langObj;
4656 * Get the language in which the content of this page is written when
4657 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4658 * e.g. $wgLang (such as special pages, which are in the user language).
4660 * @since 1.20
4661 * @return Language
4663 public function getPageViewLanguage() {
4664 global $wgLang;
4666 if ( $this->isSpecialPage() ) {
4667 // If the user chooses a variant, the content is actually
4668 // in a language whose code is the variant code.
4669 $variant = $wgLang->getPreferredVariant();
4670 if ( $wgLang->getCode() !== $variant ) {
4671 return Language::factory( $variant );
4674 return $wgLang;
4677 // @note Can't be cached persistently, depends on user settings.
4678 // @note ContentHandler::getPageViewLanguage() may need to load the
4679 // content to determine the page language!
4680 $contentHandler = ContentHandler::getForTitle( $this );
4681 $pageLang = $contentHandler->getPageViewLanguage( $this );
4682 return $pageLang;
4686 * Get a list of rendered edit notices for this page.
4688 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4689 * they will already be wrapped in paragraphs.
4691 * @since 1.21
4692 * @param int $oldid Revision ID that's being edited
4693 * @return array
4695 public function getEditNotices( $oldid = 0 ) {
4696 $notices = array();
4698 // Optional notice for the entire namespace
4699 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4700 $msg = wfMessage( $editnotice_ns );
4701 if ( $msg->exists() ) {
4702 $html = $msg->parseAsBlock();
4703 // Edit notices may have complex logic, but output nothing (T91715)
4704 if ( trim( $html ) !== '' ) {
4705 $notices[$editnotice_ns] = Html::rawElement(
4706 'div',
4707 array( 'class' => array(
4708 'mw-editnotice',
4709 'mw-editnotice-namespace',
4710 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4711 ) ),
4712 $html
4717 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4718 // Optional notice for page itself and any parent page
4719 $parts = explode( '/', $this->getDBkey() );
4720 $editnotice_base = $editnotice_ns;
4721 while ( count( $parts ) > 0 ) {
4722 $editnotice_base .= '-' . array_shift( $parts );
4723 $msg = wfMessage( $editnotice_base );
4724 if ( $msg->exists() ) {
4725 $html = $msg->parseAsBlock();
4726 if ( trim( $html ) !== '' ) {
4727 $notices[$editnotice_base] = Html::rawElement(
4728 'div',
4729 array( 'class' => array(
4730 'mw-editnotice',
4731 'mw-editnotice-base',
4732 Sanitizer::escapeClass( "mw-$editnotice_base" )
4733 ) ),
4734 $html
4739 } else {
4740 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4741 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4742 $msg = wfMessage( $editnoticeText );
4743 if ( $msg->exists() ) {
4744 $html = $msg->parseAsBlock();
4745 if ( trim( $html ) !== '' ) {
4746 $notices[$editnoticeText] = Html::rawElement(
4747 'div',
4748 array( 'class' => array(
4749 'mw-editnotice',
4750 'mw-editnotice-page',
4751 Sanitizer::escapeClass( "mw-$editnoticeText" )
4752 ) ),
4753 $html
4759 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4760 return $notices;
4764 * @return array
4766 public function __sleep() {
4767 return array(
4768 'mNamespace',
4769 'mDbkeyform',
4770 'mFragment',
4771 'mInterwiki',
4772 'mLocalInterwiki',
4773 'mUserCaseDBKey',
4774 'mDefaultNamespace',
4778 public function __wakeup() {
4779 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4780 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4781 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );