resourceloader: Add @covers and minor clean up of test suites
[mediawiki.git] / includes / Title.php
blob921538b2871ddaaad6d13b83a651f8570504cafd
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 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;
228 if ( $t->secureAndSplit() ) {
229 return $t;
230 } else {
231 return null;
236 * Create a new Title from a TitleValue
238 * @param TitleValue $titleValue Assumed to be safe.
240 * @return Title
242 public static function newFromTitleValue( TitleValue $titleValue ) {
243 return self::makeTitle(
244 $titleValue->getNamespace(),
245 $titleValue->getText(),
246 $titleValue->getFragment() );
250 * Create a new Title from text, such as what one would find in a link. De-
251 * codes any HTML entities in the text.
253 * @param string $text The link text; spaces, prefixes, and an
254 * initial ':' indicating the main namespace are accepted.
255 * @param int $defaultNamespace The namespace to use if none is specified
256 * by a prefix. If you want to force a specific namespace even if
257 * $text might begin with a namespace prefix, use makeTitle() or
258 * makeTitleSafe().
259 * @throws MWException
260 * @return Title|null Title or null on an error.
262 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
263 if ( is_object( $text ) ) {
264 throw new MWException( 'Title::newFromText given an object' );
267 $cache = self::getTitleCache();
270 * Wiki pages often contain multiple links to the same page.
271 * Title normalization and parsing can become expensive on
272 * pages with many links, so we can save a little time by
273 * caching them.
275 * In theory these are value objects and won't get changed...
277 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
278 return $cache->get( $text );
281 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
282 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
284 $t = new Title();
285 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
286 $t->mDefaultNamespace = intval( $defaultNamespace );
288 if ( $t->secureAndSplit() ) {
289 if ( $defaultNamespace == NS_MAIN ) {
290 $cache->set( $text, $t );
292 return $t;
293 } else {
294 return null;
299 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
301 * Example of wrong and broken code:
302 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
304 * Example of right code:
305 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
307 * Create a new Title from URL-encoded text. Ensures that
308 * the given title's length does not exceed the maximum.
310 * @param string $url The title, as might be taken from a URL
311 * @return Title|null The new object, or null on an error
313 public static function newFromURL( $url ) {
314 $t = new Title();
316 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
317 # but some URLs used it as a space replacement and they still come
318 # from some external search tools.
319 if ( strpos( self::legalChars(), '+' ) === false ) {
320 $url = str_replace( '+', ' ', $url );
323 $t->mDbkeyform = str_replace( ' ', '_', $url );
324 if ( $t->secureAndSplit() ) {
325 return $t;
326 } else {
327 return null;
332 * @return MapCacheLRU
334 private static function getTitleCache() {
335 if ( self::$titleCache == null ) {
336 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
338 return self::$titleCache;
342 * Returns a list of fields that are to be selected for initializing Title
343 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
344 * whether to include page_content_model.
346 * @return array
348 protected static function getSelectFields() {
349 global $wgContentHandlerUseDB;
351 $fields = array(
352 'page_namespace', 'page_title', 'page_id',
353 'page_len', 'page_is_redirect', 'page_latest',
356 if ( $wgContentHandlerUseDB ) {
357 $fields[] = 'page_content_model';
360 return $fields;
364 * Create a new Title from an article ID
366 * @param int $id The page_id corresponding to the Title to create
367 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
368 * @return Title|null The new object, or null on an error
370 public static function newFromID( $id, $flags = 0 ) {
371 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
372 $row = $db->selectRow(
373 'page',
374 self::getSelectFields(),
375 array( 'page_id' => $id ),
376 __METHOD__
378 if ( $row !== false ) {
379 $title = Title::newFromRow( $row );
380 } else {
381 $title = null;
383 return $title;
387 * Make an array of titles from an array of IDs
389 * @param int[] $ids Array of IDs
390 * @return Title[] Array of Titles
392 public static function newFromIDs( $ids ) {
393 if ( !count( $ids ) ) {
394 return array();
396 $dbr = wfGetDB( DB_SLAVE );
398 $res = $dbr->select(
399 'page',
400 self::getSelectFields(),
401 array( 'page_id' => $ids ),
402 __METHOD__
405 $titles = array();
406 foreach ( $res as $row ) {
407 $titles[] = Title::newFromRow( $row );
409 return $titles;
413 * Make a Title object from a DB row
415 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
416 * @return Title Corresponding Title
418 public static function newFromRow( $row ) {
419 $t = self::makeTitle( $row->page_namespace, $row->page_title );
420 $t->loadFromRow( $row );
421 return $t;
425 * Load Title object fields from a DB row.
426 * If false is given, the title will be treated as non-existing.
428 * @param stdClass|bool $row Database row
430 public function loadFromRow( $row ) {
431 if ( $row ) { // page found
432 if ( isset( $row->page_id ) ) {
433 $this->mArticleID = (int)$row->page_id;
435 if ( isset( $row->page_len ) ) {
436 $this->mLength = (int)$row->page_len;
438 if ( isset( $row->page_is_redirect ) ) {
439 $this->mRedirect = (bool)$row->page_is_redirect;
441 if ( isset( $row->page_latest ) ) {
442 $this->mLatestID = (int)$row->page_latest;
444 if ( isset( $row->page_content_model ) ) {
445 $this->mContentModel = strval( $row->page_content_model );
446 } else {
447 $this->mContentModel = false; # initialized lazily in getContentModel()
449 if ( isset( $row->page_lang ) ) {
450 $this->mDbPageLanguage = (string)$row->page_lang;
452 } else { // page not found
453 $this->mArticleID = 0;
454 $this->mLength = 0;
455 $this->mRedirect = false;
456 $this->mLatestID = 0;
457 $this->mContentModel = false; # initialized lazily in getContentModel()
462 * Create a new Title from a namespace index and a DB key.
463 * It's assumed that $ns and $title are *valid*, for instance when
464 * they came directly from the database or a special page name.
465 * For convenience, spaces are converted to underscores so that
466 * eg user_text fields can be used directly.
468 * @param int $ns The namespace of the article
469 * @param string $title The unprefixed database key form
470 * @param string $fragment The link fragment (after the "#")
471 * @param string $interwiki The interwiki prefix
472 * @return Title The new object
474 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
475 $t = new Title();
476 $t->mInterwiki = $interwiki;
477 $t->mFragment = $fragment;
478 $t->mNamespace = $ns = intval( $ns );
479 $t->mDbkeyform = str_replace( ' ', '_', $title );
480 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
481 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
482 $t->mTextform = str_replace( '_', ' ', $title );
483 $t->mContentModel = false; # initialized lazily in getContentModel()
484 return $t;
488 * Create a new Title from a namespace index and a DB key.
489 * The parameters will be checked for validity, which is a bit slower
490 * than makeTitle() but safer for user-provided data.
492 * @param int $ns The namespace of the article
493 * @param string $title Database key form
494 * @param string $fragment The link fragment (after the "#")
495 * @param string $interwiki Interwiki prefix
496 * @return Title The new object, or null on an error
498 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
499 if ( !MWNamespace::exists( $ns ) ) {
500 return null;
503 $t = new Title();
504 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
505 if ( $t->secureAndSplit() ) {
506 return $t;
507 } else {
508 return null;
513 * Create a new Title for the Main Page
515 * @return Title The new object
517 public static function newMainPage() {
518 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
519 // Don't give fatal errors if the message is broken
520 if ( !$title ) {
521 $title = Title::newFromText( 'Main Page' );
523 return $title;
527 * Extract a redirect destination from a string and return the
528 * Title, or null if the text doesn't contain a valid redirect
529 * This will only return the very next target, useful for
530 * the redirect table and other checks that don't need full recursion
532 * @param string $text Text with possible redirect
533 * @return Title The corresponding Title
534 * @deprecated since 1.21, use Content::getRedirectTarget instead.
536 public static function newFromRedirect( $text ) {
537 ContentHandler::deprecated( __METHOD__, '1.21' );
539 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
540 return $content->getRedirectTarget();
544 * Extract a redirect destination from a string and return the
545 * Title, or null if the text doesn't contain a valid redirect
546 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
547 * in order to provide (hopefully) the Title of the final destination instead of another redirect
549 * @param string $text Text with possible redirect
550 * @return Title
551 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
553 public static function newFromRedirectRecurse( $text ) {
554 ContentHandler::deprecated( __METHOD__, '1.21' );
556 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
557 return $content->getUltimateRedirectTarget();
561 * Extract a redirect destination from a string and return an
562 * array of Titles, or null if the text doesn't contain a valid redirect
563 * The last element in the array is the final destination after all redirects
564 * have been resolved (up to $wgMaxRedirects times)
566 * @param string $text Text with possible redirect
567 * @return Title[] Array of Titles, with the destination last
568 * @deprecated since 1.21, use Content::getRedirectChain instead.
570 public static function newFromRedirectArray( $text ) {
571 ContentHandler::deprecated( __METHOD__, '1.21' );
573 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
574 return $content->getRedirectChain();
578 * Get the prefixed DB key associated with an ID
580 * @param int $id The page_id of the article
581 * @return Title|null An object representing the article, or null if no such article was found
583 public static function nameOf( $id ) {
584 $dbr = wfGetDB( DB_SLAVE );
586 $s = $dbr->selectRow(
587 'page',
588 array( 'page_namespace', 'page_title' ),
589 array( 'page_id' => $id ),
590 __METHOD__
592 if ( $s === false ) {
593 return null;
596 $n = self::makeName( $s->page_namespace, $s->page_title );
597 return $n;
601 * Get a regex character class describing the legal characters in a link
603 * @return string The list of characters, not delimited
605 public static function legalChars() {
606 global $wgLegalTitleChars;
607 return $wgLegalTitleChars;
611 * Returns a simple regex that will match on characters and sequences invalid in titles.
612 * Note that this doesn't pick up many things that could be wrong with titles, but that
613 * replacing this regex with something valid will make many titles valid.
615 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
617 * @return string Regex string
619 static function getTitleInvalidRegex() {
620 wfDeprecated( __METHOD__, '1.25' );
621 return MediaWikiTitleCodec::getTitleInvalidRegex();
625 * Utility method for converting a character sequence from bytes to Unicode.
627 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
628 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
630 * @param string $byteClass
631 * @return string
633 public static function convertByteClassToUnicodeClass( $byteClass ) {
634 $length = strlen( $byteClass );
635 // Input token queue
636 $x0 = $x1 = $x2 = '';
637 // Decoded queue
638 $d0 = $d1 = $d2 = '';
639 // Decoded integer codepoints
640 $ord0 = $ord1 = $ord2 = 0;
641 // Re-encoded queue
642 $r0 = $r1 = $r2 = '';
643 // Output
644 $out = '';
645 // Flags
646 $allowUnicode = false;
647 for ( $pos = 0; $pos < $length; $pos++ ) {
648 // Shift the queues down
649 $x2 = $x1;
650 $x1 = $x0;
651 $d2 = $d1;
652 $d1 = $d0;
653 $ord2 = $ord1;
654 $ord1 = $ord0;
655 $r2 = $r1;
656 $r1 = $r0;
657 // Load the current input token and decoded values
658 $inChar = $byteClass[$pos];
659 if ( $inChar == '\\' ) {
660 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
661 $x0 = $inChar . $m[0];
662 $d0 = chr( hexdec( $m[1] ) );
663 $pos += strlen( $m[0] );
664 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
665 $x0 = $inChar . $m[0];
666 $d0 = chr( octdec( $m[0] ) );
667 $pos += strlen( $m[0] );
668 } elseif ( $pos + 1 >= $length ) {
669 $x0 = $d0 = '\\';
670 } else {
671 $d0 = $byteClass[$pos + 1];
672 $x0 = $inChar . $d0;
673 $pos += 1;
675 } else {
676 $x0 = $d0 = $inChar;
678 $ord0 = ord( $d0 );
679 // Load the current re-encoded value
680 if ( $ord0 < 32 || $ord0 == 0x7f ) {
681 $r0 = sprintf( '\x%02x', $ord0 );
682 } elseif ( $ord0 >= 0x80 ) {
683 // Allow unicode if a single high-bit character appears
684 $r0 = sprintf( '\x%02x', $ord0 );
685 $allowUnicode = true;
686 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
687 $r0 = '\\' . $d0;
688 } else {
689 $r0 = $d0;
691 // Do the output
692 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
693 // Range
694 if ( $ord2 > $ord0 ) {
695 // Empty range
696 } elseif ( $ord0 >= 0x80 ) {
697 // Unicode range
698 $allowUnicode = true;
699 if ( $ord2 < 0x80 ) {
700 // Keep the non-unicode section of the range
701 $out .= "$r2-\\x7F";
703 } else {
704 // Normal range
705 $out .= "$r2-$r0";
707 // Reset state to the initial value
708 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
709 } elseif ( $ord2 < 0x80 ) {
710 // ASCII character
711 $out .= $r2;
714 if ( $ord1 < 0x80 ) {
715 $out .= $r1;
717 if ( $ord0 < 0x80 ) {
718 $out .= $r0;
720 if ( $allowUnicode ) {
721 $out .= '\u0080-\uFFFF';
723 return $out;
727 * Make a prefixed DB key from a DB key and a namespace index
729 * @param int $ns Numerical representation of the namespace
730 * @param string $title The DB key form the title
731 * @param string $fragment The link fragment (after the "#")
732 * @param string $interwiki The interwiki prefix
733 * @param bool $canoncialNamespace If true, use the canonical name for
734 * $ns instead of the localized version.
735 * @return string The prefixed form of the title
737 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
738 $canoncialNamespace = false
740 global $wgContLang;
742 if ( $canoncialNamespace ) {
743 $namespace = MWNamespace::getCanonicalName( $ns );
744 } else {
745 $namespace = $wgContLang->getNsText( $ns );
747 $name = $namespace == '' ? $title : "$namespace:$title";
748 if ( strval( $interwiki ) != '' ) {
749 $name = "$interwiki:$name";
751 if ( strval( $fragment ) != '' ) {
752 $name .= '#' . $fragment;
754 return $name;
758 * Escape a text fragment, say from a link, for a URL
760 * @param string $fragment Containing a URL or link fragment (after the "#")
761 * @return string Escaped string
763 static function escapeFragmentForURL( $fragment ) {
764 # Note that we don't urlencode the fragment. urlencoded Unicode
765 # fragments appear not to work in IE (at least up to 7) or in at least
766 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
767 # to care if they aren't encoded.
768 return Sanitizer::escapeId( $fragment, 'noninitial' );
772 * Callback for usort() to do title sorts by (namespace, title)
774 * @param Title $a
775 * @param Title $b
777 * @return int Result of string comparison, or namespace comparison
779 public static function compare( $a, $b ) {
780 if ( $a->getNamespace() == $b->getNamespace() ) {
781 return strcmp( $a->getText(), $b->getText() );
782 } else {
783 return $a->getNamespace() - $b->getNamespace();
788 * Determine whether the object refers to a page within
789 * this project (either this wiki or a wiki with a local
790 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
792 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
794 public function isLocal() {
795 if ( $this->isExternal() ) {
796 $iw = Interwiki::fetch( $this->mInterwiki );
797 if ( $iw ) {
798 return $iw->isLocal();
801 return true;
805 * Is this Title interwiki?
807 * @return bool
809 public function isExternal() {
810 return $this->mInterwiki !== '';
814 * Get the interwiki prefix
816 * Use Title::isExternal to check if a interwiki is set
818 * @return string Interwiki prefix
820 public function getInterwiki() {
821 return $this->mInterwiki;
825 * Was this a local interwiki link?
827 * @return bool
829 public function wasLocalInterwiki() {
830 return $this->mLocalInterwiki;
834 * Determine whether the object refers to a page within
835 * this project and is transcludable.
837 * @return bool True if this is transcludable
839 public function isTrans() {
840 if ( !$this->isExternal() ) {
841 return false;
844 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
848 * Returns the DB name of the distant wiki which owns the object.
850 * @return string The DB name
852 public function getTransWikiID() {
853 if ( !$this->isExternal() ) {
854 return false;
857 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
861 * Get a TitleValue object representing this Title.
863 * @note Not all valid Titles have a corresponding valid TitleValue
864 * (e.g. TitleValues cannot represent page-local links that have a
865 * fragment but no title text).
867 * @return TitleValue|null
869 public function getTitleValue() {
870 if ( $this->mTitleValue === null ) {
871 try {
872 $this->mTitleValue = new TitleValue(
873 $this->getNamespace(),
874 $this->getDBkey(),
875 $this->getFragment() );
876 } catch ( InvalidArgumentException $ex ) {
877 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
878 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
882 return $this->mTitleValue;
886 * Get the text form (spaces not underscores) of the main part
888 * @return string Main part of the title
890 public function getText() {
891 return $this->mTextform;
895 * Get the URL-encoded form of the main part
897 * @return string Main part of the title, URL-encoded
899 public function getPartialURL() {
900 return $this->mUrlform;
904 * Get the main part with underscores
906 * @return string Main part of the title, with underscores
908 public function getDBkey() {
909 return $this->mDbkeyform;
913 * Get the DB key with the initial letter case as specified by the user
915 * @return string DB key
917 function getUserCaseDBKey() {
918 if ( !is_null( $this->mUserCaseDBKey ) ) {
919 return $this->mUserCaseDBKey;
920 } else {
921 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
922 return $this->mDbkeyform;
927 * Get the namespace index, i.e. one of the NS_xxxx constants.
929 * @return int Namespace index
931 public function getNamespace() {
932 return $this->mNamespace;
936 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
938 * @throws MWException
939 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
940 * @return string Content model id
942 public function getContentModel( $flags = 0 ) {
943 if ( !$this->mContentModel && $this->getArticleID( $flags ) ) {
944 $linkCache = LinkCache::singleton();
945 $linkCache->addLinkObj( $this ); # in case we already had an article ID
946 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
949 if ( !$this->mContentModel ) {
950 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
953 if ( !$this->mContentModel ) {
954 throw new MWException( 'Failed to determine content model!' );
957 return $this->mContentModel;
961 * Convenience method for checking a title's content model name
963 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
964 * @return bool True if $this->getContentModel() == $id
966 public function hasContentModel( $id ) {
967 return $this->getContentModel() == $id;
971 * Get the namespace text
973 * @return string Namespace text
975 public function getNsText() {
976 if ( $this->isExternal() ) {
977 // This probably shouldn't even happen. ohh man, oh yuck.
978 // But for interwiki transclusion it sometimes does.
979 // Shit. Shit shit shit.
981 // Use the canonical namespaces if possible to try to
982 // resolve a foreign namespace.
983 if ( MWNamespace::exists( $this->mNamespace ) ) {
984 return MWNamespace::getCanonicalName( $this->mNamespace );
988 try {
989 $formatter = self::getTitleFormatter();
990 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
991 } catch ( InvalidArgumentException $ex ) {
992 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
993 return false;
998 * Get the namespace text of the subject (rather than talk) page
1000 * @return string Namespace text
1002 public function getSubjectNsText() {
1003 global $wgContLang;
1004 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1008 * Get the namespace text of the talk page
1010 * @return string Namespace text
1012 public function getTalkNsText() {
1013 global $wgContLang;
1014 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1018 * Could this title have a corresponding talk page?
1020 * @return bool
1022 public function canTalk() {
1023 return MWNamespace::canTalk( $this->mNamespace );
1027 * Is this in a namespace that allows actual pages?
1029 * @return bool
1031 public function canExist() {
1032 return $this->mNamespace >= NS_MAIN;
1036 * Can this title be added to a user's watchlist?
1038 * @return bool
1040 public function isWatchable() {
1041 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1045 * Returns true if this is a special page.
1047 * @return bool
1049 public function isSpecialPage() {
1050 return $this->getNamespace() == NS_SPECIAL;
1054 * Returns true if this title resolves to the named special page
1056 * @param string $name The special page name
1057 * @return bool
1059 public function isSpecial( $name ) {
1060 if ( $this->isSpecialPage() ) {
1061 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1062 if ( $name == $thisName ) {
1063 return true;
1066 return false;
1070 * If the Title refers to a special page alias which is not the local default, resolve
1071 * the alias, and localise the name as necessary. Otherwise, return $this
1073 * @return Title
1075 public function fixSpecialName() {
1076 if ( $this->isSpecialPage() ) {
1077 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1078 if ( $canonicalName ) {
1079 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1080 if ( $localName != $this->mDbkeyform ) {
1081 return Title::makeTitle( NS_SPECIAL, $localName );
1085 return $this;
1089 * Returns true if the title is inside the specified namespace.
1091 * Please make use of this instead of comparing to getNamespace()
1092 * This function is much more resistant to changes we may make
1093 * to namespaces than code that makes direct comparisons.
1094 * @param int $ns The namespace
1095 * @return bool
1096 * @since 1.19
1098 public function inNamespace( $ns ) {
1099 return MWNamespace::equals( $this->getNamespace(), $ns );
1103 * Returns true if the title is inside one of the specified namespaces.
1105 * @param int $namespaces,... The namespaces to check for
1106 * @return bool
1107 * @since 1.19
1109 public function inNamespaces( /* ... */ ) {
1110 $namespaces = func_get_args();
1111 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1112 $namespaces = $namespaces[0];
1115 foreach ( $namespaces as $ns ) {
1116 if ( $this->inNamespace( $ns ) ) {
1117 return true;
1121 return false;
1125 * Returns true if the title has the same subject namespace as the
1126 * namespace specified.
1127 * For example this method will take NS_USER and return true if namespace
1128 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1129 * as their subject namespace.
1131 * This is MUCH simpler than individually testing for equivalence
1132 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1133 * @since 1.19
1134 * @param int $ns
1135 * @return bool
1137 public function hasSubjectNamespace( $ns ) {
1138 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1142 * Is this Title in a namespace which contains content?
1143 * In other words, is this a content page, for the purposes of calculating
1144 * statistics, etc?
1146 * @return bool
1148 public function isContentPage() {
1149 return MWNamespace::isContent( $this->getNamespace() );
1153 * Would anybody with sufficient privileges be able to move this page?
1154 * Some pages just aren't movable.
1156 * @return bool
1158 public function isMovable() {
1159 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1160 // Interwiki title or immovable namespace. Hooks don't get to override here
1161 return false;
1164 $result = true;
1165 Hooks::run( 'TitleIsMovable', array( $this, &$result ) );
1166 return $result;
1170 * Is this the mainpage?
1171 * @note Title::newFromText seems to be sufficiently optimized by the title
1172 * cache that we don't need to over-optimize by doing direct comparisons and
1173 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1174 * ends up reporting something differently than $title->isMainPage();
1176 * @since 1.18
1177 * @return bool
1179 public function isMainPage() {
1180 return $this->equals( Title::newMainPage() );
1184 * Is this a subpage?
1186 * @return bool
1188 public function isSubpage() {
1189 return MWNamespace::hasSubpages( $this->mNamespace )
1190 ? strpos( $this->getText(), '/' ) !== false
1191 : false;
1195 * Is this a conversion table for the LanguageConverter?
1197 * @return bool
1199 public function isConversionTable() {
1200 // @todo ConversionTable should become a separate content model.
1202 return $this->getNamespace() == NS_MEDIAWIKI &&
1203 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1207 * Does that page contain wikitext, or it is JS, CSS or whatever?
1209 * @return bool
1211 public function isWikitextPage() {
1212 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1216 * Could this page contain custom CSS or JavaScript for the global UI.
1217 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1218 * or CONTENT_MODEL_JAVASCRIPT.
1220 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1221 * for that!
1223 * Note that this method should not return true for pages that contain and
1224 * show "inactive" CSS or JS.
1226 * @return bool
1228 public function isCssOrJsPage() {
1229 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1230 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1231 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1233 # @note This hook is also called in ContentHandler::getDefaultModel.
1234 # It's called here again to make sure hook functions can force this
1235 # method to return true even outside the MediaWiki namespace.
1237 Hooks::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1239 return $isCssOrJsPage;
1243 * Is this a .css or .js subpage of a user page?
1244 * @return bool
1246 public function isCssJsSubpage() {
1247 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1248 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1249 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1253 * Trim down a .css or .js subpage title to get the corresponding skin name
1255 * @return string Containing skin name from .css or .js subpage title
1257 public function getSkinFromCssJsSubpage() {
1258 $subpage = explode( '/', $this->mTextform );
1259 $subpage = $subpage[count( $subpage ) - 1];
1260 $lastdot = strrpos( $subpage, '.' );
1261 if ( $lastdot === false ) {
1262 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1264 return substr( $subpage, 0, $lastdot );
1268 * Is this a .css subpage of a user page?
1270 * @return bool
1272 public function isCssSubpage() {
1273 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1274 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1278 * Is this a .js subpage of a user page?
1280 * @return bool
1282 public function isJsSubpage() {
1283 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1284 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1288 * Is this a talk page of some sort?
1290 * @return bool
1292 public function isTalkPage() {
1293 return MWNamespace::isTalk( $this->getNamespace() );
1297 * Get a Title object associated with the talk page of this article
1299 * @return Title The object for the talk page
1301 public function getTalkPage() {
1302 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1306 * Get a title object associated with the subject page of this
1307 * talk page
1309 * @return Title The object for the subject page
1311 public function getSubjectPage() {
1312 // Is this the same title?
1313 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1314 if ( $this->getNamespace() == $subjectNS ) {
1315 return $this;
1317 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1321 * Get the other title for this page, if this is a subject page
1322 * get the talk page, if it is a subject page get the talk page
1324 * @since 1.25
1325 * @throws MWException
1326 * @return Title
1328 public function getOtherPage() {
1329 if ( $this->isSpecialPage() ) {
1330 throw new MWException( 'Special pages cannot have other pages' );
1332 if ( $this->isTalkPage() ) {
1333 return $this->getSubjectPage();
1334 } else {
1335 return $this->getTalkPage();
1340 * Get the default namespace index, for when there is no namespace
1342 * @return int Default namespace index
1344 public function getDefaultNamespace() {
1345 return $this->mDefaultNamespace;
1349 * Get the Title fragment (i.e.\ the bit after the #) in text form
1351 * Use Title::hasFragment to check for a fragment
1353 * @return string Title fragment
1355 public function getFragment() {
1356 return $this->mFragment;
1360 * Check if a Title fragment is set
1362 * @return bool
1363 * @since 1.23
1365 public function hasFragment() {
1366 return $this->mFragment !== '';
1370 * Get the fragment in URL form, including the "#" character if there is one
1371 * @return string Fragment in URL form
1373 public function getFragmentForURL() {
1374 if ( !$this->hasFragment() ) {
1375 return '';
1376 } else {
1377 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1382 * Set the fragment for this title. Removes the first character from the
1383 * specified fragment before setting, so it assumes you're passing it with
1384 * an initial "#".
1386 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1387 * Still in active use privately.
1389 * @param string $fragment Text
1391 public function setFragment( $fragment ) {
1392 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1396 * Prefix some arbitrary text with the namespace or interwiki prefix
1397 * of this object
1399 * @param string $name The text
1400 * @return string The prefixed text
1402 private function prefix( $name ) {
1403 $p = '';
1404 if ( $this->isExternal() ) {
1405 $p = $this->mInterwiki . ':';
1408 if ( 0 != $this->mNamespace ) {
1409 $p .= $this->getNsText() . ':';
1411 return $p . $name;
1415 * Get the prefixed database key form
1417 * @return string The prefixed title, with underscores and
1418 * any interwiki and namespace prefixes
1420 public function getPrefixedDBkey() {
1421 $s = $this->prefix( $this->mDbkeyform );
1422 $s = str_replace( ' ', '_', $s );
1423 return $s;
1427 * Get the prefixed title with spaces.
1428 * This is the form usually used for display
1430 * @return string The prefixed title, with spaces
1432 public function getPrefixedText() {
1433 if ( $this->mPrefixedText === null ) {
1434 $s = $this->prefix( $this->mTextform );
1435 $s = str_replace( '_', ' ', $s );
1436 $this->mPrefixedText = $s;
1438 return $this->mPrefixedText;
1442 * Return a string representation of this title
1444 * @return string Representation of this title
1446 public function __toString() {
1447 return $this->getPrefixedText();
1451 * Get the prefixed title with spaces, plus any fragment
1452 * (part beginning with '#')
1454 * @return string The prefixed title, with spaces and the fragment, including '#'
1456 public function getFullText() {
1457 $text = $this->getPrefixedText();
1458 if ( $this->hasFragment() ) {
1459 $text .= '#' . $this->getFragment();
1461 return $text;
1465 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1467 * @par Example:
1468 * @code
1469 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1470 * # returns: 'Foo'
1471 * @endcode
1473 * @return string Root name
1474 * @since 1.20
1476 public function getRootText() {
1477 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1478 return $this->getText();
1481 return strtok( $this->getText(), '/' );
1485 * Get the root page name title, i.e. the leftmost part before any slashes
1487 * @par Example:
1488 * @code
1489 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1490 * # returns: Title{User:Foo}
1491 * @endcode
1493 * @return Title Root title
1494 * @since 1.20
1496 public function getRootTitle() {
1497 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1501 * Get the base page name without a namespace, i.e. the part before the subpage name
1503 * @par Example:
1504 * @code
1505 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1506 * # returns: 'Foo/Bar'
1507 * @endcode
1509 * @return string Base name
1511 public function getBaseText() {
1512 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1513 return $this->getText();
1516 $parts = explode( '/', $this->getText() );
1517 # Don't discard the real title if there's no subpage involved
1518 if ( count( $parts ) > 1 ) {
1519 unset( $parts[count( $parts ) - 1] );
1521 return implode( '/', $parts );
1525 * Get the base page name title, i.e. the part before the subpage name
1527 * @par Example:
1528 * @code
1529 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1530 * # returns: Title{User:Foo/Bar}
1531 * @endcode
1533 * @return Title Base title
1534 * @since 1.20
1536 public function getBaseTitle() {
1537 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1541 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1543 * @par Example:
1544 * @code
1545 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1546 * # returns: "Baz"
1547 * @endcode
1549 * @return string Subpage name
1551 public function getSubpageText() {
1552 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1553 return $this->mTextform;
1555 $parts = explode( '/', $this->mTextform );
1556 return $parts[count( $parts ) - 1];
1560 * Get the title for a subpage of the current page
1562 * @par Example:
1563 * @code
1564 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1565 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1566 * @endcode
1568 * @param string $text The subpage name to add to the title
1569 * @return Title Subpage title
1570 * @since 1.20
1572 public function getSubpage( $text ) {
1573 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1577 * Get a URL-encoded form of the subpage text
1579 * @return string URL-encoded subpage name
1581 public function getSubpageUrlForm() {
1582 $text = $this->getSubpageText();
1583 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1584 return $text;
1588 * Get a URL-encoded title (not an actual URL) including interwiki
1590 * @return string The URL-encoded form
1592 public function getPrefixedURL() {
1593 $s = $this->prefix( $this->mDbkeyform );
1594 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1595 return $s;
1599 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1600 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1601 * second argument named variant. This was deprecated in favor
1602 * of passing an array of option with a "variant" key
1603 * Once $query2 is removed for good, this helper can be dropped
1604 * and the wfArrayToCgi moved to getLocalURL();
1606 * @since 1.19 (r105919)
1607 * @param array|string $query
1608 * @param bool $query2
1609 * @return string
1611 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1612 if ( $query2 !== false ) {
1613 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1614 "method called with a second parameter is deprecated. Add your " .
1615 "parameter to an array passed as the first parameter.", "1.19" );
1617 if ( is_array( $query ) ) {
1618 $query = wfArrayToCgi( $query );
1620 if ( $query2 ) {
1621 if ( is_string( $query2 ) ) {
1622 // $query2 is a string, we will consider this to be
1623 // a deprecated $variant argument and add it to the query
1624 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1625 } else {
1626 $query2 = wfArrayToCgi( $query2 );
1628 // If we have $query content add a & to it first
1629 if ( $query ) {
1630 $query .= '&';
1632 // Now append the queries together
1633 $query .= $query2;
1635 return $query;
1639 * Get a real URL referring to this title, with interwiki link and
1640 * fragment
1642 * @see self::getLocalURL for the arguments.
1643 * @see wfExpandUrl
1644 * @param array|string $query
1645 * @param bool $query2
1646 * @param string $proto Protocol type to use in URL
1647 * @return string The URL
1649 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1650 $query = self::fixUrlQueryArgs( $query, $query2 );
1652 # Hand off all the decisions on urls to getLocalURL
1653 $url = $this->getLocalURL( $query );
1655 # Expand the url to make it a full url. Note that getLocalURL has the
1656 # potential to output full urls for a variety of reasons, so we use
1657 # wfExpandUrl instead of simply prepending $wgServer
1658 $url = wfExpandUrl( $url, $proto );
1660 # Finally, add the fragment.
1661 $url .= $this->getFragmentForURL();
1663 Hooks::run( 'GetFullURL', array( &$this, &$url, $query ) );
1664 return $url;
1668 * Get a URL with no fragment or server name (relative URL) from a Title object.
1669 * If this page is generated with action=render, however,
1670 * $wgServer is prepended to make an absolute URL.
1672 * @see self::getFullURL to always get an absolute URL.
1673 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1674 * valid to link, locally, to the current Title.
1675 * @see self::newFromText to produce a Title object.
1677 * @param string|array $query An optional query string,
1678 * not used for interwiki links. Can be specified as an associative array as well,
1679 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1680 * Some query patterns will trigger various shorturl path replacements.
1681 * @param array $query2 An optional secondary query array. This one MUST
1682 * be an array. If a string is passed it will be interpreted as a deprecated
1683 * variant argument and urlencoded into a variant= argument.
1684 * This second query argument will be added to the $query
1685 * The second parameter is deprecated since 1.19. Pass it as a key,value
1686 * pair in the first parameter array instead.
1688 * @return string String of the URL.
1690 public function getLocalURL( $query = '', $query2 = false ) {
1691 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1693 $query = self::fixUrlQueryArgs( $query, $query2 );
1695 $interwiki = Interwiki::fetch( $this->mInterwiki );
1696 if ( $interwiki ) {
1697 $namespace = $this->getNsText();
1698 if ( $namespace != '' ) {
1699 # Can this actually happen? Interwikis shouldn't be parsed.
1700 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1701 $namespace .= ':';
1703 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1704 $url = wfAppendQuery( $url, $query );
1705 } else {
1706 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1707 if ( $query == '' ) {
1708 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1709 Hooks::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1710 } else {
1711 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1712 $url = false;
1713 $matches = array();
1715 if ( !empty( $wgActionPaths )
1716 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1718 $action = urldecode( $matches[2] );
1719 if ( isset( $wgActionPaths[$action] ) ) {
1720 $query = $matches[1];
1721 if ( isset( $matches[4] ) ) {
1722 $query .= $matches[4];
1724 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1725 if ( $query != '' ) {
1726 $url = wfAppendQuery( $url, $query );
1731 if ( $url === false
1732 && $wgVariantArticlePath
1733 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1734 && $this->getPageLanguage()->hasVariants()
1735 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1737 $variant = urldecode( $matches[1] );
1738 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1739 // Only do the variant replacement if the given variant is a valid
1740 // variant for the page's language.
1741 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1742 $url = str_replace( '$1', $dbkey, $url );
1746 if ( $url === false ) {
1747 if ( $query == '-' ) {
1748 $query = '';
1750 $url = "{$wgScript}?title={$dbkey}&{$query}";
1754 Hooks::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1756 // @todo FIXME: This causes breakage in various places when we
1757 // actually expected a local URL and end up with dupe prefixes.
1758 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1759 $url = $wgServer . $url;
1762 Hooks::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1763 return $url;
1767 * Get a URL that's the simplest URL that will be valid to link, locally,
1768 * to the current Title. It includes the fragment, but does not include
1769 * the server unless action=render is used (or the link is external). If
1770 * there's a fragment but the prefixed text is empty, we just return a link
1771 * to the fragment.
1773 * The result obviously should not be URL-escaped, but does need to be
1774 * HTML-escaped if it's being output in HTML.
1776 * @param array $query
1777 * @param bool $query2
1778 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1779 * @see self::getLocalURL for the arguments.
1780 * @return string The URL
1782 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1783 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1784 $ret = $this->getFullURL( $query, $query2, $proto );
1785 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1786 $ret = $this->getFragmentForURL();
1787 } else {
1788 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1790 return $ret;
1794 * Get the URL form for an internal link.
1795 * - Used in various Squid-related code, in case we have a different
1796 * internal hostname for the server from the exposed one.
1798 * This uses $wgInternalServer to qualify the path, or $wgServer
1799 * if $wgInternalServer is not set. If the server variable used is
1800 * protocol-relative, the URL will be expanded to http://
1802 * @see self::getLocalURL for the arguments.
1803 * @return string The URL
1805 public function getInternalURL( $query = '', $query2 = false ) {
1806 global $wgInternalServer, $wgServer;
1807 $query = self::fixUrlQueryArgs( $query, $query2 );
1808 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1809 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1810 Hooks::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1811 return $url;
1815 * Get the URL for a canonical link, for use in things like IRC and
1816 * e-mail notifications. Uses $wgCanonicalServer and the
1817 * GetCanonicalURL hook.
1819 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1821 * @see self::getLocalURL for the arguments.
1822 * @return string The URL
1823 * @since 1.18
1825 public function getCanonicalURL( $query = '', $query2 = false ) {
1826 $query = self::fixUrlQueryArgs( $query, $query2 );
1827 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1828 Hooks::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1829 return $url;
1833 * Get the edit URL for this Title
1835 * @return string The URL, or a null string if this is an interwiki link
1837 public function getEditURL() {
1838 if ( $this->isExternal() ) {
1839 return '';
1841 $s = $this->getLocalURL( 'action=edit' );
1843 return $s;
1847 * Is $wgUser watching this page?
1849 * @deprecated since 1.20; use User::isWatched() instead.
1850 * @return bool
1852 public function userIsWatching() {
1853 global $wgUser;
1855 if ( is_null( $this->mWatched ) ) {
1856 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1857 $this->mWatched = false;
1858 } else {
1859 $this->mWatched = $wgUser->isWatched( $this );
1862 return $this->mWatched;
1866 * Can $user perform $action on this page?
1867 * This skips potentially expensive cascading permission checks
1868 * as well as avoids expensive error formatting
1870 * Suitable for use for nonessential UI controls in common cases, but
1871 * _not_ for functional access control.
1873 * May provide false positives, but should never provide a false negative.
1875 * @param string $action Action that permission needs to be checked for
1876 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1877 * @return bool
1879 public function quickUserCan( $action, $user = null ) {
1880 return $this->userCan( $action, $user, false );
1884 * Can $user perform $action on this page?
1886 * @param string $action Action that permission needs to be checked for
1887 * @param User $user User to check (since 1.19); $wgUser will be used if not
1888 * provided.
1889 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1890 * @return bool
1892 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1893 if ( !$user instanceof User ) {
1894 global $wgUser;
1895 $user = $wgUser;
1898 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1902 * Can $user perform $action on this page?
1904 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1906 * @param string $action Action that permission needs to be checked for
1907 * @param User $user User to check
1908 * @param string $rigor One of (quick,full,secure)
1909 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1910 * - full : does cheap and expensive checks possibly from a slave
1911 * - secure : does cheap and expensive checks, using the master as needed
1912 * @param bool $short Set this to true to stop after the first permission error.
1913 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1914 * whose corresponding errors may be ignored.
1915 * @return array Array of arguments to wfMessage to explain permissions problems.
1917 public function getUserPermissionsErrors(
1918 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1920 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1922 // Remove the errors being ignored.
1923 foreach ( $errors as $index => $error ) {
1924 $error_key = is_array( $error ) ? $error[0] : $error;
1926 if ( in_array( $error_key, $ignoreErrors ) ) {
1927 unset( $errors[$index] );
1931 return $errors;
1935 * Permissions checks that fail most often, and which are easiest to test.
1937 * @param string $action The action to check
1938 * @param User $user User to check
1939 * @param array $errors List of current errors
1940 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1941 * @param bool $short Short circuit on first error
1943 * @return array List of errors
1945 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1946 if ( !Hooks::run( 'TitleQuickPermissions',
1947 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1949 return $errors;
1952 if ( $action == 'create' ) {
1953 if (
1954 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1955 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1957 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1959 } elseif ( $action == 'move' ) {
1960 if ( !$user->isAllowed( 'move-rootuserpages' )
1961 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1962 // Show user page-specific message only if the user can move other pages
1963 $errors[] = array( 'cant-move-user-page' );
1966 // Check if user is allowed to move files if it's a file
1967 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1968 $errors[] = array( 'movenotallowedfile' );
1971 // Check if user is allowed to move category pages if it's a category page
1972 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1973 $errors[] = array( 'cant-move-category-page' );
1976 if ( !$user->isAllowed( 'move' ) ) {
1977 // User can't move anything
1978 $userCanMove = User::groupHasPermission( 'user', 'move' );
1979 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1980 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1981 // custom message if logged-in users without any special rights can move
1982 $errors[] = array( 'movenologintext' );
1983 } else {
1984 $errors[] = array( 'movenotallowed' );
1987 } elseif ( $action == 'move-target' ) {
1988 if ( !$user->isAllowed( 'move' ) ) {
1989 // User can't move anything
1990 $errors[] = array( 'movenotallowed' );
1991 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1992 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1993 // Show user page-specific message only if the user can move other pages
1994 $errors[] = array( 'cant-move-to-user-page' );
1995 } elseif ( !$user->isAllowed( 'move-categorypages' )
1996 && $this->mNamespace == NS_CATEGORY ) {
1997 // Show category page-specific message only if the user can move other pages
1998 $errors[] = array( 'cant-move-to-category-page' );
2000 } elseif ( !$user->isAllowed( $action ) ) {
2001 $errors[] = $this->missingPermissionError( $action, $short );
2004 return $errors;
2008 * Add the resulting error code to the errors array
2010 * @param array $errors List of current errors
2011 * @param array $result Result of errors
2013 * @return array List of errors
2015 private function resultToError( $errors, $result ) {
2016 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2017 // A single array representing an error
2018 $errors[] = $result;
2019 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2020 // A nested array representing multiple errors
2021 $errors = array_merge( $errors, $result );
2022 } elseif ( $result !== '' && is_string( $result ) ) {
2023 // A string representing a message-id
2024 $errors[] = array( $result );
2025 } elseif ( $result === false ) {
2026 // a generic "We don't want them to do that"
2027 $errors[] = array( 'badaccess-group0' );
2029 return $errors;
2033 * Check various permission hooks
2035 * @param string $action The action to check
2036 * @param User $user User to check
2037 * @param array $errors List of current errors
2038 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2039 * @param bool $short Short circuit on first error
2041 * @return array List of errors
2043 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2044 // Use getUserPermissionsErrors instead
2045 $result = '';
2046 if ( !Hooks::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2047 return $result ? array() : array( array( 'badaccess-group0' ) );
2049 // Check getUserPermissionsErrors hook
2050 if ( !Hooks::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2051 $errors = $this->resultToError( $errors, $result );
2053 // Check getUserPermissionsErrorsExpensive hook
2054 if (
2055 $rigor !== 'quick'
2056 && !( $short && count( $errors ) > 0 )
2057 && !Hooks::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2059 $errors = $this->resultToError( $errors, $result );
2062 return $errors;
2066 * Check permissions on special pages & namespaces
2068 * @param string $action The action to check
2069 * @param User $user User to check
2070 * @param array $errors List of current errors
2071 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2072 * @param bool $short Short circuit on first error
2074 * @return array List of errors
2076 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2077 # Only 'createaccount' can be performed on special pages,
2078 # which don't actually exist in the DB.
2079 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2080 $errors[] = array( 'ns-specialprotected' );
2083 # Check $wgNamespaceProtection for restricted namespaces
2084 if ( $this->isNamespaceProtected( $user ) ) {
2085 $ns = $this->mNamespace == NS_MAIN ?
2086 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2087 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2088 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2091 return $errors;
2095 * Check CSS/JS sub-page permissions
2097 * @param string $action The action to check
2098 * @param User $user User to check
2099 * @param array $errors List of current errors
2100 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2101 * @param bool $short Short circuit on first error
2103 * @return array List of errors
2105 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2106 # Protect css/js subpages of user pages
2107 # XXX: this might be better using restrictions
2108 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2109 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2110 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2111 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2112 $errors[] = array( 'mycustomcssprotected', $action );
2113 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2114 $errors[] = array( 'mycustomjsprotected', $action );
2116 } else {
2117 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2118 $errors[] = array( 'customcssprotected', $action );
2119 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2120 $errors[] = array( 'customjsprotected', $action );
2125 return $errors;
2129 * Check against page_restrictions table requirements on this
2130 * page. The user must possess all required rights for this
2131 * action.
2133 * @param string $action The action to check
2134 * @param User $user User to check
2135 * @param array $errors List of current errors
2136 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2137 * @param bool $short Short circuit on first error
2139 * @return array List of errors
2141 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2142 foreach ( $this->getRestrictions( $action ) as $right ) {
2143 // Backwards compatibility, rewrite sysop -> editprotected
2144 if ( $right == 'sysop' ) {
2145 $right = 'editprotected';
2147 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2148 if ( $right == 'autoconfirmed' ) {
2149 $right = 'editsemiprotected';
2151 if ( $right == '' ) {
2152 continue;
2154 if ( !$user->isAllowed( $right ) ) {
2155 $errors[] = array( 'protectedpagetext', $right, $action );
2156 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2157 $errors[] = array( 'protectedpagetext', 'protect', $action );
2161 return $errors;
2165 * Check restrictions on cascading pages.
2167 * @param string $action The action to check
2168 * @param User $user User to check
2169 * @param array $errors List of current errors
2170 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2171 * @param bool $short Short circuit on first error
2173 * @return array List of errors
2175 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2176 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2177 # We /could/ use the protection level on the source page, but it's
2178 # fairly ugly as we have to establish a precedence hierarchy for pages
2179 # included by multiple cascade-protected pages. So just restrict
2180 # it to people with 'protect' permission, as they could remove the
2181 # protection anyway.
2182 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2183 # Cascading protection depends on more than this page...
2184 # Several cascading protected pages may include this page...
2185 # Check each cascading level
2186 # This is only for protection restrictions, not for all actions
2187 if ( isset( $restrictions[$action] ) ) {
2188 foreach ( $restrictions[$action] as $right ) {
2189 // Backwards compatibility, rewrite sysop -> editprotected
2190 if ( $right == 'sysop' ) {
2191 $right = 'editprotected';
2193 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2194 if ( $right == 'autoconfirmed' ) {
2195 $right = 'editsemiprotected';
2197 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2198 $pages = '';
2199 foreach ( $cascadingSources as $page ) {
2200 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2202 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2208 return $errors;
2212 * Check action permissions not already checked in checkQuickPermissions
2214 * @param string $action The action to check
2215 * @param User $user User to check
2216 * @param array $errors List of current errors
2217 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2218 * @param bool $short Short circuit on first error
2220 * @return array List of errors
2222 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2223 global $wgDeleteRevisionsLimit, $wgLang;
2225 if ( $action == 'protect' ) {
2226 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2227 // If they can't edit, they shouldn't protect.
2228 $errors[] = array( 'protect-cantedit' );
2230 } elseif ( $action == 'create' ) {
2231 $title_protection = $this->getTitleProtection();
2232 if ( $title_protection ) {
2233 if ( $title_protection['permission'] == ''
2234 || !$user->isAllowed( $title_protection['permission'] )
2236 $errors[] = array(
2237 'titleprotected',
2238 User::whoIs( $title_protection['user'] ),
2239 $title_protection['reason']
2243 } elseif ( $action == 'move' ) {
2244 // Check for immobile pages
2245 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2246 // Specific message for this case
2247 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2248 } elseif ( !$this->isMovable() ) {
2249 // Less specific message for rarer cases
2250 $errors[] = array( 'immobile-source-page' );
2252 } elseif ( $action == 'move-target' ) {
2253 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2254 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2255 } elseif ( !$this->isMovable() ) {
2256 $errors[] = array( 'immobile-target-page' );
2258 } elseif ( $action == 'delete' ) {
2259 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2260 if ( !$tempErrors ) {
2261 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2262 $user, $tempErrors, $rigor, true );
2264 if ( $tempErrors ) {
2265 // If protection keeps them from editing, they shouldn't be able to delete.
2266 $errors[] = array( 'deleteprotected' );
2268 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2269 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2271 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2274 return $errors;
2278 * Check that the user isn't blocked from editing.
2280 * @param string $action The action to check
2281 * @param User $user User to check
2282 * @param array $errors List of current errors
2283 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2284 * @param bool $short Short circuit on first error
2286 * @return array List of errors
2288 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2289 // Account creation blocks handled at userlogin.
2290 // Unblocking handled in SpecialUnblock
2291 if ( $rigor === 'quick' || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2292 return $errors;
2295 global $wgEmailConfirmToEdit;
2297 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2298 $errors[] = array( 'confirmedittext' );
2301 $useSlave = ( $rigor !== 'secure' );
2302 if ( ( $action == 'edit' || $action == 'create' )
2303 && !$user->isBlockedFrom( $this, $useSlave )
2305 // Don't block the user from editing their own talk page unless they've been
2306 // explicitly blocked from that too.
2307 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2308 // @todo FIXME: Pass the relevant context into this function.
2309 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2312 return $errors;
2316 * Check that the user is allowed to read this page.
2318 * @param string $action The action to check
2319 * @param User $user User to check
2320 * @param array $errors List of current errors
2321 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2322 * @param bool $short Short circuit on first error
2324 * @return array List of errors
2326 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2327 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2329 $whitelisted = false;
2330 if ( User::isEveryoneAllowed( 'read' ) ) {
2331 # Shortcut for public wikis, allows skipping quite a bit of code
2332 $whitelisted = true;
2333 } elseif ( $user->isAllowed( 'read' ) ) {
2334 # If the user is allowed to read pages, he is allowed to read all pages
2335 $whitelisted = true;
2336 } elseif ( $this->isSpecial( 'Userlogin' )
2337 || $this->isSpecial( 'ChangePassword' )
2338 || $this->isSpecial( 'PasswordReset' )
2340 # Always grant access to the login page.
2341 # Even anons need to be able to log in.
2342 $whitelisted = true;
2343 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2344 # Time to check the whitelist
2345 # Only do these checks is there's something to check against
2346 $name = $this->getPrefixedText();
2347 $dbName = $this->getPrefixedDBkey();
2349 // Check for explicit whitelisting with and without underscores
2350 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2351 $whitelisted = true;
2352 } elseif ( $this->getNamespace() == NS_MAIN ) {
2353 # Old settings might have the title prefixed with
2354 # a colon for main-namespace pages
2355 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2356 $whitelisted = true;
2358 } elseif ( $this->isSpecialPage() ) {
2359 # If it's a special page, ditch the subpage bit and check again
2360 $name = $this->getDBkey();
2361 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2362 if ( $name ) {
2363 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2364 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2365 $whitelisted = true;
2371 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2372 $name = $this->getPrefixedText();
2373 // Check for regex whitelisting
2374 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2375 if ( preg_match( $listItem, $name ) ) {
2376 $whitelisted = true;
2377 break;
2382 if ( !$whitelisted ) {
2383 # If the title is not whitelisted, give extensions a chance to do so...
2384 Hooks::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2385 if ( !$whitelisted ) {
2386 $errors[] = $this->missingPermissionError( $action, $short );
2390 return $errors;
2394 * Get a description array when the user doesn't have the right to perform
2395 * $action (i.e. when User::isAllowed() returns false)
2397 * @param string $action The action to check
2398 * @param bool $short Short circuit on first error
2399 * @return array List of errors
2401 private function missingPermissionError( $action, $short ) {
2402 // We avoid expensive display logic for quickUserCan's and such
2403 if ( $short ) {
2404 return array( 'badaccess-group0' );
2407 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2408 User::getGroupsWithPermission( $action ) );
2410 if ( count( $groups ) ) {
2411 global $wgLang;
2412 return array(
2413 'badaccess-groups',
2414 $wgLang->commaList( $groups ),
2415 count( $groups )
2417 } else {
2418 return array( 'badaccess-group0' );
2423 * Can $user perform $action on this page? This is an internal function,
2424 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2425 * checks on wfReadOnly() and blocks)
2427 * @param string $action Action that permission needs to be checked for
2428 * @param User $user User to check
2429 * @param string $rigor One of (quick,full,secure)
2430 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2431 * - full : does cheap and expensive checks possibly from a slave
2432 * - secure : does cheap and expensive checks, using the master as needed
2433 * @param bool $short Set this to true to stop after the first permission error.
2434 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2436 protected function getUserPermissionsErrorsInternal(
2437 $action, $user, $rigor = 'secure', $short = false
2439 if ( $rigor === true ) {
2440 $rigor = 'secure'; // b/c
2441 } elseif ( $rigor === false ) {
2442 $rigor = 'quick'; // b/c
2443 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2444 throw new Exception( "Invalid rigor parameter '$rigor'." );
2447 # Read has special handling
2448 if ( $action == 'read' ) {
2449 $checks = array(
2450 'checkPermissionHooks',
2451 'checkReadPermissions',
2453 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2454 # here as it will lead to duplicate error messages. This is okay to do
2455 # since anywhere that checks for create will also check for edit, and
2456 # those checks are called for edit.
2457 } elseif ( $action == 'create' ) {
2458 $checks = array(
2459 'checkQuickPermissions',
2460 'checkPermissionHooks',
2461 'checkPageRestrictions',
2462 'checkCascadingSourcesRestrictions',
2463 'checkActionPermissions',
2464 'checkUserBlock'
2466 } else {
2467 $checks = array(
2468 'checkQuickPermissions',
2469 'checkPermissionHooks',
2470 'checkSpecialsAndNSPermissions',
2471 'checkCSSandJSPermissions',
2472 'checkPageRestrictions',
2473 'checkCascadingSourcesRestrictions',
2474 'checkActionPermissions',
2475 'checkUserBlock'
2479 $errors = array();
2480 while ( count( $checks ) > 0 &&
2481 !( $short && count( $errors ) > 0 ) ) {
2482 $method = array_shift( $checks );
2483 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2486 return $errors;
2490 * Get a filtered list of all restriction types supported by this wiki.
2491 * @param bool $exists True to get all restriction types that apply to
2492 * titles that do exist, False for all restriction types that apply to
2493 * titles that do not exist
2494 * @return array
2496 public static function getFilteredRestrictionTypes( $exists = true ) {
2497 global $wgRestrictionTypes;
2498 $types = $wgRestrictionTypes;
2499 if ( $exists ) {
2500 # Remove the create restriction for existing titles
2501 $types = array_diff( $types, array( 'create' ) );
2502 } else {
2503 # Only the create and upload restrictions apply to non-existing titles
2504 $types = array_intersect( $types, array( 'create', 'upload' ) );
2506 return $types;
2510 * Returns restriction types for the current Title
2512 * @return array Applicable restriction types
2514 public function getRestrictionTypes() {
2515 if ( $this->isSpecialPage() ) {
2516 return array();
2519 $types = self::getFilteredRestrictionTypes( $this->exists() );
2521 if ( $this->getNamespace() != NS_FILE ) {
2522 # Remove the upload restriction for non-file titles
2523 $types = array_diff( $types, array( 'upload' ) );
2526 Hooks::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2528 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2529 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2531 return $types;
2535 * Is this title subject to title protection?
2536 * Title protection is the one applied against creation of such title.
2538 * @return array|bool An associative array representing any existent title
2539 * protection, or false if there's none.
2541 public function getTitleProtection() {
2542 // Can't protect pages in special namespaces
2543 if ( $this->getNamespace() < 0 ) {
2544 return false;
2547 // Can't protect pages that exist.
2548 if ( $this->exists() ) {
2549 return false;
2552 if ( $this->mTitleProtection === null ) {
2553 $dbr = wfGetDB( DB_SLAVE );
2554 $res = $dbr->select(
2555 'protected_titles',
2556 array(
2557 'user' => 'pt_user',
2558 'reason' => 'pt_reason',
2559 'expiry' => 'pt_expiry',
2560 'permission' => 'pt_create_perm'
2562 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2563 __METHOD__
2566 // fetchRow returns false if there are no rows.
2567 $row = $dbr->fetchRow( $res );
2568 if ( $row ) {
2569 if ( $row['permission'] == 'sysop' ) {
2570 $row['permission'] = 'editprotected'; // B/C
2572 if ( $row['permission'] == 'autoconfirmed' ) {
2573 $row['permission'] = 'editsemiprotected'; // B/C
2576 $this->mTitleProtection = $row;
2578 return $this->mTitleProtection;
2582 * Remove any title protection due to page existing
2584 public function deleteTitleProtection() {
2585 $dbw = wfGetDB( DB_MASTER );
2587 $dbw->delete(
2588 'protected_titles',
2589 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2590 __METHOD__
2592 $this->mTitleProtection = false;
2596 * Is this page "semi-protected" - the *only* protection levels are listed
2597 * in $wgSemiprotectedRestrictionLevels?
2599 * @param string $action Action to check (default: edit)
2600 * @return bool
2602 public function isSemiProtected( $action = 'edit' ) {
2603 global $wgSemiprotectedRestrictionLevels;
2605 $restrictions = $this->getRestrictions( $action );
2606 $semi = $wgSemiprotectedRestrictionLevels;
2607 if ( !$restrictions || !$semi ) {
2608 // Not protected, or all protection is full protection
2609 return false;
2612 // Remap autoconfirmed to editsemiprotected for BC
2613 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2614 $semi[$key] = 'editsemiprotected';
2616 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2617 $restrictions[$key] = 'editsemiprotected';
2620 return !array_diff( $restrictions, $semi );
2624 * Does the title correspond to a protected article?
2626 * @param string $action The action the page is protected from,
2627 * by default checks all actions.
2628 * @return bool
2630 public function isProtected( $action = '' ) {
2631 global $wgRestrictionLevels;
2633 $restrictionTypes = $this->getRestrictionTypes();
2635 # Special pages have inherent protection
2636 if ( $this->isSpecialPage() ) {
2637 return true;
2640 # Check regular protection levels
2641 foreach ( $restrictionTypes as $type ) {
2642 if ( $action == $type || $action == '' ) {
2643 $r = $this->getRestrictions( $type );
2644 foreach ( $wgRestrictionLevels as $level ) {
2645 if ( in_array( $level, $r ) && $level != '' ) {
2646 return true;
2652 return false;
2656 * Determines if $user is unable to edit this page because it has been protected
2657 * by $wgNamespaceProtection.
2659 * @param User $user User object to check permissions
2660 * @return bool
2662 public function isNamespaceProtected( User $user ) {
2663 global $wgNamespaceProtection;
2665 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2666 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2667 if ( $right != '' && !$user->isAllowed( $right ) ) {
2668 return true;
2672 return false;
2676 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2678 * @return bool If the page is subject to cascading restrictions.
2680 public function isCascadeProtected() {
2681 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2682 return ( $sources > 0 );
2686 * Determines whether cascading protection sources have already been loaded from
2687 * the database.
2689 * @param bool $getPages True to check if the pages are loaded, or false to check
2690 * if the status is loaded.
2691 * @return bool Whether or not the specified information has been loaded
2692 * @since 1.23
2694 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2695 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2699 * Cascading protection: Get the source of any cascading restrictions on this page.
2701 * @param bool $getPages Whether or not to retrieve the actual pages
2702 * that the restrictions have come from and the actual restrictions
2703 * themselves.
2704 * @return array Two elements: First is an array of Title objects of the
2705 * pages from which cascading restrictions have come, false for
2706 * none, or true if such restrictions exist but $getPages was not
2707 * set. Second is an array like that returned by
2708 * Title::getAllRestrictions(), or an empty array if $getPages is
2709 * false.
2711 public function getCascadeProtectionSources( $getPages = true ) {
2712 global $wgContLang;
2713 $pagerestrictions = array();
2715 if ( $this->mCascadeSources !== null && $getPages ) {
2716 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2717 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2718 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2721 $dbr = wfGetDB( DB_SLAVE );
2723 if ( $this->getNamespace() == NS_FILE ) {
2724 $tables = array( 'imagelinks', 'page_restrictions' );
2725 $where_clauses = array(
2726 'il_to' => $this->getDBkey(),
2727 'il_from=pr_page',
2728 'pr_cascade' => 1
2730 } else {
2731 $tables = array( 'templatelinks', 'page_restrictions' );
2732 $where_clauses = array(
2733 'tl_namespace' => $this->getNamespace(),
2734 'tl_title' => $this->getDBkey(),
2735 'tl_from=pr_page',
2736 'pr_cascade' => 1
2740 if ( $getPages ) {
2741 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2742 'pr_expiry', 'pr_type', 'pr_level' );
2743 $where_clauses[] = 'page_id=pr_page';
2744 $tables[] = 'page';
2745 } else {
2746 $cols = array( 'pr_expiry' );
2749 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2751 $sources = $getPages ? array() : false;
2752 $now = wfTimestampNow();
2754 foreach ( $res as $row ) {
2755 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2756 if ( $expiry > $now ) {
2757 if ( $getPages ) {
2758 $page_id = $row->pr_page;
2759 $page_ns = $row->page_namespace;
2760 $page_title = $row->page_title;
2761 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2762 # Add groups needed for each restriction type if its not already there
2763 # Make sure this restriction type still exists
2765 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2766 $pagerestrictions[$row->pr_type] = array();
2769 if (
2770 isset( $pagerestrictions[$row->pr_type] )
2771 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2773 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2775 } else {
2776 $sources = true;
2781 if ( $getPages ) {
2782 $this->mCascadeSources = $sources;
2783 $this->mCascadingRestrictions = $pagerestrictions;
2784 } else {
2785 $this->mHasCascadingRestrictions = $sources;
2788 return array( $sources, $pagerestrictions );
2792 * Accessor for mRestrictionsLoaded
2794 * @return bool Whether or not the page's restrictions have already been
2795 * loaded from the database
2796 * @since 1.23
2798 public function areRestrictionsLoaded() {
2799 return $this->mRestrictionsLoaded;
2803 * Accessor/initialisation for mRestrictions
2805 * @param string $action Action that permission needs to be checked for
2806 * @return array Restriction levels needed to take the action. All levels are
2807 * required. Note that restriction levels are normally user rights, but 'sysop'
2808 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2809 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2811 public function getRestrictions( $action ) {
2812 if ( !$this->mRestrictionsLoaded ) {
2813 $this->loadRestrictions();
2815 return isset( $this->mRestrictions[$action] )
2816 ? $this->mRestrictions[$action]
2817 : array();
2821 * Accessor/initialisation for mRestrictions
2823 * @return array Keys are actions, values are arrays as returned by
2824 * Title::getRestrictions()
2825 * @since 1.23
2827 public function getAllRestrictions() {
2828 if ( !$this->mRestrictionsLoaded ) {
2829 $this->loadRestrictions();
2831 return $this->mRestrictions;
2835 * Get the expiry time for the restriction against a given action
2837 * @param string $action
2838 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2839 * or not protected at all, or false if the action is not recognised.
2841 public function getRestrictionExpiry( $action ) {
2842 if ( !$this->mRestrictionsLoaded ) {
2843 $this->loadRestrictions();
2845 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2849 * Returns cascading restrictions for the current article
2851 * @return bool
2853 function areRestrictionsCascading() {
2854 if ( !$this->mRestrictionsLoaded ) {
2855 $this->loadRestrictions();
2858 return $this->mCascadeRestriction;
2862 * Loads a string into mRestrictions array
2864 * @param ResultWrapper $res Resource restrictions as an SQL result.
2865 * @param string $oldFashionedRestrictions Comma-separated list of page
2866 * restrictions from page table (pre 1.10)
2868 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2869 $rows = array();
2871 foreach ( $res as $row ) {
2872 $rows[] = $row;
2875 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2879 * Compiles list of active page restrictions from both page table (pre 1.10)
2880 * and page_restrictions table for this existing page.
2881 * Public for usage by LiquidThreads.
2883 * @param array $rows Array of db result objects
2884 * @param string $oldFashionedRestrictions Comma-separated list of page
2885 * restrictions from page table (pre 1.10)
2887 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2888 global $wgContLang;
2889 $dbr = wfGetDB( DB_SLAVE );
2891 $restrictionTypes = $this->getRestrictionTypes();
2893 foreach ( $restrictionTypes as $type ) {
2894 $this->mRestrictions[$type] = array();
2895 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2898 $this->mCascadeRestriction = false;
2900 # Backwards-compatibility: also load the restrictions from the page record (old format).
2902 if ( $oldFashionedRestrictions === null ) {
2903 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2904 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2907 if ( $oldFashionedRestrictions != '' ) {
2909 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2910 $temp = explode( '=', trim( $restrict ) );
2911 if ( count( $temp ) == 1 ) {
2912 // old old format should be treated as edit/move restriction
2913 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2914 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2915 } else {
2916 $restriction = trim( $temp[1] );
2917 if ( $restriction != '' ) { //some old entries are empty
2918 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2923 $this->mOldRestrictions = true;
2927 if ( count( $rows ) ) {
2928 # Current system - load second to make them override.
2929 $now = wfTimestampNow();
2931 # Cycle through all the restrictions.
2932 foreach ( $rows as $row ) {
2934 // Don't take care of restrictions types that aren't allowed
2935 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2936 continue;
2939 // This code should be refactored, now that it's being used more generally,
2940 // But I don't really see any harm in leaving it in Block for now -werdna
2941 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2943 // Only apply the restrictions if they haven't expired!
2944 if ( !$expiry || $expiry > $now ) {
2945 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2946 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2948 $this->mCascadeRestriction |= $row->pr_cascade;
2953 $this->mRestrictionsLoaded = true;
2957 * Load restrictions from the page_restrictions table
2959 * @param string $oldFashionedRestrictions Comma-separated list of page
2960 * restrictions from page table (pre 1.10)
2962 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2963 global $wgContLang;
2964 if ( !$this->mRestrictionsLoaded ) {
2965 if ( $this->exists() ) {
2966 $dbr = wfGetDB( DB_SLAVE );
2968 $res = $dbr->select(
2969 'page_restrictions',
2970 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2971 array( 'pr_page' => $this->getArticleID() ),
2972 __METHOD__
2975 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2976 } else {
2977 $title_protection = $this->getTitleProtection();
2979 if ( $title_protection ) {
2980 $now = wfTimestampNow();
2981 $expiry = $wgContLang->formatExpiry( $title_protection['expiry'], TS_MW );
2983 if ( !$expiry || $expiry > $now ) {
2984 // Apply the restrictions
2985 $this->mRestrictionsExpiry['create'] = $expiry;
2986 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['permission'] ) );
2987 } else { // Get rid of the old restrictions
2988 $this->mTitleProtection = false;
2990 } else {
2991 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2993 $this->mRestrictionsLoaded = true;
2999 * Flush the protection cache in this object and force reload from the database.
3000 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3002 public function flushRestrictions() {
3003 $this->mRestrictionsLoaded = false;
3004 $this->mTitleProtection = null;
3008 * Purge expired restrictions from the page_restrictions table
3010 static function purgeExpiredRestrictions() {
3011 if ( wfReadOnly() ) {
3012 return;
3015 $method = __METHOD__;
3016 $dbw = wfGetDB( DB_MASTER );
3017 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3018 $dbw->delete(
3019 'page_restrictions',
3020 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3021 $method
3023 $dbw->delete(
3024 'protected_titles',
3025 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3026 $method
3028 } );
3032 * Does this have subpages? (Warning, usually requires an extra DB query.)
3034 * @return bool
3036 public function hasSubpages() {
3037 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3038 # Duh
3039 return false;
3042 # We dynamically add a member variable for the purpose of this method
3043 # alone to cache the result. There's no point in having it hanging
3044 # around uninitialized in every Title object; therefore we only add it
3045 # if needed and don't declare it statically.
3046 if ( $this->mHasSubpages === null ) {
3047 $this->mHasSubpages = false;
3048 $subpages = $this->getSubpages( 1 );
3049 if ( $subpages instanceof TitleArray ) {
3050 $this->mHasSubpages = (bool)$subpages->count();
3054 return $this->mHasSubpages;
3058 * Get all subpages of this page.
3060 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3061 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3062 * doesn't allow subpages
3064 public function getSubpages( $limit = -1 ) {
3065 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3066 return array();
3069 $dbr = wfGetDB( DB_SLAVE );
3070 $conds['page_namespace'] = $this->getNamespace();
3071 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3072 $options = array();
3073 if ( $limit > -1 ) {
3074 $options['LIMIT'] = $limit;
3076 $this->mSubpages = TitleArray::newFromResult(
3077 $dbr->select( 'page',
3078 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3079 $conds,
3080 __METHOD__,
3081 $options
3084 return $this->mSubpages;
3088 * Is there a version of this page in the deletion archive?
3090 * @return int The number of archived revisions
3092 public function isDeleted() {
3093 if ( $this->getNamespace() < 0 ) {
3094 $n = 0;
3095 } else {
3096 $dbr = wfGetDB( DB_SLAVE );
3098 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3099 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3100 __METHOD__
3102 if ( $this->getNamespace() == NS_FILE ) {
3103 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3104 array( 'fa_name' => $this->getDBkey() ),
3105 __METHOD__
3109 return (int)$n;
3113 * Is there a version of this page in the deletion archive?
3115 * @return bool
3117 public function isDeletedQuick() {
3118 if ( $this->getNamespace() < 0 ) {
3119 return false;
3121 $dbr = wfGetDB( DB_SLAVE );
3122 $deleted = (bool)$dbr->selectField( 'archive', '1',
3123 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3124 __METHOD__
3126 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3127 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3128 array( 'fa_name' => $this->getDBkey() ),
3129 __METHOD__
3132 return $deleted;
3136 * Get the article ID for this Title from the link cache,
3137 * adding it if necessary
3139 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3140 * for update
3141 * @return int The ID
3143 public function getArticleID( $flags = 0 ) {
3144 if ( $this->getNamespace() < 0 ) {
3145 $this->mArticleID = 0;
3146 return $this->mArticleID;
3148 $linkCache = LinkCache::singleton();
3149 if ( $flags & self::GAID_FOR_UPDATE ) {
3150 $oldUpdate = $linkCache->forUpdate( true );
3151 $linkCache->clearLink( $this );
3152 $this->mArticleID = $linkCache->addLinkObj( $this );
3153 $linkCache->forUpdate( $oldUpdate );
3154 } else {
3155 if ( -1 == $this->mArticleID ) {
3156 $this->mArticleID = $linkCache->addLinkObj( $this );
3159 return $this->mArticleID;
3163 * Is this an article that is a redirect page?
3164 * Uses link cache, adding it if necessary
3166 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3167 * @return bool
3169 public function isRedirect( $flags = 0 ) {
3170 if ( !is_null( $this->mRedirect ) ) {
3171 return $this->mRedirect;
3173 if ( !$this->getArticleID( $flags ) ) {
3174 $this->mRedirect = false;
3175 return $this->mRedirect;
3178 $linkCache = LinkCache::singleton();
3179 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3180 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3181 if ( $cached === null ) {
3182 # Trust LinkCache's state over our own
3183 # LinkCache is telling us that the page doesn't exist, despite there being cached
3184 # data relating to an existing page in $this->mArticleID. Updaters should clear
3185 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3186 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3187 # LinkCache to refresh its data from the master.
3188 $this->mRedirect = false;
3189 return $this->mRedirect;
3192 $this->mRedirect = (bool)$cached;
3194 return $this->mRedirect;
3198 * What is the length of this page?
3199 * Uses link cache, adding it if necessary
3201 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3202 * @return int
3204 public function getLength( $flags = 0 ) {
3205 if ( $this->mLength != -1 ) {
3206 return $this->mLength;
3208 if ( !$this->getArticleID( $flags ) ) {
3209 $this->mLength = 0;
3210 return $this->mLength;
3212 $linkCache = LinkCache::singleton();
3213 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3214 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3215 if ( $cached === null ) {
3216 # Trust LinkCache's state over our own, as for isRedirect()
3217 $this->mLength = 0;
3218 return $this->mLength;
3221 $this->mLength = intval( $cached );
3223 return $this->mLength;
3227 * What is the page_latest field for this page?
3229 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3230 * @return int Int or 0 if the page doesn't exist
3232 public function getLatestRevID( $flags = 0 ) {
3233 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3234 return intval( $this->mLatestID );
3236 if ( !$this->getArticleID( $flags ) ) {
3237 $this->mLatestID = 0;
3238 return $this->mLatestID;
3240 $linkCache = LinkCache::singleton();
3241 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3242 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3243 if ( $cached === null ) {
3244 # Trust LinkCache's state over our own, as for isRedirect()
3245 $this->mLatestID = 0;
3246 return $this->mLatestID;
3249 $this->mLatestID = intval( $cached );
3251 return $this->mLatestID;
3255 * This clears some fields in this object, and clears any associated
3256 * keys in the "bad links" section of the link cache.
3258 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3259 * loading of the new page_id. It's also called from
3260 * WikiPage::doDeleteArticleReal()
3262 * @param int $newid The new Article ID
3264 public function resetArticleID( $newid ) {
3265 $linkCache = LinkCache::singleton();
3266 $linkCache->clearLink( $this );
3268 if ( $newid === false ) {
3269 $this->mArticleID = -1;
3270 } else {
3271 $this->mArticleID = intval( $newid );
3273 $this->mRestrictionsLoaded = false;
3274 $this->mRestrictions = array();
3275 $this->mRedirect = null;
3276 $this->mLength = -1;
3277 $this->mLatestID = false;
3278 $this->mContentModel = false;
3279 $this->mEstimateRevisions = null;
3280 $this->mPageLanguage = false;
3281 $this->mDbPageLanguage = null;
3282 $this->mIsBigDeletion = null;
3286 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3288 * @param string $text Containing title to capitalize
3289 * @param int $ns Namespace index, defaults to NS_MAIN
3290 * @return string Containing capitalized title
3292 public static function capitalize( $text, $ns = NS_MAIN ) {
3293 global $wgContLang;
3295 if ( MWNamespace::isCapitalized( $ns ) ) {
3296 return $wgContLang->ucfirst( $text );
3297 } else {
3298 return $text;
3303 * Secure and split - main initialisation function for this object
3305 * Assumes that mDbkeyform has been set, and is urldecoded
3306 * and uses underscores, but not otherwise munged. This function
3307 * removes illegal characters, splits off the interwiki and
3308 * namespace prefixes, sets the other forms, and canonicalizes
3309 * everything.
3311 * @return bool True on success
3313 private function secureAndSplit() {
3314 # Initialisation
3315 $this->mInterwiki = '';
3316 $this->mFragment = '';
3317 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3319 $dbkey = $this->mDbkeyform;
3321 try {
3322 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3323 // the parsing code with Title, while avoiding massive refactoring.
3324 // @todo: get rid of secureAndSplit, refactor parsing code.
3325 $titleParser = self::getTitleParser();
3326 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3327 } catch ( MalformedTitleException $ex ) {
3328 return false;
3331 # Fill fields
3332 $this->setFragment( '#' . $parts['fragment'] );
3333 $this->mInterwiki = $parts['interwiki'];
3334 $this->mLocalInterwiki = $parts['local_interwiki'];
3335 $this->mNamespace = $parts['namespace'];
3336 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3338 $this->mDbkeyform = $parts['dbkey'];
3339 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3340 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3342 # We already know that some pages won't be in the database!
3343 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3344 $this->mArticleID = 0;
3347 return true;
3351 * Get an array of Title objects linking to this Title
3352 * Also stores the IDs in the link cache.
3354 * WARNING: do not use this function on arbitrary user-supplied titles!
3355 * On heavily-used templates it will max out the memory.
3357 * @param array $options May be FOR UPDATE
3358 * @param string $table Table name
3359 * @param string $prefix Fields prefix
3360 * @return Title[] Array of Title objects linking here
3362 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3363 if ( count( $options ) > 0 ) {
3364 $db = wfGetDB( DB_MASTER );
3365 } else {
3366 $db = wfGetDB( DB_SLAVE );
3369 $res = $db->select(
3370 array( 'page', $table ),
3371 self::getSelectFields(),
3372 array(
3373 "{$prefix}_from=page_id",
3374 "{$prefix}_namespace" => $this->getNamespace(),
3375 "{$prefix}_title" => $this->getDBkey() ),
3376 __METHOD__,
3377 $options
3380 $retVal = array();
3381 if ( $res->numRows() ) {
3382 $linkCache = LinkCache::singleton();
3383 foreach ( $res as $row ) {
3384 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3385 if ( $titleObj ) {
3386 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3387 $retVal[] = $titleObj;
3391 return $retVal;
3395 * Get an array of Title objects using this Title as a template
3396 * Also stores the IDs in the link cache.
3398 * WARNING: do not use this function on arbitrary user-supplied titles!
3399 * On heavily-used templates it will max out the memory.
3401 * @param array $options May be FOR UPDATE
3402 * @return Title[] Array of Title the Title objects linking here
3404 public function getTemplateLinksTo( $options = array() ) {
3405 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3409 * Get an array of Title objects linked from this Title
3410 * Also stores the IDs in the link cache.
3412 * WARNING: do not use this function on arbitrary user-supplied titles!
3413 * On heavily-used templates it will max out the memory.
3415 * @param array $options May be FOR UPDATE
3416 * @param string $table Table name
3417 * @param string $prefix Fields prefix
3418 * @return array Array of Title objects linking here
3420 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3421 global $wgContentHandlerUseDB;
3423 $id = $this->getArticleID();
3425 # If the page doesn't exist; there can't be any link from this page
3426 if ( !$id ) {
3427 return array();
3430 if ( count( $options ) > 0 ) {
3431 $db = wfGetDB( DB_MASTER );
3432 } else {
3433 $db = wfGetDB( DB_SLAVE );
3436 $namespaceFiled = "{$prefix}_namespace";
3437 $titleField = "{$prefix}_title";
3439 $fields = array(
3440 $namespaceFiled,
3441 $titleField,
3442 'page_id',
3443 'page_len',
3444 'page_is_redirect',
3445 'page_latest'
3448 if ( $wgContentHandlerUseDB ) {
3449 $fields[] = 'page_content_model';
3452 $res = $db->select(
3453 array( $table, 'page' ),
3454 $fields,
3455 array( "{$prefix}_from" => $id ),
3456 __METHOD__,
3457 $options,
3458 array( 'page' => array(
3459 'LEFT JOIN',
3460 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3464 $retVal = array();
3465 if ( $res->numRows() ) {
3466 $linkCache = LinkCache::singleton();
3467 foreach ( $res as $row ) {
3468 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3469 if ( $titleObj ) {
3470 if ( $row->page_id ) {
3471 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3472 } else {
3473 $linkCache->addBadLinkObj( $titleObj );
3475 $retVal[] = $titleObj;
3479 return $retVal;
3483 * Get an array of Title objects used on this Title as a template
3484 * Also stores the IDs in the link cache.
3486 * WARNING: do not use this function on arbitrary user-supplied titles!
3487 * On heavily-used templates it will max out the memory.
3489 * @param array $options May be FOR UPDATE
3490 * @return Title[] Array of Title the Title objects used here
3492 public function getTemplateLinksFrom( $options = array() ) {
3493 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3497 * Get an array of Title objects referring to non-existent articles linked
3498 * from this page.
3500 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3501 * should use redirect table in this case).
3502 * @return Title[] Array of Title the Title objects
3504 public function getBrokenLinksFrom() {
3505 if ( $this->getArticleID() == 0 ) {
3506 # All links from article ID 0 are false positives
3507 return array();
3510 $dbr = wfGetDB( DB_SLAVE );
3511 $res = $dbr->select(
3512 array( 'page', 'pagelinks' ),
3513 array( 'pl_namespace', 'pl_title' ),
3514 array(
3515 'pl_from' => $this->getArticleID(),
3516 'page_namespace IS NULL'
3518 __METHOD__, array(),
3519 array(
3520 'page' => array(
3521 'LEFT JOIN',
3522 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3527 $retVal = array();
3528 foreach ( $res as $row ) {
3529 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3531 return $retVal;
3535 * Get a list of URLs to purge from the Squid cache when this
3536 * page changes
3538 * @return string[] Array of String the URLs
3540 public function getSquidURLs() {
3541 $urls = array(
3542 $this->getInternalURL(),
3543 $this->getInternalURL( 'action=history' )
3546 $pageLang = $this->getPageLanguage();
3547 if ( $pageLang->hasVariants() ) {
3548 $variants = $pageLang->getVariants();
3549 foreach ( $variants as $vCode ) {
3550 $urls[] = $this->getInternalURL( '', $vCode );
3554 // If we are looking at a css/js user subpage, purge the action=raw.
3555 if ( $this->isJsSubpage() ) {
3556 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3557 } elseif ( $this->isCssSubpage() ) {
3558 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3561 Hooks::run( 'TitleSquidURLs', array( $this, &$urls ) );
3562 return $urls;
3566 * Purge all applicable Squid URLs
3568 public function purgeSquid() {
3569 global $wgUseSquid;
3570 if ( $wgUseSquid ) {
3571 $urls = $this->getSquidURLs();
3572 $u = new SquidUpdate( $urls );
3573 $u->doUpdate();
3578 * Move this page without authentication
3580 * @deprecated since 1.25 use MovePage class instead
3581 * @param Title $nt The new page Title
3582 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3584 public function moveNoAuth( &$nt ) {
3585 wfDeprecated( __METHOD__, '1.25' );
3586 return $this->moveTo( $nt, false );
3590 * Check whether a given move operation would be valid.
3591 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3593 * @deprecated since 1.25, use MovePage's methods instead
3594 * @param Title $nt The new title
3595 * @param bool $auth Whether to check user permissions (uses $wgUser)
3596 * @param string $reason Is the log summary of the move, used for spam checking
3597 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3599 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3600 global $wgUser;
3602 if ( !( $nt instanceof Title ) ) {
3603 // Normally we'd add this to $errors, but we'll get
3604 // lots of syntax errors if $nt is not an object
3605 return array( array( 'badtitletext' ) );
3608 $mp = new MovePage( $this, $nt );
3609 $errors = $mp->isValidMove()->getErrorsArray();
3610 if ( $auth ) {
3611 $errors = wfMergeErrorArrays(
3612 $errors,
3613 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3617 return $errors ? : true;
3621 * Check if the requested move target is a valid file move target
3622 * @todo move this to MovePage
3623 * @param Title $nt Target title
3624 * @return array List of errors
3626 protected function validateFileMoveOperation( $nt ) {
3627 global $wgUser;
3629 $errors = array();
3631 $destFile = wfLocalFile( $nt );
3632 $destFile->load( File::READ_LATEST );
3633 if ( !$wgUser->isAllowed( 'reupload-shared' )
3634 && !$destFile->exists() && wfFindFile( $nt )
3636 $errors[] = array( 'file-exists-sharedrepo' );
3639 return $errors;
3643 * Move a title to a new location
3645 * @deprecated since 1.25, use the MovePage class instead
3646 * @param Title $nt The new title
3647 * @param bool $auth Indicates whether $wgUser's permissions
3648 * should be checked
3649 * @param string $reason The reason for the move
3650 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3651 * Ignored if the user doesn't have the suppressredirect right.
3652 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3654 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3655 global $wgUser;
3656 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3657 if ( is_array( $err ) ) {
3658 // Auto-block user's IP if the account was "hard" blocked
3659 $wgUser->spreadAnyEditBlock();
3660 return $err;
3662 // Check suppressredirect permission
3663 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3664 $createRedirect = true;
3667 $mp = new MovePage( $this, $nt );
3668 $status = $mp->move( $wgUser, $reason, $createRedirect );
3669 if ( $status->isOK() ) {
3670 return true;
3671 } else {
3672 return $status->getErrorsArray();
3677 * Move this page's subpages to be subpages of $nt
3679 * @param Title $nt Move target
3680 * @param bool $auth Whether $wgUser's permissions should be checked
3681 * @param string $reason The reason for the move
3682 * @param bool $createRedirect Whether to create redirects from the old subpages to
3683 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3684 * @return array Array with old page titles as keys, and strings (new page titles) or
3685 * arrays (errors) as values, or an error array with numeric indices if no pages
3686 * were moved
3688 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3689 global $wgMaximumMovedPages;
3690 // Check permissions
3691 if ( !$this->userCan( 'move-subpages' ) ) {
3692 return array( 'cant-move-subpages' );
3694 // Do the source and target namespaces support subpages?
3695 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3696 return array( 'namespace-nosubpages',
3697 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3699 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3700 return array( 'namespace-nosubpages',
3701 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3704 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3705 $retval = array();
3706 $count = 0;
3707 foreach ( $subpages as $oldSubpage ) {
3708 $count++;
3709 if ( $count > $wgMaximumMovedPages ) {
3710 $retval[$oldSubpage->getPrefixedText()] =
3711 array( 'movepage-max-pages',
3712 $wgMaximumMovedPages );
3713 break;
3716 // We don't know whether this function was called before
3717 // or after moving the root page, so check both
3718 // $this and $nt
3719 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3720 || $oldSubpage->getArticleID() == $nt->getArticleID()
3722 // When moving a page to a subpage of itself,
3723 // don't move it twice
3724 continue;
3726 $newPageName = preg_replace(
3727 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3728 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3729 $oldSubpage->getDBkey() );
3730 if ( $oldSubpage->isTalkPage() ) {
3731 $newNs = $nt->getTalkPage()->getNamespace();
3732 } else {
3733 $newNs = $nt->getSubjectPage()->getNamespace();
3735 # Bug 14385: we need makeTitleSafe because the new page names may
3736 # be longer than 255 characters.
3737 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3739 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3740 if ( $success === true ) {
3741 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3742 } else {
3743 $retval[$oldSubpage->getPrefixedText()] = $success;
3746 return $retval;
3750 * Checks if this page is just a one-rev redirect.
3751 * Adds lock, so don't use just for light purposes.
3753 * @return bool
3755 public function isSingleRevRedirect() {
3756 global $wgContentHandlerUseDB;
3758 $dbw = wfGetDB( DB_MASTER );
3760 # Is it a redirect?
3761 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3762 if ( $wgContentHandlerUseDB ) {
3763 $fields[] = 'page_content_model';
3766 $row = $dbw->selectRow( 'page',
3767 $fields,
3768 $this->pageCond(),
3769 __METHOD__,
3770 array( 'FOR UPDATE' )
3772 # Cache some fields we may want
3773 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3774 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3775 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3776 $this->mContentModel = $row && isset( $row->page_content_model )
3777 ? strval( $row->page_content_model )
3778 : false;
3780 if ( !$this->mRedirect ) {
3781 return false;
3783 # Does the article have a history?
3784 $row = $dbw->selectField( array( 'page', 'revision' ),
3785 'rev_id',
3786 array( 'page_namespace' => $this->getNamespace(),
3787 'page_title' => $this->getDBkey(),
3788 'page_id=rev_page',
3789 'page_latest != rev_id'
3791 __METHOD__,
3792 array( 'FOR UPDATE' )
3794 # Return true if there was no history
3795 return ( $row === false );
3799 * Checks if $this can be moved to a given Title
3800 * - Selects for update, so don't call it unless you mean business
3802 * @deprecated since 1.25, use MovePage's methods instead
3803 * @param Title $nt The new title to check
3804 * @return bool
3806 public function isValidMoveTarget( $nt ) {
3807 # Is it an existing file?
3808 if ( $nt->getNamespace() == NS_FILE ) {
3809 $file = wfLocalFile( $nt );
3810 $file->load( File::READ_LATEST );
3811 if ( $file->exists() ) {
3812 wfDebug( __METHOD__ . ": file exists\n" );
3813 return false;
3816 # Is it a redirect with no history?
3817 if ( !$nt->isSingleRevRedirect() ) {
3818 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3819 return false;
3821 # Get the article text
3822 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3823 if ( !is_object( $rev ) ) {
3824 return false;
3826 $content = $rev->getContent();
3827 # Does the redirect point to the source?
3828 # Or is it a broken self-redirect, usually caused by namespace collisions?
3829 $redirTitle = $content ? $content->getRedirectTarget() : null;
3831 if ( $redirTitle ) {
3832 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3833 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3834 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3835 return false;
3836 } else {
3837 return true;
3839 } else {
3840 # Fail safe (not a redirect after all. strange.)
3841 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3842 " is a redirect, but it doesn't contain a valid redirect.\n" );
3843 return false;
3848 * Get categories to which this Title belongs and return an array of
3849 * categories' names.
3851 * @return array Array of parents in the form:
3852 * $parent => $currentarticle
3854 public function getParentCategories() {
3855 global $wgContLang;
3857 $data = array();
3859 $titleKey = $this->getArticleID();
3861 if ( $titleKey === 0 ) {
3862 return $data;
3865 $dbr = wfGetDB( DB_SLAVE );
3867 $res = $dbr->select(
3868 'categorylinks',
3869 'cl_to',
3870 array( 'cl_from' => $titleKey ),
3871 __METHOD__
3874 if ( $res->numRows() > 0 ) {
3875 foreach ( $res as $row ) {
3876 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3877 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3880 return $data;
3884 * Get a tree of parent categories
3886 * @param array $children Array with the children in the keys, to check for circular refs
3887 * @return array Tree of parent categories
3889 public function getParentCategoryTree( $children = array() ) {
3890 $stack = array();
3891 $parents = $this->getParentCategories();
3893 if ( $parents ) {
3894 foreach ( $parents as $parent => $current ) {
3895 if ( array_key_exists( $parent, $children ) ) {
3896 # Circular reference
3897 $stack[$parent] = array();
3898 } else {
3899 $nt = Title::newFromText( $parent );
3900 if ( $nt ) {
3901 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3907 return $stack;
3911 * Get an associative array for selecting this title from
3912 * the "page" table
3914 * @return array Array suitable for the $where parameter of DB::select()
3916 public function pageCond() {
3917 if ( $this->mArticleID > 0 ) {
3918 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3919 return array( 'page_id' => $this->mArticleID );
3920 } else {
3921 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3926 * Get the revision ID of the previous revision
3928 * @param int $revId Revision ID. Get the revision that was before this one.
3929 * @param int $flags Title::GAID_FOR_UPDATE
3930 * @return int|bool Old revision ID, or false if none exists
3932 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3933 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3934 $revId = $db->selectField( 'revision', 'rev_id',
3935 array(
3936 'rev_page' => $this->getArticleID( $flags ),
3937 'rev_id < ' . intval( $revId )
3939 __METHOD__,
3940 array( 'ORDER BY' => 'rev_id DESC' )
3943 if ( $revId === false ) {
3944 return false;
3945 } else {
3946 return intval( $revId );
3951 * Get the revision ID of the next revision
3953 * @param int $revId Revision ID. Get the revision that was after this one.
3954 * @param int $flags Title::GAID_FOR_UPDATE
3955 * @return int|bool Next revision ID, or false if none exists
3957 public function getNextRevisionID( $revId, $flags = 0 ) {
3958 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3959 $revId = $db->selectField( 'revision', 'rev_id',
3960 array(
3961 'rev_page' => $this->getArticleID( $flags ),
3962 'rev_id > ' . intval( $revId )
3964 __METHOD__,
3965 array( 'ORDER BY' => 'rev_id' )
3968 if ( $revId === false ) {
3969 return false;
3970 } else {
3971 return intval( $revId );
3976 * Get the first revision of the page
3978 * @param int $flags Title::GAID_FOR_UPDATE
3979 * @return Revision|null If page doesn't exist
3981 public function getFirstRevision( $flags = 0 ) {
3982 $pageId = $this->getArticleID( $flags );
3983 if ( $pageId ) {
3984 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3985 $row = $db->selectRow( 'revision', Revision::selectFields(),
3986 array( 'rev_page' => $pageId ),
3987 __METHOD__,
3988 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3990 if ( $row ) {
3991 return new Revision( $row );
3994 return null;
3998 * Get the oldest revision timestamp of this page
4000 * @param int $flags Title::GAID_FOR_UPDATE
4001 * @return string MW timestamp
4003 public function getEarliestRevTime( $flags = 0 ) {
4004 $rev = $this->getFirstRevision( $flags );
4005 return $rev ? $rev->getTimestamp() : null;
4009 * Check if this is a new page
4011 * @return bool
4013 public function isNewPage() {
4014 $dbr = wfGetDB( DB_SLAVE );
4015 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4019 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4021 * @return bool
4023 public function isBigDeletion() {
4024 global $wgDeleteRevisionsLimit;
4026 if ( !$wgDeleteRevisionsLimit ) {
4027 return false;
4030 if ( $this->mIsBigDeletion === null ) {
4031 $dbr = wfGetDB( DB_SLAVE );
4033 $revCount = $dbr->selectRowCount(
4034 'revision',
4035 '1',
4036 array( 'rev_page' => $this->getArticleID() ),
4037 __METHOD__,
4038 array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 )
4041 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4044 return $this->mIsBigDeletion;
4048 * Get the approximate revision count of this page.
4050 * @return int
4052 public function estimateRevisionCount() {
4053 if ( !$this->exists() ) {
4054 return 0;
4057 if ( $this->mEstimateRevisions === null ) {
4058 $dbr = wfGetDB( DB_SLAVE );
4059 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4060 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4063 return $this->mEstimateRevisions;
4067 * Get the number of revisions between the given revision.
4068 * Used for diffs and other things that really need it.
4070 * @param int|Revision $old Old revision or rev ID (first before range)
4071 * @param int|Revision $new New revision or rev ID (first after range)
4072 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4073 * @return int Number of revisions between these revisions.
4075 public function countRevisionsBetween( $old, $new, $max = null ) {
4076 if ( !( $old instanceof Revision ) ) {
4077 $old = Revision::newFromTitle( $this, (int)$old );
4079 if ( !( $new instanceof Revision ) ) {
4080 $new = Revision::newFromTitle( $this, (int)$new );
4082 if ( !$old || !$new ) {
4083 return 0; // nothing to compare
4085 $dbr = wfGetDB( DB_SLAVE );
4086 $conds = array(
4087 'rev_page' => $this->getArticleID(),
4088 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4089 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4091 if ( $max !== null ) {
4092 return $dbr->selectRowCount( 'revision', '1',
4093 $conds,
4094 __METHOD__,
4095 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4097 } else {
4098 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4103 * Get the authors between the given revisions or revision IDs.
4104 * Used for diffs and other things that really need it.
4106 * @since 1.23
4108 * @param int|Revision $old Old revision or rev ID (first before range by default)
4109 * @param int|Revision $new New revision or rev ID (first after range by default)
4110 * @param int $limit Maximum number of authors
4111 * @param string|array $options (Optional): Single option, or an array of options:
4112 * 'include_old' Include $old in the range; $new is excluded.
4113 * 'include_new' Include $new in the range; $old is excluded.
4114 * 'include_both' Include both $old and $new in the range.
4115 * Unknown option values are ignored.
4116 * @return array|null Names of revision authors in the range; null if not both revisions exist
4118 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4119 if ( !( $old instanceof Revision ) ) {
4120 $old = Revision::newFromTitle( $this, (int)$old );
4122 if ( !( $new instanceof Revision ) ) {
4123 $new = Revision::newFromTitle( $this, (int)$new );
4125 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4126 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4127 // in the sanity check below?
4128 if ( !$old || !$new ) {
4129 return null; // nothing to compare
4131 $authors = array();
4132 $old_cmp = '>';
4133 $new_cmp = '<';
4134 $options = (array)$options;
4135 if ( in_array( 'include_old', $options ) ) {
4136 $old_cmp = '>=';
4138 if ( in_array( 'include_new', $options ) ) {
4139 $new_cmp = '<=';
4141 if ( in_array( 'include_both', $options ) ) {
4142 $old_cmp = '>=';
4143 $new_cmp = '<=';
4145 // No DB query needed if $old and $new are the same or successive revisions:
4146 if ( $old->getId() === $new->getId() ) {
4147 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4148 array() :
4149 array( $old->getUserText( Revision::RAW ) );
4150 } elseif ( $old->getId() === $new->getParentId() ) {
4151 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4152 $authors[] = $old->getUserText( Revision::RAW );
4153 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4154 $authors[] = $new->getUserText( Revision::RAW );
4156 } elseif ( $old_cmp === '>=' ) {
4157 $authors[] = $old->getUserText( Revision::RAW );
4158 } elseif ( $new_cmp === '<=' ) {
4159 $authors[] = $new->getUserText( Revision::RAW );
4161 return $authors;
4163 $dbr = wfGetDB( DB_SLAVE );
4164 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4165 array(
4166 'rev_page' => $this->getArticleID(),
4167 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4168 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4169 ), __METHOD__,
4170 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4172 foreach ( $res as $row ) {
4173 $authors[] = $row->rev_user_text;
4175 return $authors;
4179 * Get the number of authors between the given revisions or revision IDs.
4180 * Used for diffs and other things that really need it.
4182 * @param int|Revision $old Old revision or rev ID (first before range by default)
4183 * @param int|Revision $new New revision or rev ID (first after range by default)
4184 * @param int $limit Maximum number of authors
4185 * @param string|array $options (Optional): Single option, or an array of options:
4186 * 'include_old' Include $old in the range; $new is excluded.
4187 * 'include_new' Include $new in the range; $old is excluded.
4188 * 'include_both' Include both $old and $new in the range.
4189 * Unknown option values are ignored.
4190 * @return int Number of revision authors in the range; zero if not both revisions exist
4192 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4193 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4194 return $authors ? count( $authors ) : 0;
4198 * Compare with another title.
4200 * @param Title $title
4201 * @return bool
4203 public function equals( Title $title ) {
4204 // Note: === is necessary for proper matching of number-like titles.
4205 return $this->getInterwiki() === $title->getInterwiki()
4206 && $this->getNamespace() == $title->getNamespace()
4207 && $this->getDBkey() === $title->getDBkey();
4211 * Check if this title is a subpage of another title
4213 * @param Title $title
4214 * @return bool
4216 public function isSubpageOf( Title $title ) {
4217 return $this->getInterwiki() === $title->getInterwiki()
4218 && $this->getNamespace() == $title->getNamespace()
4219 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4223 * Check if page exists. For historical reasons, this function simply
4224 * checks for the existence of the title in the page table, and will
4225 * thus return false for interwiki links, special pages and the like.
4226 * If you want to know if a title can be meaningfully viewed, you should
4227 * probably call the isKnown() method instead.
4229 * @return bool
4231 public function exists() {
4232 $exists = $this->getArticleID() != 0;
4233 Hooks::run( 'TitleExists', array( $this, &$exists ) );
4234 return $exists;
4238 * Should links to this title be shown as potentially viewable (i.e. as
4239 * "bluelinks"), even if there's no record by this title in the page
4240 * table?
4242 * This function is semi-deprecated for public use, as well as somewhat
4243 * misleadingly named. You probably just want to call isKnown(), which
4244 * calls this function internally.
4246 * (ISSUE: Most of these checks are cheap, but the file existence check
4247 * can potentially be quite expensive. Including it here fixes a lot of
4248 * existing code, but we might want to add an optional parameter to skip
4249 * it and any other expensive checks.)
4251 * @return bool
4253 public function isAlwaysKnown() {
4254 $isKnown = null;
4257 * Allows overriding default behavior for determining if a page exists.
4258 * If $isKnown is kept as null, regular checks happen. If it's
4259 * a boolean, this value is returned by the isKnown method.
4261 * @since 1.20
4263 * @param Title $title
4264 * @param bool|null $isKnown
4266 Hooks::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4268 if ( !is_null( $isKnown ) ) {
4269 return $isKnown;
4272 if ( $this->isExternal() ) {
4273 return true; // any interwiki link might be viewable, for all we know
4276 switch ( $this->mNamespace ) {
4277 case NS_MEDIA:
4278 case NS_FILE:
4279 // file exists, possibly in a foreign repo
4280 return (bool)wfFindFile( $this );
4281 case NS_SPECIAL:
4282 // valid special page
4283 return SpecialPageFactory::exists( $this->getDBkey() );
4284 case NS_MAIN:
4285 // selflink, possibly with fragment
4286 return $this->mDbkeyform == '';
4287 case NS_MEDIAWIKI:
4288 // known system message
4289 return $this->hasSourceText() !== false;
4290 default:
4291 return false;
4296 * Does this title refer to a page that can (or might) be meaningfully
4297 * viewed? In particular, this function may be used to determine if
4298 * links to the title should be rendered as "bluelinks" (as opposed to
4299 * "redlinks" to non-existent pages).
4300 * Adding something else to this function will cause inconsistency
4301 * since LinkHolderArray calls isAlwaysKnown() and does its own
4302 * page existence check.
4304 * @return bool
4306 public function isKnown() {
4307 return $this->isAlwaysKnown() || $this->exists();
4311 * Does this page have source text?
4313 * @return bool
4315 public function hasSourceText() {
4316 if ( $this->exists() ) {
4317 return true;
4320 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4321 // If the page doesn't exist but is a known system message, default
4322 // message content will be displayed, same for language subpages-
4323 // Use always content language to avoid loading hundreds of languages
4324 // to get the link color.
4325 global $wgContLang;
4326 list( $name, ) = MessageCache::singleton()->figureMessage(
4327 $wgContLang->lcfirst( $this->getText() )
4329 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4330 return $message->exists();
4333 return false;
4337 * Get the default message text or false if the message doesn't exist
4339 * @return string|bool
4341 public function getDefaultMessageText() {
4342 global $wgContLang;
4344 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4345 return false;
4348 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4349 $wgContLang->lcfirst( $this->getText() )
4351 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4353 if ( $message->exists() ) {
4354 return $message->plain();
4355 } else {
4356 return false;
4361 * Updates page_touched for this page; called from LinksUpdate.php
4363 * @return bool True if the update succeeded
4365 public function invalidateCache() {
4366 if ( wfReadOnly() ) {
4367 return false;
4370 if ( $this->mArticleID === 0 ) {
4371 return true; // avoid gap locking if we know it's not there
4374 $method = __METHOD__;
4375 $dbw = wfGetDB( DB_MASTER );
4376 $conds = $this->pageCond();
4377 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4378 $dbw->update(
4379 'page',
4380 array( 'page_touched' => $dbw->timestamp() ),
4381 $conds,
4382 $method
4384 } );
4386 return true;
4390 * Update page_touched timestamps and send squid purge messages for
4391 * pages linking to this title. May be sent to the job queue depending
4392 * on the number of links. Typically called on create and delete.
4394 public function touchLinks() {
4395 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4396 $u->doUpdate();
4398 if ( $this->getNamespace() == NS_CATEGORY ) {
4399 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4400 $u->doUpdate();
4405 * Get the last touched timestamp
4407 * @param DatabaseBase $db Optional db
4408 * @return string Last-touched timestamp
4410 public function getTouched( $db = null ) {
4411 if ( $db === null ) {
4412 $db = wfGetDB( DB_SLAVE );
4414 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4415 return $touched;
4419 * Get the timestamp when this page was updated since the user last saw it.
4421 * @param User $user
4422 * @return string|null
4424 public function getNotificationTimestamp( $user = null ) {
4425 global $wgUser, $wgShowUpdatedMarker;
4426 // Assume current user if none given
4427 if ( !$user ) {
4428 $user = $wgUser;
4430 // Check cache first
4431 $uid = $user->getId();
4432 // avoid isset here, as it'll return false for null entries
4433 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4434 return $this->mNotificationTimestamp[$uid];
4436 if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) {
4437 $this->mNotificationTimestamp[$uid] = false;
4438 return $this->mNotificationTimestamp[$uid];
4440 // Don't cache too much!
4441 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4442 $this->mNotificationTimestamp = array();
4444 $dbr = wfGetDB( DB_SLAVE );
4445 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4446 'wl_notificationtimestamp',
4447 array(
4448 'wl_user' => $user->getId(),
4449 'wl_namespace' => $this->getNamespace(),
4450 'wl_title' => $this->getDBkey(),
4452 __METHOD__
4454 return $this->mNotificationTimestamp[$uid];
4458 * Generate strings used for xml 'id' names in monobook tabs
4460 * @param string $prepend Defaults to 'nstab-'
4461 * @return string XML 'id' name
4463 public function getNamespaceKey( $prepend = 'nstab-' ) {
4464 global $wgContLang;
4465 // Gets the subject namespace if this title
4466 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4467 // Checks if canonical namespace name exists for namespace
4468 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4469 // Uses canonical namespace name
4470 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4471 } else {
4472 // Uses text of namespace
4473 $namespaceKey = $this->getSubjectNsText();
4475 // Makes namespace key lowercase
4476 $namespaceKey = $wgContLang->lc( $namespaceKey );
4477 // Uses main
4478 if ( $namespaceKey == '' ) {
4479 $namespaceKey = 'main';
4481 // Changes file to image for backwards compatibility
4482 if ( $namespaceKey == 'file' ) {
4483 $namespaceKey = 'image';
4485 return $prepend . $namespaceKey;
4489 * Get all extant redirects to this Title
4491 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4492 * @return Title[] Array of Title redirects to this title
4494 public function getRedirectsHere( $ns = null ) {
4495 $redirs = array();
4497 $dbr = wfGetDB( DB_SLAVE );
4498 $where = array(
4499 'rd_namespace' => $this->getNamespace(),
4500 'rd_title' => $this->getDBkey(),
4501 'rd_from = page_id'
4503 if ( $this->isExternal() ) {
4504 $where['rd_interwiki'] = $this->getInterwiki();
4505 } else {
4506 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4508 if ( !is_null( $ns ) ) {
4509 $where['page_namespace'] = $ns;
4512 $res = $dbr->select(
4513 array( 'redirect', 'page' ),
4514 array( 'page_namespace', 'page_title' ),
4515 $where,
4516 __METHOD__
4519 foreach ( $res as $row ) {
4520 $redirs[] = self::newFromRow( $row );
4522 return $redirs;
4526 * Check if this Title is a valid redirect target
4528 * @return bool
4530 public function isValidRedirectTarget() {
4531 global $wgInvalidRedirectTargets;
4533 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4534 if ( $this->isSpecial( 'Userlogout' ) ) {
4535 return false;
4538 foreach ( $wgInvalidRedirectTargets as $target ) {
4539 if ( $this->isSpecial( $target ) ) {
4540 return false;
4544 return true;
4548 * Get a backlink cache object
4550 * @return BacklinkCache
4552 public function getBacklinkCache() {
4553 return BacklinkCache::get( $this );
4557 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4559 * @return bool
4561 public function canUseNoindex() {
4562 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4564 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4565 ? $wgContentNamespaces
4566 : $wgExemptFromUserRobotsControl;
4568 return !in_array( $this->mNamespace, $bannedNamespaces );
4573 * Returns the raw sort key to be used for categories, with the specified
4574 * prefix. This will be fed to Collation::getSortKey() to get a
4575 * binary sortkey that can be used for actual sorting.
4577 * @param string $prefix The prefix to be used, specified using
4578 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4579 * prefix.
4580 * @return string
4582 public function getCategorySortkey( $prefix = '' ) {
4583 $unprefixed = $this->getText();
4585 // Anything that uses this hook should only depend
4586 // on the Title object passed in, and should probably
4587 // tell the users to run updateCollations.php --force
4588 // in order to re-sort existing category relations.
4589 Hooks::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4590 if ( $prefix !== '' ) {
4591 # Separate with a line feed, so the unprefixed part is only used as
4592 # a tiebreaker when two pages have the exact same prefix.
4593 # In UCA, tab is the only character that can sort above LF
4594 # so we strip both of them from the original prefix.
4595 $prefix = strtr( $prefix, "\n\t", ' ' );
4596 return "$prefix\n$unprefixed";
4598 return $unprefixed;
4602 * Get the language in which the content of this page is written in
4603 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4604 * e.g. $wgLang (such as special pages, which are in the user language).
4606 * @since 1.18
4607 * @return Language
4609 public function getPageLanguage() {
4610 global $wgLang, $wgLanguageCode;
4611 if ( $this->isSpecialPage() ) {
4612 // special pages are in the user language
4613 return $wgLang;
4616 // Checking if DB language is set
4617 if ( $this->mDbPageLanguage ) {
4618 return wfGetLangObj( $this->mDbPageLanguage );
4621 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4622 // Note that this may depend on user settings, so the cache should
4623 // be only per-request.
4624 // NOTE: ContentHandler::getPageLanguage() may need to load the
4625 // content to determine the page language!
4626 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4627 // tests.
4628 $contentHandler = ContentHandler::getForTitle( $this );
4629 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4630 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4631 } else {
4632 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4635 return $langObj;
4639 * Get the language in which the content of this page is written when
4640 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4641 * e.g. $wgLang (such as special pages, which are in the user language).
4643 * @since 1.20
4644 * @return Language
4646 public function getPageViewLanguage() {
4647 global $wgLang;
4649 if ( $this->isSpecialPage() ) {
4650 // If the user chooses a variant, the content is actually
4651 // in a language whose code is the variant code.
4652 $variant = $wgLang->getPreferredVariant();
4653 if ( $wgLang->getCode() !== $variant ) {
4654 return Language::factory( $variant );
4657 return $wgLang;
4660 // @note Can't be cached persistently, depends on user settings.
4661 // @note ContentHandler::getPageViewLanguage() may need to load the
4662 // content to determine the page language!
4663 $contentHandler = ContentHandler::getForTitle( $this );
4664 $pageLang = $contentHandler->getPageViewLanguage( $this );
4665 return $pageLang;
4669 * Get a list of rendered edit notices for this page.
4671 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4672 * they will already be wrapped in paragraphs.
4674 * @since 1.21
4675 * @param int $oldid Revision ID that's being edited
4676 * @return array
4678 public function getEditNotices( $oldid = 0 ) {
4679 $notices = array();
4681 // Optional notice for the entire namespace
4682 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4683 $msg = wfMessage( $editnotice_ns );
4684 if ( $msg->exists() ) {
4685 $html = $msg->parseAsBlock();
4686 // Edit notices may have complex logic, but output nothing (T91715)
4687 if ( trim( $html ) !== '' ) {
4688 $notices[$editnotice_ns] = Html::rawElement(
4689 'div',
4690 array( 'class' => array(
4691 'mw-editnotice',
4692 'mw-editnotice-namespace',
4693 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4694 ) ),
4695 $html
4700 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4701 // Optional notice for page itself and any parent page
4702 $parts = explode( '/', $this->getDBkey() );
4703 $editnotice_base = $editnotice_ns;
4704 while ( count( $parts ) > 0 ) {
4705 $editnotice_base .= '-' . array_shift( $parts );
4706 $msg = wfMessage( $editnotice_base );
4707 if ( $msg->exists() ) {
4708 $html = $msg->parseAsBlock();
4709 if ( trim( $html ) !== '' ) {
4710 $notices[$editnotice_base] = Html::rawElement(
4711 'div',
4712 array( 'class' => array(
4713 'mw-editnotice',
4714 'mw-editnotice-base',
4715 Sanitizer::escapeClass( "mw-$editnotice_base" )
4716 ) ),
4717 $html
4722 } else {
4723 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4724 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4725 $msg = wfMessage( $editnoticeText );
4726 if ( $msg->exists() ) {
4727 $html = $msg->parseAsBlock();
4728 if ( trim( $html ) !== '' ) {
4729 $notices[$editnoticeText] = Html::rawElement(
4730 'div',
4731 array( 'class' => array(
4732 'mw-editnotice',
4733 'mw-editnotice-page',
4734 Sanitizer::escapeClass( "mw-$editnoticeText" )
4735 ) ),
4736 $html
4742 Hooks::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4743 return $notices;