Merge "Make sure images that don't have an explicit alignment get aligned right"
[mediawiki.git] / includes / Title.php
blob9d8614df44eadcc8d344b2998a705ad91f93753a
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 * @internal documentation reviewed 15 Mar 2010
35 class Title {
36 /** @var MapCacheLRU */
37 static private $titleCache = null;
39 /**
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX = 1000;
46 /**
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE = 1;
52 /**
53 * @name Private member variables
54 * Please use the accessor functions instead.
55 * @private
57 // @{
59 /** @var string Text form (spaces not underscores) of the main part */
60 public $mTextform = '';
62 /** @var string URL-encoded form of the main part */
63 public $mUrlform = '';
65 /** @var string Main part with underscores */
66 public $mDbkeyform = '';
68 /** @var string Database key with the initial letter in the case specified by the user */
69 protected $mUserCaseDBKey;
71 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
72 public $mNamespace = NS_MAIN;
74 /** @var string Interwiki prefix */
75 public $mInterwiki = '';
77 /** @var string Title fragment (i.e. the bit after the #) */
78 public $mFragment = '';
80 /** @var int Article ID, fetched from the link cache on demand */
81 public $mArticleID = -1;
83 /** @var bool|int ID of most recent revision */
84 protected $mLatestID = false;
86 /**
87 * @var bool|string ID of the page's content model, i.e. one of the
88 * CONTENT_MODEL_XXX constants
90 public $mContentModel = false;
92 /** @var int Estimated number of revisions; null of not loaded */
93 private $mEstimateRevisions;
95 /** @var array Array of groups allowed to edit this article */
96 public $mRestrictions = array();
98 /** @var bool */
99 protected $mOldRestrictions = false;
101 /** @var bool Cascade restrictions on this page to included templates and images? */
102 public $mCascadeRestriction;
104 /** Caching the results of getCascadeProtectionSources */
105 public $mCascadingRestrictions;
107 /** @var array When do the restrictions on this page expire? */
108 protected $mRestrictionsExpiry = array();
110 /** @var bool Are cascading restrictions in effect on this page? */
111 protected $mHasCascadingRestrictions;
113 /** @var array Where are the cascading restrictions coming from on this page? */
114 public $mCascadeSources;
116 /** @var bool Boolean for initialisation on demand */
117 public $mRestrictionsLoaded = false;
119 /** @var string Text form including namespace/interwiki, initialised on demand */
120 protected $mPrefixedText = null;
122 /** @var mixed Cached value for getTitleProtection (create protection) */
123 public $mTitleProtection;
126 * @var int Namespace index when there is no namespace. Don't change the
127 * following default, NS_MAIN is hardcoded in several places. See bug 696.
128 * Zero except in {{transclusion}} tags.
130 public $mDefaultNamespace = NS_MAIN;
133 * @var bool Is $wgUser watching this page? null if unfilled, accessed
134 * through userIsWatching()
136 protected $mWatched = null;
138 /** @var int The page length, 0 for special pages */
139 protected $mLength = -1;
141 /** @var null Is the article at this title a redirect? */
142 public $mRedirect = null;
144 /** @var array Associative array of user ID -> timestamp/false */
145 private $mNotificationTimestamp = array();
147 /** @var bool Whether a page has any subpages */
148 private $mHasSubpages;
150 /** @var bool The (string) language code of the page's language and content code. */
151 private $mPageLanguage = false;
153 /** @var TitleValue A corresponding TitleValue object */
154 private $mTitleValue = null;
155 // @}
158 * B/C kludge: provide a TitleParser for use by Title.
159 * Ideally, Title would have no methods that need this.
160 * Avoid usage of this singleton by using TitleValue
161 * and the associated services when possible.
163 * @return TitleParser
165 private static function getTitleParser() {
166 global $wgContLang, $wgLocalInterwikis;
168 static $titleCodec = null;
169 static $titleCodecFingerprint = null;
171 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
172 // make sure we are using the right one. To detect changes over the course
173 // of a request, we remember a fingerprint of the config used to create the
174 // codec singleton, and re-create it if the fingerprint doesn't match.
175 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
177 if ( $fingerprint !== $titleCodecFingerprint ) {
178 $titleCodec = null;
181 if ( !$titleCodec ) {
182 $titleCodec = new MediaWikiTitleCodec(
183 $wgContLang,
184 GenderCache::singleton(),
185 $wgLocalInterwikis
187 $titleCodecFingerprint = $fingerprint;
190 return $titleCodec;
194 * B/C kludge: provide a TitleParser for use by Title.
195 * Ideally, Title would have no methods that need this.
196 * Avoid usage of this singleton by using TitleValue
197 * and the associated services when possible.
199 * @return TitleFormatter
201 private static function getTitleFormatter() {
202 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
203 // which implements TitleFormatter.
204 return self::getTitleParser();
207 function __construct() {
211 * Create a new Title from a prefixed DB key
213 * @param string $key The database key, which has underscores
214 * instead of spaces, possibly including namespace and
215 * interwiki prefixes
216 * @return Title|null Title, or null on an error
218 public static function newFromDBkey( $key ) {
219 $t = new Title();
220 $t->mDbkeyform = $key;
221 if ( $t->secureAndSplit() ) {
222 return $t;
223 } else {
224 return null;
229 * Create a new Title from a TitleValue
231 * @param TitleValue $titleValue Assumed to be safe.
233 * @return Title
235 public static function newFromTitleValue( TitleValue $titleValue ) {
236 return self::makeTitle(
237 $titleValue->getNamespace(),
238 $titleValue->getText(),
239 $titleValue->getFragment() );
243 * Create a new Title from text, such as what one would find in a link. De-
244 * codes any HTML entities in the text.
246 * @param string $text The link text; spaces, prefixes, and an
247 * initial ':' indicating the main namespace are accepted.
248 * @param int $defaultNamespace The namespace to use if none is specified
249 * by a prefix. If you want to force a specific namespace even if
250 * $text might begin with a namespace prefix, use makeTitle() or
251 * makeTitleSafe().
252 * @throws MWException
253 * @return Title|null Title or null on an error.
255 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
256 if ( is_object( $text ) ) {
257 throw new MWException( 'Title::newFromText given an object' );
260 $cache = self::getTitleCache();
263 * Wiki pages often contain multiple links to the same page.
264 * Title normalization and parsing can become expensive on
265 * pages with many links, so we can save a little time by
266 * caching them.
268 * In theory these are value objects and won't get changed...
270 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
271 return $cache->get( $text );
274 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
275 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
277 $t = new Title();
278 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
279 $t->mDefaultNamespace = intval( $defaultNamespace );
281 if ( $t->secureAndSplit() ) {
282 if ( $defaultNamespace == NS_MAIN ) {
283 $cache->set( $text, $t );
285 return $t;
286 } else {
287 return null;
292 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
294 * Example of wrong and broken code:
295 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
297 * Example of right code:
298 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
300 * Create a new Title from URL-encoded text. Ensures that
301 * the given title's length does not exceed the maximum.
303 * @param string $url The title, as might be taken from a URL
304 * @return Title|null The new object, or null on an error
306 public static function newFromURL( $url ) {
307 $t = new Title();
309 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
310 # but some URLs used it as a space replacement and they still come
311 # from some external search tools.
312 if ( strpos( self::legalChars(), '+' ) === false ) {
313 $url = str_replace( '+', ' ', $url );
316 $t->mDbkeyform = str_replace( ' ', '_', $url );
317 if ( $t->secureAndSplit() ) {
318 return $t;
319 } else {
320 return null;
325 * @return MapCacheLRU
327 private static function getTitleCache() {
328 if ( self::$titleCache == null ) {
329 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
331 return self::$titleCache;
335 * Returns a list of fields that are to be selected for initializing Title
336 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
337 * whether to include page_content_model.
339 * @return array
341 protected static function getSelectFields() {
342 global $wgContentHandlerUseDB;
344 $fields = array(
345 'page_namespace', 'page_title', 'page_id',
346 'page_len', 'page_is_redirect', 'page_latest',
349 if ( $wgContentHandlerUseDB ) {
350 $fields[] = 'page_content_model';
353 return $fields;
357 * Create a new Title from an article ID
359 * @param int $id The page_id corresponding to the Title to create
360 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
361 * @return Title|null The new object, or null on an error
363 public static function newFromID( $id, $flags = 0 ) {
364 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
365 $row = $db->selectRow(
366 'page',
367 self::getSelectFields(),
368 array( 'page_id' => $id ),
369 __METHOD__
371 if ( $row !== false ) {
372 $title = Title::newFromRow( $row );
373 } else {
374 $title = null;
376 return $title;
380 * Make an array of titles from an array of IDs
382 * @param int[] $ids Array of IDs
383 * @return Title[] Array of Titles
385 public static function newFromIDs( $ids ) {
386 if ( !count( $ids ) ) {
387 return array();
389 $dbr = wfGetDB( DB_SLAVE );
391 $res = $dbr->select(
392 'page',
393 self::getSelectFields(),
394 array( 'page_id' => $ids ),
395 __METHOD__
398 $titles = array();
399 foreach ( $res as $row ) {
400 $titles[] = Title::newFromRow( $row );
402 return $titles;
406 * Make a Title object from a DB row
408 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
409 * @return Title Corresponding Title
411 public static function newFromRow( $row ) {
412 $t = self::makeTitle( $row->page_namespace, $row->page_title );
413 $t->loadFromRow( $row );
414 return $t;
418 * Load Title object fields from a DB row.
419 * If false is given, the title will be treated as non-existing.
421 * @param stdClass|bool $row Database row
423 public function loadFromRow( $row ) {
424 if ( $row ) { // page found
425 if ( isset( $row->page_id ) ) {
426 $this->mArticleID = (int)$row->page_id;
428 if ( isset( $row->page_len ) ) {
429 $this->mLength = (int)$row->page_len;
431 if ( isset( $row->page_is_redirect ) ) {
432 $this->mRedirect = (bool)$row->page_is_redirect;
434 if ( isset( $row->page_latest ) ) {
435 $this->mLatestID = (int)$row->page_latest;
437 if ( isset( $row->page_content_model ) ) {
438 $this->mContentModel = strval( $row->page_content_model );
439 } else {
440 $this->mContentModel = false; # initialized lazily in getContentModel()
442 } else { // page not found
443 $this->mArticleID = 0;
444 $this->mLength = 0;
445 $this->mRedirect = false;
446 $this->mLatestID = 0;
447 $this->mContentModel = false; # initialized lazily in getContentModel()
452 * Create a new Title from a namespace index and a DB key.
453 * It's assumed that $ns and $title are *valid*, for instance when
454 * they came directly from the database or a special page name.
455 * For convenience, spaces are converted to underscores so that
456 * eg user_text fields can be used directly.
458 * @param int $ns The namespace of the article
459 * @param string $title The unprefixed database key form
460 * @param string $fragment The link fragment (after the "#")
461 * @param string $interwiki The interwiki prefix
462 * @return Title The new object
464 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
465 $t = new Title();
466 $t->mInterwiki = $interwiki;
467 $t->mFragment = $fragment;
468 $t->mNamespace = $ns = intval( $ns );
469 $t->mDbkeyform = str_replace( ' ', '_', $title );
470 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
471 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
472 $t->mTextform = str_replace( '_', ' ', $title );
473 $t->mContentModel = false; # initialized lazily in getContentModel()
474 return $t;
478 * Create a new Title from a namespace index and a DB key.
479 * The parameters will be checked for validity, which is a bit slower
480 * than makeTitle() but safer for user-provided data.
482 * @param int $ns The namespace of the article
483 * @param string $title Database key form
484 * @param string $fragment The link fragment (after the "#")
485 * @param string $interwiki Interwiki prefix
486 * @return Title The new object, or null on an error
488 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
489 if ( !MWNamespace::exists( $ns ) ) {
490 return null;
493 $t = new Title();
494 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
495 if ( $t->secureAndSplit() ) {
496 return $t;
497 } else {
498 return null;
503 * Create a new Title for the Main Page
505 * @return Title The new object
507 public static function newMainPage() {
508 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
509 // Don't give fatal errors if the message is broken
510 if ( !$title ) {
511 $title = Title::newFromText( 'Main Page' );
513 return $title;
517 * Extract a redirect destination from a string and return the
518 * Title, or null if the text doesn't contain a valid redirect
519 * This will only return the very next target, useful for
520 * the redirect table and other checks that don't need full recursion
522 * @param string $text Text with possible redirect
523 * @return Title The corresponding Title
524 * @deprecated since 1.21, use Content::getRedirectTarget instead.
526 public static function newFromRedirect( $text ) {
527 ContentHandler::deprecated( __METHOD__, '1.21' );
529 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
530 return $content->getRedirectTarget();
534 * Extract a redirect destination from a string and return the
535 * Title, or null if the text doesn't contain a valid redirect
536 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
537 * in order to provide (hopefully) the Title of the final destination instead of another redirect
539 * @param string $text Text with possible redirect
540 * @return Title
541 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
543 public static function newFromRedirectRecurse( $text ) {
544 ContentHandler::deprecated( __METHOD__, '1.21' );
546 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
547 return $content->getUltimateRedirectTarget();
551 * Extract a redirect destination from a string and return an
552 * array of Titles, or null if the text doesn't contain a valid redirect
553 * The last element in the array is the final destination after all redirects
554 * have been resolved (up to $wgMaxRedirects times)
556 * @param string $text Text with possible redirect
557 * @return Title[] Array of Titles, with the destination last
558 * @deprecated since 1.21, use Content::getRedirectChain instead.
560 public static function newFromRedirectArray( $text ) {
561 ContentHandler::deprecated( __METHOD__, '1.21' );
563 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
564 return $content->getRedirectChain();
568 * Get the prefixed DB key associated with an ID
570 * @param int $id The page_id of the article
571 * @return Title|null An object representing the article, or null if no such article was found
573 public static function nameOf( $id ) {
574 $dbr = wfGetDB( DB_SLAVE );
576 $s = $dbr->selectRow(
577 'page',
578 array( 'page_namespace', 'page_title' ),
579 array( 'page_id' => $id ),
580 __METHOD__
582 if ( $s === false ) {
583 return null;
586 $n = self::makeName( $s->page_namespace, $s->page_title );
587 return $n;
591 * Get a regex character class describing the legal characters in a link
593 * @return string The list of characters, not delimited
595 public static function legalChars() {
596 global $wgLegalTitleChars;
597 return $wgLegalTitleChars;
601 * Returns a simple regex that will match on characters and sequences invalid in titles.
602 * Note that this doesn't pick up many things that could be wrong with titles, but that
603 * replacing this regex with something valid will make many titles valid.
605 * @todo: move this into MediaWikiTitleCodec
607 * @return string Regex string
609 static function getTitleInvalidRegex() {
610 static $rxTc = false;
611 if ( !$rxTc ) {
612 # Matching titles will be held as illegal.
613 $rxTc = '/' .
614 # Any character not allowed is forbidden...
615 '[^' . self::legalChars() . ']' .
616 # URL percent encoding sequences interfere with the ability
617 # to round-trip titles -- you can't link to them consistently.
618 '|%[0-9A-Fa-f]{2}' .
619 # XML/HTML character references produce similar issues.
620 '|&[A-Za-z0-9\x80-\xff]+;' .
621 '|&#[0-9]+;' .
622 '|&#x[0-9A-Fa-f]+;' .
623 '/S';
626 return $rxTc;
630 * Utility method for converting a character sequence from bytes to Unicode.
632 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
633 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
635 * @param string $byteClass
636 * @return string
638 public static function convertByteClassToUnicodeClass( $byteClass ) {
639 $length = strlen( $byteClass );
640 // Input token queue
641 $x0 = $x1 = $x2 = '';
642 // Decoded queue
643 $d0 = $d1 = $d2 = '';
644 // Decoded integer codepoints
645 $ord0 = $ord1 = $ord2 = 0;
646 // Re-encoded queue
647 $r0 = $r1 = $r2 = '';
648 // Output
649 $out = '';
650 // Flags
651 $allowUnicode = false;
652 for ( $pos = 0; $pos < $length; $pos++ ) {
653 // Shift the queues down
654 $x2 = $x1;
655 $x1 = $x0;
656 $d2 = $d1;
657 $d1 = $d0;
658 $ord2 = $ord1;
659 $ord1 = $ord0;
660 $r2 = $r1;
661 $r1 = $r0;
662 // Load the current input token and decoded values
663 $inChar = $byteClass[$pos];
664 if ( $inChar == '\\' ) {
665 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
666 $x0 = $inChar . $m[0];
667 $d0 = chr( hexdec( $m[1] ) );
668 $pos += strlen( $m[0] );
669 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
670 $x0 = $inChar . $m[0];
671 $d0 = chr( octdec( $m[0] ) );
672 $pos += strlen( $m[0] );
673 } elseif ( $pos + 1 >= $length ) {
674 $x0 = $d0 = '\\';
675 } else {
676 $d0 = $byteClass[$pos + 1];
677 $x0 = $inChar . $d0;
678 $pos += 1;
680 } else {
681 $x0 = $d0 = $inChar;
683 $ord0 = ord( $d0 );
684 // Load the current re-encoded value
685 if ( $ord0 < 32 || $ord0 == 0x7f ) {
686 $r0 = sprintf( '\x%02x', $ord0 );
687 } elseif ( $ord0 >= 0x80 ) {
688 // Allow unicode if a single high-bit character appears
689 $r0 = sprintf( '\x%02x', $ord0 );
690 $allowUnicode = true;
691 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
692 $r0 = '\\' . $d0;
693 } else {
694 $r0 = $d0;
696 // Do the output
697 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
698 // Range
699 if ( $ord2 > $ord0 ) {
700 // Empty range
701 } elseif ( $ord0 >= 0x80 ) {
702 // Unicode range
703 $allowUnicode = true;
704 if ( $ord2 < 0x80 ) {
705 // Keep the non-unicode section of the range
706 $out .= "$r2-\\x7F";
708 } else {
709 // Normal range
710 $out .= "$r2-$r0";
712 // Reset state to the initial value
713 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
714 } elseif ( $ord2 < 0x80 ) {
715 // ASCII character
716 $out .= $r2;
719 if ( $ord1 < 0x80 ) {
720 $out .= $r1;
722 if ( $ord0 < 0x80 ) {
723 $out .= $r0;
725 if ( $allowUnicode ) {
726 $out .= '\u0080-\uFFFF';
728 return $out;
732 * Make a prefixed DB key from a DB key and a namespace index
734 * @param int $ns Numerical representation of the namespace
735 * @param string $title The DB key form the title
736 * @param string $fragment The link fragment (after the "#")
737 * @param string $interwiki The interwiki prefix
738 * @return string The prefixed form of the title
740 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
741 global $wgContLang;
743 $namespace = $wgContLang->getNsText( $ns );
744 $name = $namespace == '' ? $title : "$namespace:$title";
745 if ( strval( $interwiki ) != '' ) {
746 $name = "$interwiki:$name";
748 if ( strval( $fragment ) != '' ) {
749 $name .= '#' . $fragment;
751 return $name;
755 * Escape a text fragment, say from a link, for a URL
757 * @param string $fragment Containing a URL or link fragment (after the "#")
758 * @return string Escaped string
760 static function escapeFragmentForURL( $fragment ) {
761 # Note that we don't urlencode the fragment. urlencoded Unicode
762 # fragments appear not to work in IE (at least up to 7) or in at least
763 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
764 # to care if they aren't encoded.
765 return Sanitizer::escapeId( $fragment, 'noninitial' );
769 * Callback for usort() to do title sorts by (namespace, title)
771 * @param Title $a
772 * @param Title $b
774 * @return int Result of string comparison, or namespace comparison
776 public static function compare( $a, $b ) {
777 if ( $a->getNamespace() == $b->getNamespace() ) {
778 return strcmp( $a->getText(), $b->getText() );
779 } else {
780 return $a->getNamespace() - $b->getNamespace();
785 * Determine whether the object refers to a page within
786 * this project.
788 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
790 public function isLocal() {
791 if ( $this->isExternal() ) {
792 $iw = Interwiki::fetch( $this->mInterwiki );
793 if ( $iw ) {
794 return $iw->isLocal();
797 return true;
801 * Is this Title interwiki?
803 * @return bool
805 public function isExternal() {
806 return $this->mInterwiki !== '';
810 * Get the interwiki prefix
812 * Use Title::isExternal to check if a interwiki is set
814 * @return string Interwiki prefix
816 public function getInterwiki() {
817 return $this->mInterwiki;
821 * Determine whether the object refers to a page within
822 * this project and is transcludable.
824 * @return bool True if this is transcludable
826 public function isTrans() {
827 if ( !$this->isExternal() ) {
828 return false;
831 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
835 * Returns the DB name of the distant wiki which owns the object.
837 * @return string The DB name
839 public function getTransWikiID() {
840 if ( !$this->isExternal() ) {
841 return false;
844 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
848 * Get a TitleValue object representing this Title.
850 * @note: Not all valid Titles have a corresponding valid TitleValue
851 * (e.g. TitleValues cannot represent page-local links that have a
852 * fragment but no title text).
854 * @return TitleValue|null
856 public function getTitleValue() {
857 if ( $this->mTitleValue === null ) {
858 try {
859 $this->mTitleValue = new TitleValue(
860 $this->getNamespace(),
861 $this->getDBkey(),
862 $this->getFragment() );
863 } catch ( InvalidArgumentException $ex ) {
864 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
865 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
869 return $this->mTitleValue;
873 * Get the text form (spaces not underscores) of the main part
875 * @return string Main part of the title
877 public function getText() {
878 return $this->mTextform;
882 * Get the URL-encoded form of the main part
884 * @return string Main part of the title, URL-encoded
886 public function getPartialURL() {
887 return $this->mUrlform;
891 * Get the main part with underscores
893 * @return string Main part of the title, with underscores
895 public function getDBkey() {
896 return $this->mDbkeyform;
900 * Get the DB key with the initial letter case as specified by the user
902 * @return string DB key
904 function getUserCaseDBKey() {
905 if ( !is_null( $this->mUserCaseDBKey ) ) {
906 return $this->mUserCaseDBKey;
907 } else {
908 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
909 return $this->mDbkeyform;
914 * Get the namespace index, i.e. one of the NS_xxxx constants.
916 * @return int Namespace index
918 public function getNamespace() {
919 return $this->mNamespace;
923 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
925 * @throws MWException
926 * @return string Content model id
928 public function getContentModel() {
929 if ( !$this->mContentModel ) {
930 $linkCache = LinkCache::singleton();
931 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
934 if ( !$this->mContentModel ) {
935 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
938 if ( !$this->mContentModel ) {
939 throw new MWException( 'Failed to determine content model!' );
942 return $this->mContentModel;
946 * Convenience method for checking a title's content model name
948 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
949 * @return bool True if $this->getContentModel() == $id
951 public function hasContentModel( $id ) {
952 return $this->getContentModel() == $id;
956 * Get the namespace text
958 * @return string Namespace text
960 public function getNsText() {
961 if ( $this->isExternal() ) {
962 // This probably shouldn't even happen. ohh man, oh yuck.
963 // But for interwiki transclusion it sometimes does.
964 // Shit. Shit shit shit.
966 // Use the canonical namespaces if possible to try to
967 // resolve a foreign namespace.
968 if ( MWNamespace::exists( $this->mNamespace ) ) {
969 return MWNamespace::getCanonicalName( $this->mNamespace );
973 try {
974 $formatter = $this->getTitleFormatter();
975 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
976 } catch ( InvalidArgumentException $ex ) {
977 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
978 return false;
983 * Get the namespace text of the subject (rather than talk) page
985 * @return string Namespace text
987 public function getSubjectNsText() {
988 global $wgContLang;
989 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
993 * Get the namespace text of the talk page
995 * @return string Namespace text
997 public function getTalkNsText() {
998 global $wgContLang;
999 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1003 * Could this title have a corresponding talk page?
1005 * @return bool
1007 public function canTalk() {
1008 return MWNamespace::canTalk( $this->mNamespace );
1012 * Is this in a namespace that allows actual pages?
1014 * @return bool
1015 * @internal note -- uses hardcoded namespace index instead of constants
1017 public function canExist() {
1018 return $this->mNamespace >= NS_MAIN;
1022 * Can this title be added to a user's watchlist?
1024 * @return bool
1026 public function isWatchable() {
1027 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1031 * Returns true if this is a special page.
1033 * @return bool
1035 public function isSpecialPage() {
1036 return $this->getNamespace() == NS_SPECIAL;
1040 * Returns true if this title resolves to the named special page
1042 * @param string $name The special page name
1043 * @return bool
1045 public function isSpecial( $name ) {
1046 if ( $this->isSpecialPage() ) {
1047 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1048 if ( $name == $thisName ) {
1049 return true;
1052 return false;
1056 * If the Title refers to a special page alias which is not the local default, resolve
1057 * the alias, and localise the name as necessary. Otherwise, return $this
1059 * @return Title
1061 public function fixSpecialName() {
1062 if ( $this->isSpecialPage() ) {
1063 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1064 if ( $canonicalName ) {
1065 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1066 if ( $localName != $this->mDbkeyform ) {
1067 return Title::makeTitle( NS_SPECIAL, $localName );
1071 return $this;
1075 * Returns true if the title is inside the specified namespace.
1077 * Please make use of this instead of comparing to getNamespace()
1078 * This function is much more resistant to changes we may make
1079 * to namespaces than code that makes direct comparisons.
1080 * @param int $ns The namespace
1081 * @return bool
1082 * @since 1.19
1084 public function inNamespace( $ns ) {
1085 return MWNamespace::equals( $this->getNamespace(), $ns );
1089 * Returns true if the title is inside one of the specified namespaces.
1091 * @param ...$namespaces The namespaces to check for
1092 * @return bool
1093 * @since 1.19
1095 public function inNamespaces( /* ... */ ) {
1096 $namespaces = func_get_args();
1097 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1098 $namespaces = $namespaces[0];
1101 foreach ( $namespaces as $ns ) {
1102 if ( $this->inNamespace( $ns ) ) {
1103 return true;
1107 return false;
1111 * Returns true if the title has the same subject namespace as the
1112 * namespace specified.
1113 * For example this method will take NS_USER and return true if namespace
1114 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1115 * as their subject namespace.
1117 * This is MUCH simpler than individually testing for equivalence
1118 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1119 * @since 1.19
1120 * @param int $ns
1121 * @return bool
1123 public function hasSubjectNamespace( $ns ) {
1124 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1128 * Is this Title in a namespace which contains content?
1129 * In other words, is this a content page, for the purposes of calculating
1130 * statistics, etc?
1132 * @return bool
1134 public function isContentPage() {
1135 return MWNamespace::isContent( $this->getNamespace() );
1139 * Would anybody with sufficient privileges be able to move this page?
1140 * Some pages just aren't movable.
1142 * @return bool
1144 public function isMovable() {
1145 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1146 // Interwiki title or immovable namespace. Hooks don't get to override here
1147 return false;
1150 $result = true;
1151 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1152 return $result;
1156 * Is this the mainpage?
1157 * @note Title::newFromText seems to be sufficiently optimized by the title
1158 * cache that we don't need to over-optimize by doing direct comparisons and
1159 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1160 * ends up reporting something differently than $title->isMainPage();
1162 * @since 1.18
1163 * @return bool
1165 public function isMainPage() {
1166 return $this->equals( Title::newMainPage() );
1170 * Is this a subpage?
1172 * @return bool
1174 public function isSubpage() {
1175 return MWNamespace::hasSubpages( $this->mNamespace )
1176 ? strpos( $this->getText(), '/' ) !== false
1177 : false;
1181 * Is this a conversion table for the LanguageConverter?
1183 * @return bool
1185 public function isConversionTable() {
1186 // @todo ConversionTable should become a separate content model.
1188 return $this->getNamespace() == NS_MEDIAWIKI &&
1189 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1193 * Does that page contain wikitext, or it is JS, CSS or whatever?
1195 * @return bool
1197 public function isWikitextPage() {
1198 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1202 * Could this page contain custom CSS or JavaScript for the global UI.
1203 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1204 * or CONTENT_MODEL_JAVASCRIPT.
1206 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1207 * for that!
1209 * Note that this method should not return true for pages that contain and
1210 * show "inactive" CSS or JS.
1212 * @return bool
1214 public function isCssOrJsPage() {
1215 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1216 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1217 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1219 # @note This hook is also called in ContentHandler::getDefaultModel.
1220 # It's called here again to make sure hook functions can force this
1221 # method to return true even outside the mediawiki namespace.
1223 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1225 return $isCssOrJsPage;
1229 * Is this a .css or .js subpage of a user page?
1230 * @return bool
1232 public function isCssJsSubpage() {
1233 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1234 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1235 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1239 * Trim down a .css or .js subpage title to get the corresponding skin name
1241 * @return string Containing skin name from .css or .js subpage title
1243 public function getSkinFromCssJsSubpage() {
1244 $subpage = explode( '/', $this->mTextform );
1245 $subpage = $subpage[count( $subpage ) - 1];
1246 $lastdot = strrpos( $subpage, '.' );
1247 if ( $lastdot === false ) {
1248 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1250 return substr( $subpage, 0, $lastdot );
1254 * Is this a .css subpage of a user page?
1256 * @return bool
1258 public function isCssSubpage() {
1259 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1260 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1264 * Is this a .js subpage of a user page?
1266 * @return bool
1268 public function isJsSubpage() {
1269 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1270 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1274 * Is this a talk page of some sort?
1276 * @return bool
1278 public function isTalkPage() {
1279 return MWNamespace::isTalk( $this->getNamespace() );
1283 * Get a Title object associated with the talk page of this article
1285 * @return Title The object for the talk page
1287 public function getTalkPage() {
1288 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1292 * Get a title object associated with the subject page of this
1293 * talk page
1295 * @return Title The object for the subject page
1297 public function getSubjectPage() {
1298 // Is this the same title?
1299 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1300 if ( $this->getNamespace() == $subjectNS ) {
1301 return $this;
1303 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1307 * Get the default namespace index, for when there is no namespace
1309 * @return int Default namespace index
1311 public function getDefaultNamespace() {
1312 return $this->mDefaultNamespace;
1316 * Get the Title fragment (i.e.\ the bit after the #) in text form
1318 * Use Title::hasFragment to check for a fragment
1320 * @return string Title fragment
1322 public function getFragment() {
1323 return $this->mFragment;
1327 * Check if a Title fragment is set
1329 * @return bool
1330 * @since 1.23
1332 public function hasFragment() {
1333 return $this->mFragment !== '';
1337 * Get the fragment in URL form, including the "#" character if there is one
1338 * @return string Fragment in URL form
1340 public function getFragmentForURL() {
1341 if ( !$this->hasFragment() ) {
1342 return '';
1343 } else {
1344 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1349 * Set the fragment for this title. Removes the first character from the
1350 * specified fragment before setting, so it assumes you're passing it with
1351 * an initial "#".
1353 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1354 * Still in active use privately.
1356 * @param string $fragment Text
1358 public function setFragment( $fragment ) {
1359 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1363 * Prefix some arbitrary text with the namespace or interwiki prefix
1364 * of this object
1366 * @param string $name The text
1367 * @return string The prefixed text
1368 * @private
1370 private function prefix( $name ) {
1371 $p = '';
1372 if ( $this->isExternal() ) {
1373 $p = $this->mInterwiki . ':';
1376 if ( 0 != $this->mNamespace ) {
1377 $p .= $this->getNsText() . ':';
1379 return $p . $name;
1383 * Get the prefixed database key form
1385 * @return string The prefixed title, with underscores and
1386 * any interwiki and namespace prefixes
1388 public function getPrefixedDBkey() {
1389 $s = $this->prefix( $this->mDbkeyform );
1390 $s = str_replace( ' ', '_', $s );
1391 return $s;
1395 * Get the prefixed title with spaces.
1396 * This is the form usually used for display
1398 * @return string The prefixed title, with spaces
1400 public function getPrefixedText() {
1401 if ( $this->mPrefixedText === null ) {
1402 $s = $this->prefix( $this->mTextform );
1403 $s = str_replace( '_', ' ', $s );
1404 $this->mPrefixedText = $s;
1406 return $this->mPrefixedText;
1410 * Return a string representation of this title
1412 * @return string Representation of this title
1414 public function __toString() {
1415 return $this->getPrefixedText();
1419 * Get the prefixed title with spaces, plus any fragment
1420 * (part beginning with '#')
1422 * @return string The prefixed title, with spaces and the fragment, including '#'
1424 public function getFullText() {
1425 $text = $this->getPrefixedText();
1426 if ( $this->hasFragment() ) {
1427 $text .= '#' . $this->getFragment();
1429 return $text;
1433 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1435 * @par Example:
1436 * @code
1437 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1438 * # returns: 'Foo'
1439 * @endcode
1441 * @return string Root name
1442 * @since 1.20
1444 public function getRootText() {
1445 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1446 return $this->getText();
1449 return strtok( $this->getText(), '/' );
1453 * Get the root page name title, i.e. the leftmost part before any slashes
1455 * @par Example:
1456 * @code
1457 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1458 * # returns: Title{User:Foo}
1459 * @endcode
1461 * @return Title Root title
1462 * @since 1.20
1464 public function getRootTitle() {
1465 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1469 * Get the base page name without a namespace, i.e. the part before the subpage name
1471 * @par Example:
1472 * @code
1473 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1474 * # returns: 'Foo/Bar'
1475 * @endcode
1477 * @return string Base name
1479 public function getBaseText() {
1480 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1481 return $this->getText();
1484 $parts = explode( '/', $this->getText() );
1485 # Don't discard the real title if there's no subpage involved
1486 if ( count( $parts ) > 1 ) {
1487 unset( $parts[count( $parts ) - 1] );
1489 return implode( '/', $parts );
1493 * Get the base page name title, i.e. the part before the subpage name
1495 * @par Example:
1496 * @code
1497 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1498 * # returns: Title{User:Foo/Bar}
1499 * @endcode
1501 * @return Title Base title
1502 * @since 1.20
1504 public function getBaseTitle() {
1505 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1509 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1511 * @par Example:
1512 * @code
1513 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1514 * # returns: "Baz"
1515 * @endcode
1517 * @return string Subpage name
1519 public function getSubpageText() {
1520 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1521 return $this->mTextform;
1523 $parts = explode( '/', $this->mTextform );
1524 return $parts[count( $parts ) - 1];
1528 * Get the title for a subpage of the current page
1530 * @par Example:
1531 * @code
1532 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1533 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1534 * @endcode
1536 * @param string $text The subpage name to add to the title
1537 * @return Title Subpage title
1538 * @since 1.20
1540 public function getSubpage( $text ) {
1541 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1545 * Get the HTML-escaped displayable text form.
1546 * Used for the title field in <a> tags.
1548 * @return string The text, including any prefixes
1549 * @deprecated since 1.19
1551 public function getEscapedText() {
1552 wfDeprecated( __METHOD__, '1.19' );
1553 return htmlspecialchars( $this->getPrefixedText() );
1557 * Get a URL-encoded form of the subpage text
1559 * @return string URL-encoded subpage name
1561 public function getSubpageUrlForm() {
1562 $text = $this->getSubpageText();
1563 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1564 return $text;
1568 * Get a URL-encoded title (not an actual URL) including interwiki
1570 * @return string The URL-encoded form
1572 public function getPrefixedURL() {
1573 $s = $this->prefix( $this->mDbkeyform );
1574 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1575 return $s;
1579 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1580 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1581 * second argument named variant. This was deprecated in favor
1582 * of passing an array of option with a "variant" key
1583 * Once $query2 is removed for good, this helper can be dropped
1584 * and the wfArrayToCgi moved to getLocalURL();
1586 * @since 1.19 (r105919)
1587 * @param array|string $query
1588 * @param bool $query2
1589 * @return string
1591 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1592 if ( $query2 !== false ) {
1593 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1594 "method called with a second parameter is deprecated. Add your " .
1595 "parameter to an array passed as the first parameter.", "1.19" );
1597 if ( is_array( $query ) ) {
1598 $query = wfArrayToCgi( $query );
1600 if ( $query2 ) {
1601 if ( is_string( $query2 ) ) {
1602 // $query2 is a string, we will consider this to be
1603 // a deprecated $variant argument and add it to the query
1604 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1605 } else {
1606 $query2 = wfArrayToCgi( $query2 );
1608 // If we have $query content add a & to it first
1609 if ( $query ) {
1610 $query .= '&';
1612 // Now append the queries together
1613 $query .= $query2;
1615 return $query;
1619 * Get a real URL referring to this title, with interwiki link and
1620 * fragment
1622 * @see self::getLocalURL for the arguments.
1623 * @see wfExpandUrl
1624 * @param array|string $query
1625 * @param bool $query2
1626 * @param string $proto Protocol type to use in URL
1627 * @return string The URL
1629 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1630 $query = self::fixUrlQueryArgs( $query, $query2 );
1632 # Hand off all the decisions on urls to getLocalURL
1633 $url = $this->getLocalURL( $query );
1635 # Expand the url to make it a full url. Note that getLocalURL has the
1636 # potential to output full urls for a variety of reasons, so we use
1637 # wfExpandUrl instead of simply prepending $wgServer
1638 $url = wfExpandUrl( $url, $proto );
1640 # Finally, add the fragment.
1641 $url .= $this->getFragmentForURL();
1643 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1644 return $url;
1648 * Get a URL with no fragment or server name (relative URL) from a Title object.
1649 * If this page is generated with action=render, however,
1650 * $wgServer is prepended to make an absolute URL.
1652 * @see self::getFullURL to always get an absolute URL.
1653 * @see self::newFromText to produce a Title object.
1655 * @param string|array $query an optional query string,
1656 * not used for interwiki links. Can be specified as an associative array as well,
1657 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1658 * Some query patterns will trigger various shorturl path replacements.
1659 * @param array $query2 An optional secondary query array. This one MUST
1660 * be an array. If a string is passed it will be interpreted as a deprecated
1661 * variant argument and urlencoded into a variant= argument.
1662 * This second query argument will be added to the $query
1663 * The second parameter is deprecated since 1.19. Pass it as a key,value
1664 * pair in the first parameter array instead.
1666 * @return string String of the URL.
1668 public function getLocalURL( $query = '', $query2 = false ) {
1669 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1671 $query = self::fixUrlQueryArgs( $query, $query2 );
1673 $interwiki = Interwiki::fetch( $this->mInterwiki );
1674 if ( $interwiki ) {
1675 $namespace = $this->getNsText();
1676 if ( $namespace != '' ) {
1677 # Can this actually happen? Interwikis shouldn't be parsed.
1678 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1679 $namespace .= ':';
1681 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1682 $url = wfAppendQuery( $url, $query );
1683 } else {
1684 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1685 if ( $query == '' ) {
1686 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1687 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1688 } else {
1689 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1690 $url = false;
1691 $matches = array();
1693 if ( !empty( $wgActionPaths )
1694 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1696 $action = urldecode( $matches[2] );
1697 if ( isset( $wgActionPaths[$action] ) ) {
1698 $query = $matches[1];
1699 if ( isset( $matches[4] ) ) {
1700 $query .= $matches[4];
1702 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1703 if ( $query != '' ) {
1704 $url = wfAppendQuery( $url, $query );
1709 if ( $url === false
1710 && $wgVariantArticlePath
1711 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1712 && $this->getPageLanguage()->hasVariants()
1713 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1715 $variant = urldecode( $matches[1] );
1716 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1717 // Only do the variant replacement if the given variant is a valid
1718 // variant for the page's language.
1719 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1720 $url = str_replace( '$1', $dbkey, $url );
1724 if ( $url === false ) {
1725 if ( $query == '-' ) {
1726 $query = '';
1728 $url = "{$wgScript}?title={$dbkey}&{$query}";
1732 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1734 // @todo FIXME: This causes breakage in various places when we
1735 // actually expected a local URL and end up with dupe prefixes.
1736 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1737 $url = $wgServer . $url;
1740 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1741 return $url;
1745 * Get a URL that's the simplest URL that will be valid to link, locally,
1746 * to the current Title. It includes the fragment, but does not include
1747 * the server unless action=render is used (or the link is external). If
1748 * there's a fragment but the prefixed text is empty, we just return a link
1749 * to the fragment.
1751 * The result obviously should not be URL-escaped, but does need to be
1752 * HTML-escaped if it's being output in HTML.
1754 * @param array $query
1755 * @param bool $query2
1756 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1757 * @see self::getLocalURL for the arguments.
1758 * @return string The URL
1760 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1761 wfProfileIn( __METHOD__ );
1762 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1763 $ret = $this->getFullURL( $query, $query2, $proto );
1764 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1765 $ret = $this->getFragmentForURL();
1766 } else {
1767 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1769 wfProfileOut( __METHOD__ );
1770 return $ret;
1774 * Get an HTML-escaped version of the URL form, suitable for
1775 * using in a link, without a server name or fragment
1777 * @see self::getLocalURL for the arguments.
1778 * @param string $query
1779 * @param bool|string $query2
1780 * @return string The URL
1781 * @deprecated since 1.19
1783 public function escapeLocalURL( $query = '', $query2 = false ) {
1784 wfDeprecated( __METHOD__, '1.19' );
1785 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1789 * Get an HTML-escaped version of the URL form, suitable for
1790 * using in a link, including the server name and fragment
1792 * @see self::getLocalURL for the arguments.
1793 * @return string The URL
1794 * @deprecated since 1.19
1796 public function escapeFullURL( $query = '', $query2 = false ) {
1797 wfDeprecated( __METHOD__, '1.19' );
1798 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1802 * Get the URL form for an internal link.
1803 * - Used in various Squid-related code, in case we have a different
1804 * internal hostname for the server from the exposed one.
1806 * This uses $wgInternalServer to qualify the path, or $wgServer
1807 * if $wgInternalServer is not set. If the server variable used is
1808 * protocol-relative, the URL will be expanded to http://
1810 * @see self::getLocalURL for the arguments.
1811 * @return string The URL
1813 public function getInternalURL( $query = '', $query2 = false ) {
1814 global $wgInternalServer, $wgServer;
1815 $query = self::fixUrlQueryArgs( $query, $query2 );
1816 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1817 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1818 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1819 return $url;
1823 * Get the URL for a canonical link, for use in things like IRC and
1824 * e-mail notifications. Uses $wgCanonicalServer and the
1825 * GetCanonicalURL hook.
1827 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1829 * @see self::getLocalURL for the arguments.
1830 * @return string The URL
1831 * @since 1.18
1833 public function getCanonicalURL( $query = '', $query2 = false ) {
1834 $query = self::fixUrlQueryArgs( $query, $query2 );
1835 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1836 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1837 return $url;
1841 * HTML-escaped version of getCanonicalURL()
1843 * @see self::getLocalURL for the arguments.
1844 * @since 1.18
1845 * @return string
1846 * @deprecated since 1.19
1848 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1849 wfDeprecated( __METHOD__, '1.19' );
1850 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1854 * Get the edit URL for this Title
1856 * @return string The URL, or a null string if this is an interwiki link
1858 public function getEditURL() {
1859 if ( $this->isExternal() ) {
1860 return '';
1862 $s = $this->getLocalURL( 'action=edit' );
1864 return $s;
1868 * Is $wgUser watching this page?
1870 * @deprecated since 1.20; use User::isWatched() instead.
1871 * @return bool
1873 public function userIsWatching() {
1874 global $wgUser;
1876 if ( is_null( $this->mWatched ) ) {
1877 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1878 $this->mWatched = false;
1879 } else {
1880 $this->mWatched = $wgUser->isWatched( $this );
1883 return $this->mWatched;
1887 * Can $wgUser read this page?
1889 * @deprecated since 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1890 * @return bool
1892 public function userCanRead() {
1893 wfDeprecated( __METHOD__, '1.19' );
1894 return $this->userCan( 'read' );
1898 * Can $user perform $action on this page?
1899 * This skips potentially expensive cascading permission checks
1900 * as well as avoids expensive error formatting
1902 * Suitable for use for nonessential UI controls in common cases, but
1903 * _not_ for functional access control.
1905 * May provide false positives, but should never provide a false negative.
1907 * @param string $action Action that permission needs to be checked for
1908 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1909 * @return bool
1911 public function quickUserCan( $action, $user = null ) {
1912 return $this->userCan( $action, $user, false );
1916 * Can $user perform $action on this page?
1918 * @param string $action Action that permission needs to be checked for
1919 * @param User $user User to check (since 1.19); $wgUser will be used if not
1920 * provided.
1921 * @param bool $doExpensiveQueries Set this to false to avoid doing
1922 * unnecessary queries.
1923 * @return bool
1925 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1926 if ( !$user instanceof User ) {
1927 global $wgUser;
1928 $user = $wgUser;
1931 return !count( $this->getUserPermissionsErrorsInternal(
1932 $action, $user, $doExpensiveQueries, true ) );
1936 * Can $user perform $action on this page?
1938 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1940 * @param string $action action that permission needs to be checked for
1941 * @param User $user User to check
1942 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1943 * queries by skipping checks for cascading protections and user blocks.
1944 * @param array $ignoreErrors of Strings Set this to a list of message keys
1945 * whose corresponding errors may be ignored.
1946 * @return array Array of arguments to wfMessage to explain permissions problems.
1948 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1949 $ignoreErrors = array()
1951 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1953 // Remove the errors being ignored.
1954 foreach ( $errors as $index => $error ) {
1955 $error_key = is_array( $error ) ? $error[0] : $error;
1957 if ( in_array( $error_key, $ignoreErrors ) ) {
1958 unset( $errors[$index] );
1962 return $errors;
1966 * Permissions checks that fail most often, and which are easiest to test.
1968 * @param string $action the action to check
1969 * @param User $user User to check
1970 * @param array $errors List of current errors
1971 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1972 * @param bool $short Short circuit on first error
1974 * @return array List of errors
1976 private function checkQuickPermissions( $action, $user, $errors,
1977 $doExpensiveQueries, $short
1979 if ( !wfRunHooks( 'TitleQuickPermissions',
1980 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1982 return $errors;
1985 if ( $action == 'create' ) {
1986 if (
1987 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1988 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1990 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1992 } elseif ( $action == 'move' ) {
1993 if ( !$user->isAllowed( 'move-rootuserpages' )
1994 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1995 // Show user page-specific message only if the user can move other pages
1996 $errors[] = array( 'cant-move-user-page' );
1999 // Check if user is allowed to move files if it's a file
2000 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
2001 $errors[] = array( 'movenotallowedfile' );
2004 // Check if user is allowed to move category pages if it's a category page
2005 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
2006 $errors[] = array( 'cant-move-category-page' );
2009 if ( !$user->isAllowed( 'move' ) ) {
2010 // User can't move anything
2011 $userCanMove = User::groupHasPermission( 'user', 'move' );
2012 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
2013 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
2014 // custom message if logged-in users without any special rights can move
2015 $errors[] = array( 'movenologintext' );
2016 } else {
2017 $errors[] = array( 'movenotallowed' );
2020 } elseif ( $action == 'move-target' ) {
2021 if ( !$user->isAllowed( 'move' ) ) {
2022 // User can't move anything
2023 $errors[] = array( 'movenotallowed' );
2024 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2025 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2026 // Show user page-specific message only if the user can move other pages
2027 $errors[] = array( 'cant-move-to-user-page' );
2028 } elseif ( !$user->isAllowed( 'move-categorypages' )
2029 && $this->mNamespace == NS_CATEGORY ) {
2030 // Show category page-specific message only if the user can move other pages
2031 $errors[] = array( 'cant-move-to-category-page' );
2033 } elseif ( !$user->isAllowed( $action ) ) {
2034 $errors[] = $this->missingPermissionError( $action, $short );
2037 return $errors;
2041 * Add the resulting error code to the errors array
2043 * @param array $errors List of current errors
2044 * @param array $result Result of errors
2046 * @return array List of errors
2048 private function resultToError( $errors, $result ) {
2049 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2050 // A single array representing an error
2051 $errors[] = $result;
2052 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2053 // A nested array representing multiple errors
2054 $errors = array_merge( $errors, $result );
2055 } elseif ( $result !== '' && is_string( $result ) ) {
2056 // A string representing a message-id
2057 $errors[] = array( $result );
2058 } elseif ( $result === false ) {
2059 // a generic "We don't want them to do that"
2060 $errors[] = array( 'badaccess-group0' );
2062 return $errors;
2066 * Check various permission hooks
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 bool $doExpensiveQueries Whether or not to perform expensive queries
2072 * @param bool $short Short circuit on first error
2074 * @return array List of errors
2076 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2077 // Use getUserPermissionsErrors instead
2078 $result = '';
2079 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2080 return $result ? array() : array( array( 'badaccess-group0' ) );
2082 // Check getUserPermissionsErrors hook
2083 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2084 $errors = $this->resultToError( $errors, $result );
2086 // Check getUserPermissionsErrorsExpensive hook
2087 if (
2088 $doExpensiveQueries
2089 && !( $short && count( $errors ) > 0 )
2090 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2092 $errors = $this->resultToError( $errors, $result );
2095 return $errors;
2099 * Check permissions on special pages & namespaces
2101 * @param string $action The action to check
2102 * @param User $user User to check
2103 * @param array $errors List of current errors
2104 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2105 * @param bool $short Short circuit on first error
2107 * @return array List of errors
2109 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2110 $doExpensiveQueries, $short
2112 # Only 'createaccount' can be performed on special pages,
2113 # which don't actually exist in the DB.
2114 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2115 $errors[] = array( 'ns-specialprotected' );
2118 # Check $wgNamespaceProtection for restricted namespaces
2119 if ( $this->isNamespaceProtected( $user ) ) {
2120 $ns = $this->mNamespace == NS_MAIN ?
2121 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2122 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2123 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
2126 return $errors;
2130 * Check CSS/JS sub-page permissions
2132 * @param string $action The action to check
2133 * @param User $user User to check
2134 * @param array $errors List of current errors
2135 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2136 * @param bool $short Short circuit on first error
2138 * @return array List of errors
2140 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2141 # Protect css/js subpages of user pages
2142 # XXX: this might be better using restrictions
2143 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2144 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2145 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2146 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2147 $errors[] = array( 'mycustomcssprotected' );
2148 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2149 $errors[] = array( 'mycustomjsprotected' );
2151 } else {
2152 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2153 $errors[] = array( 'customcssprotected' );
2154 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2155 $errors[] = array( 'customjsprotected' );
2160 return $errors;
2164 * Check against page_restrictions table requirements on this
2165 * page. The user must possess all required rights for this
2166 * action.
2168 * @param string $action The action to check
2169 * @param User $user User to check
2170 * @param array $errors List of current errors
2171 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2172 * @param bool $short Short circuit on first error
2174 * @return array List of errors
2176 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2177 foreach ( $this->getRestrictions( $action ) as $right ) {
2178 // Backwards compatibility, rewrite sysop -> editprotected
2179 if ( $right == 'sysop' ) {
2180 $right = 'editprotected';
2182 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2183 if ( $right == 'autoconfirmed' ) {
2184 $right = 'editsemiprotected';
2186 if ( $right == '' ) {
2187 continue;
2189 if ( !$user->isAllowed( $right ) ) {
2190 $errors[] = array( 'protectedpagetext', $right );
2191 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2192 $errors[] = array( 'protectedpagetext', 'protect' );
2196 return $errors;
2200 * Check restrictions on cascading pages.
2202 * @param string $action The action to check
2203 * @param User $user User to check
2204 * @param array $errors List of current errors
2205 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2206 * @param bool $short Short circuit on first error
2208 * @return array List of errors
2210 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2211 $doExpensiveQueries, $short
2213 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2214 # We /could/ use the protection level on the source page, but it's
2215 # fairly ugly as we have to establish a precedence hierarchy for pages
2216 # included by multiple cascade-protected pages. So just restrict
2217 # it to people with 'protect' permission, as they could remove the
2218 # protection anyway.
2219 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2220 # Cascading protection depends on more than this page...
2221 # Several cascading protected pages may include this page...
2222 # Check each cascading level
2223 # This is only for protection restrictions, not for all actions
2224 if ( isset( $restrictions[$action] ) ) {
2225 foreach ( $restrictions[$action] as $right ) {
2226 // Backwards compatibility, rewrite sysop -> editprotected
2227 if ( $right == 'sysop' ) {
2228 $right = 'editprotected';
2230 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2231 if ( $right == 'autoconfirmed' ) {
2232 $right = 'editsemiprotected';
2234 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2235 $pages = '';
2236 foreach ( $cascadingSources as $page ) {
2237 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2239 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
2245 return $errors;
2249 * Check action permissions not already checked in checkQuickPermissions
2251 * @param string $action The action to check
2252 * @param User $user User to check
2253 * @param array $errors List of current errors
2254 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2255 * @param bool $short Short circuit on first error
2257 * @return array List of errors
2259 private function checkActionPermissions( $action, $user, $errors,
2260 $doExpensiveQueries, $short
2262 global $wgDeleteRevisionsLimit, $wgLang;
2264 if ( $action == 'protect' ) {
2265 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2266 $user, $doExpensiveQueries, true ) )
2268 // If they can't edit, they shouldn't protect.
2269 $errors[] = array( 'protect-cantedit' );
2271 } elseif ( $action == 'create' ) {
2272 $title_protection = $this->getTitleProtection();
2273 if ( $title_protection ) {
2274 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
2275 $title_protection['pt_create_perm'] = 'editprotected'; // B/C
2277 if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) {
2278 $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C
2280 if ( $title_protection['pt_create_perm'] == ''
2281 || !$user->isAllowed( $title_protection['pt_create_perm'] )
2283 $errors[] = array(
2284 'titleprotected',
2285 User::whoIs( $title_protection['pt_user'] ),
2286 $title_protection['pt_reason']
2290 } elseif ( $action == 'move' ) {
2291 // Check for immobile pages
2292 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2293 // Specific message for this case
2294 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2295 } elseif ( !$this->isMovable() ) {
2296 // Less specific message for rarer cases
2297 $errors[] = array( 'immobile-source-page' );
2299 } elseif ( $action == 'move-target' ) {
2300 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2301 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2302 } elseif ( !$this->isMovable() ) {
2303 $errors[] = array( 'immobile-target-page' );
2305 } elseif ( $action == 'delete' ) {
2306 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2307 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2309 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2312 return $errors;
2316 * Check that the user isn't blocked from editing.
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 bool $doExpensiveQueries Whether or not to perform expensive queries
2322 * @param bool $short Short circuit on first error
2324 * @return array List of errors
2326 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2327 // Account creation blocks handled at userlogin.
2328 // Unblocking handled in SpecialUnblock
2329 if ( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2330 return $errors;
2333 global $wgEmailConfirmToEdit;
2335 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2336 $errors[] = array( 'confirmedittext' );
2339 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2340 // Don't block the user from editing their own talk page unless they've been
2341 // explicitly blocked from that too.
2342 } elseif ( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2343 // @todo FIXME: Pass the relevant context into this function.
2344 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2347 return $errors;
2351 * Check that the user is allowed to read this page.
2353 * @param string $action The action to check
2354 * @param User $user User to check
2355 * @param array $errors List of current errors
2356 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2357 * @param bool $short Short circuit on first error
2359 * @return array List of errors
2361 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2362 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2364 $whitelisted = false;
2365 if ( User::isEveryoneAllowed( 'read' ) ) {
2366 # Shortcut for public wikis, allows skipping quite a bit of code
2367 $whitelisted = true;
2368 } elseif ( $user->isAllowed( 'read' ) ) {
2369 # If the user is allowed to read pages, he is allowed to read all pages
2370 $whitelisted = true;
2371 } elseif ( $this->isSpecial( 'Userlogin' )
2372 || $this->isSpecial( 'ChangePassword' )
2373 || $this->isSpecial( 'PasswordReset' )
2375 # Always grant access to the login page.
2376 # Even anons need to be able to log in.
2377 $whitelisted = true;
2378 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2379 # Time to check the whitelist
2380 # Only do these checks is there's something to check against
2381 $name = $this->getPrefixedText();
2382 $dbName = $this->getPrefixedDBkey();
2384 // Check for explicit whitelisting with and without underscores
2385 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2386 $whitelisted = true;
2387 } elseif ( $this->getNamespace() == NS_MAIN ) {
2388 # Old settings might have the title prefixed with
2389 # a colon for main-namespace pages
2390 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2391 $whitelisted = true;
2393 } elseif ( $this->isSpecialPage() ) {
2394 # If it's a special page, ditch the subpage bit and check again
2395 $name = $this->getDBkey();
2396 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2397 if ( $name ) {
2398 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2399 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2400 $whitelisted = true;
2406 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2407 $name = $this->getPrefixedText();
2408 // Check for regex whitelisting
2409 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2410 if ( preg_match( $listItem, $name ) ) {
2411 $whitelisted = true;
2412 break;
2417 if ( !$whitelisted ) {
2418 # If the title is not whitelisted, give extensions a chance to do so...
2419 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2420 if ( !$whitelisted ) {
2421 $errors[] = $this->missingPermissionError( $action, $short );
2425 return $errors;
2429 * Get a description array when the user doesn't have the right to perform
2430 * $action (i.e. when User::isAllowed() returns false)
2432 * @param string $action The action to check
2433 * @param bool $short Short circuit on first error
2434 * @return array List of errors
2436 private function missingPermissionError( $action, $short ) {
2437 // We avoid expensive display logic for quickUserCan's and such
2438 if ( $short ) {
2439 return array( 'badaccess-group0' );
2442 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2443 User::getGroupsWithPermission( $action ) );
2445 if ( count( $groups ) ) {
2446 global $wgLang;
2447 return array(
2448 'badaccess-groups',
2449 $wgLang->commaList( $groups ),
2450 count( $groups )
2452 } else {
2453 return array( 'badaccess-group0' );
2458 * Can $user perform $action on this page? This is an internal function,
2459 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2460 * checks on wfReadOnly() and blocks)
2462 * @param string $action Action that permission needs to be checked for
2463 * @param User $user User to check
2464 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2465 * @param bool $short Set this to true to stop after the first permission error.
2466 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2468 protected function getUserPermissionsErrorsInternal( $action, $user,
2469 $doExpensiveQueries = true, $short = false
2471 wfProfileIn( __METHOD__ );
2473 # Read has special handling
2474 if ( $action == 'read' ) {
2475 $checks = array(
2476 'checkPermissionHooks',
2477 'checkReadPermissions',
2479 } else {
2480 $checks = array(
2481 'checkQuickPermissions',
2482 'checkPermissionHooks',
2483 'checkSpecialsAndNSPermissions',
2484 'checkCSSandJSPermissions',
2485 'checkPageRestrictions',
2486 'checkCascadingSourcesRestrictions',
2487 'checkActionPermissions',
2488 'checkUserBlock'
2492 $errors = array();
2493 while ( count( $checks ) > 0 &&
2494 !( $short && count( $errors ) > 0 ) ) {
2495 $method = array_shift( $checks );
2496 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2499 wfProfileOut( __METHOD__ );
2500 return $errors;
2504 * Get a filtered list of all restriction types supported by this wiki.
2505 * @param bool $exists True to get all restriction types that apply to
2506 * titles that do exist, False for all restriction types that apply to
2507 * titles that do not exist
2508 * @return array
2510 public static function getFilteredRestrictionTypes( $exists = true ) {
2511 global $wgRestrictionTypes;
2512 $types = $wgRestrictionTypes;
2513 if ( $exists ) {
2514 # Remove the create restriction for existing titles
2515 $types = array_diff( $types, array( 'create' ) );
2516 } else {
2517 # Only the create and upload restrictions apply to non-existing titles
2518 $types = array_intersect( $types, array( 'create', 'upload' ) );
2520 return $types;
2524 * Returns restriction types for the current Title
2526 * @return array Applicable restriction types
2528 public function getRestrictionTypes() {
2529 if ( $this->isSpecialPage() ) {
2530 return array();
2533 $types = self::getFilteredRestrictionTypes( $this->exists() );
2535 if ( $this->getNamespace() != NS_FILE ) {
2536 # Remove the upload restriction for non-file titles
2537 $types = array_diff( $types, array( 'upload' ) );
2540 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2542 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2543 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2545 return $types;
2549 * Is this title subject to title protection?
2550 * Title protection is the one applied against creation of such title.
2552 * @return array|bool An associative array representing any existent title
2553 * protection, or false if there's none.
2555 private function getTitleProtection() {
2556 // Can't protect pages in special namespaces
2557 if ( $this->getNamespace() < 0 ) {
2558 return false;
2561 // Can't protect pages that exist.
2562 if ( $this->exists() ) {
2563 return false;
2566 if ( !isset( $this->mTitleProtection ) ) {
2567 $dbr = wfGetDB( DB_SLAVE );
2568 $res = $dbr->select(
2569 'protected_titles',
2570 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2571 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2572 __METHOD__
2575 // fetchRow returns false if there are no rows.
2576 $this->mTitleProtection = $dbr->fetchRow( $res );
2578 return $this->mTitleProtection;
2582 * Update the title protection status
2584 * @deprecated since 1.19; use WikiPage::doUpdateRestrictions() instead.
2585 * @param string $create_perm Permission required for creation
2586 * @param string $reason Reason for protection
2587 * @param string $expiry Expiry timestamp
2588 * @return bool
2590 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2591 wfDeprecated( __METHOD__, '1.19' );
2593 global $wgUser;
2595 $limit = array( 'create' => $create_perm );
2596 $expiry = array( 'create' => $expiry );
2598 $page = WikiPage::factory( $this );
2599 $cascade = false;
2600 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2602 return $status->isOK();
2606 * Remove any title protection due to page existing
2608 public function deleteTitleProtection() {
2609 $dbw = wfGetDB( DB_MASTER );
2611 $dbw->delete(
2612 'protected_titles',
2613 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2614 __METHOD__
2616 $this->mTitleProtection = false;
2620 * Is this page "semi-protected" - the *only* protection levels are listed
2621 * in $wgSemiprotectedRestrictionLevels?
2623 * @param string $action Action to check (default: edit)
2624 * @return bool
2626 public function isSemiProtected( $action = 'edit' ) {
2627 global $wgSemiprotectedRestrictionLevels;
2629 $restrictions = $this->getRestrictions( $action );
2630 $semi = $wgSemiprotectedRestrictionLevels;
2631 if ( !$restrictions || !$semi ) {
2632 // Not protected, or all protection is full protection
2633 return false;
2636 // Remap autoconfirmed to editsemiprotected for BC
2637 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2638 $semi[$key] = 'editsemiprotected';
2640 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2641 $restrictions[$key] = 'editsemiprotected';
2644 return !array_diff( $restrictions, $semi );
2648 * Does the title correspond to a protected article?
2650 * @param string $action the action the page is protected from,
2651 * by default checks all actions.
2652 * @return bool
2654 public function isProtected( $action = '' ) {
2655 global $wgRestrictionLevels;
2657 $restrictionTypes = $this->getRestrictionTypes();
2659 # Special pages have inherent protection
2660 if ( $this->isSpecialPage() ) {
2661 return true;
2664 # Check regular protection levels
2665 foreach ( $restrictionTypes as $type ) {
2666 if ( $action == $type || $action == '' ) {
2667 $r = $this->getRestrictions( $type );
2668 foreach ( $wgRestrictionLevels as $level ) {
2669 if ( in_array( $level, $r ) && $level != '' ) {
2670 return true;
2676 return false;
2680 * Determines if $user is unable to edit this page because it has been protected
2681 * by $wgNamespaceProtection.
2683 * @param User $user User object to check permissions
2684 * @return bool
2686 public function isNamespaceProtected( User $user ) {
2687 global $wgNamespaceProtection;
2689 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2690 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2691 if ( $right != '' && !$user->isAllowed( $right ) ) {
2692 return true;
2696 return false;
2700 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2702 * @return bool If the page is subject to cascading restrictions.
2704 public function isCascadeProtected() {
2705 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2706 return ( $sources > 0 );
2710 * Determines whether cascading protection sources have already been loaded from
2711 * the database.
2713 * @param bool $getPages True to check if the pages are loaded, or false to check
2714 * if the status is loaded.
2715 * @return bool Whether or not the specified information has been loaded
2716 * @since 1.23
2718 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2719 return $getPages ? isset( $this->mCascadeSources ) : isset( $this->mHasCascadingRestrictions );
2723 * Cascading protection: Get the source of any cascading restrictions on this page.
2725 * @param bool $getPages Whether or not to retrieve the actual pages
2726 * that the restrictions have come from and the actual restrictions
2727 * themselves.
2728 * @return array Two elements: First is an array of Title objects of the
2729 * pages from which cascading restrictions have come, false for
2730 * none, or true if such restrictions exist but $getPages was not
2731 * set. Second is an array like that returned by
2732 * Title::getAllRestrictions(), or an empty array if $getPages is
2733 * false.
2735 public function getCascadeProtectionSources( $getPages = true ) {
2736 global $wgContLang;
2737 $pagerestrictions = array();
2739 if ( isset( $this->mCascadeSources ) && $getPages ) {
2740 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2741 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2742 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2745 wfProfileIn( __METHOD__ );
2747 $dbr = wfGetDB( DB_SLAVE );
2749 if ( $this->getNamespace() == NS_FILE ) {
2750 $tables = array( 'imagelinks', 'page_restrictions' );
2751 $where_clauses = array(
2752 'il_to' => $this->getDBkey(),
2753 'il_from=pr_page',
2754 'pr_cascade' => 1
2756 } else {
2757 $tables = array( 'templatelinks', 'page_restrictions' );
2758 $where_clauses = array(
2759 'tl_namespace' => $this->getNamespace(),
2760 'tl_title' => $this->getDBkey(),
2761 'tl_from=pr_page',
2762 'pr_cascade' => 1
2766 if ( $getPages ) {
2767 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2768 'pr_expiry', 'pr_type', 'pr_level' );
2769 $where_clauses[] = 'page_id=pr_page';
2770 $tables[] = 'page';
2771 } else {
2772 $cols = array( 'pr_expiry' );
2775 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2777 $sources = $getPages ? array() : false;
2778 $now = wfTimestampNow();
2779 $purgeExpired = false;
2781 foreach ( $res as $row ) {
2782 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2783 if ( $expiry > $now ) {
2784 if ( $getPages ) {
2785 $page_id = $row->pr_page;
2786 $page_ns = $row->page_namespace;
2787 $page_title = $row->page_title;
2788 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2789 # Add groups needed for each restriction type if its not already there
2790 # Make sure this restriction type still exists
2792 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2793 $pagerestrictions[$row->pr_type] = array();
2796 if (
2797 isset( $pagerestrictions[$row->pr_type] )
2798 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2800 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2802 } else {
2803 $sources = true;
2805 } else {
2806 // Trigger lazy purge of expired restrictions from the db
2807 $purgeExpired = true;
2810 if ( $purgeExpired ) {
2811 Title::purgeExpiredRestrictions();
2814 if ( $getPages ) {
2815 $this->mCascadeSources = $sources;
2816 $this->mCascadingRestrictions = $pagerestrictions;
2817 } else {
2818 $this->mHasCascadingRestrictions = $sources;
2821 wfProfileOut( __METHOD__ );
2822 return array( $sources, $pagerestrictions );
2826 * Accessor for mRestrictionsLoaded
2828 * @return bool Whether or not the page's restrictions have already been
2829 * loaded from the database
2830 * @since 1.23
2832 public function areRestrictionsLoaded() {
2833 return $this->mRestrictionsLoaded;
2837 * Accessor/initialisation for mRestrictions
2839 * @param string $action Action that permission needs to be checked for
2840 * @return array Restriction levels needed to take the action. All levels
2841 * are required.
2843 public function getRestrictions( $action ) {
2844 if ( !$this->mRestrictionsLoaded ) {
2845 $this->loadRestrictions();
2847 return isset( $this->mRestrictions[$action] )
2848 ? $this->mRestrictions[$action]
2849 : array();
2853 * Accessor/initialisation for mRestrictions
2855 * @return array Keys are actions, values are arrays as returned by
2856 * Title::getRestrictions()
2857 * @since 1.23
2859 public function getAllRestrictions() {
2860 if ( !$this->mRestrictionsLoaded ) {
2861 $this->loadRestrictions();
2863 return $this->mRestrictions;
2867 * Get the expiry time for the restriction against a given action
2869 * @param string $action
2870 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2871 * or not protected at all, or false if the action is not recognised.
2873 public function getRestrictionExpiry( $action ) {
2874 if ( !$this->mRestrictionsLoaded ) {
2875 $this->loadRestrictions();
2877 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2881 * Returns cascading restrictions for the current article
2883 * @return bool
2885 function areRestrictionsCascading() {
2886 if ( !$this->mRestrictionsLoaded ) {
2887 $this->loadRestrictions();
2890 return $this->mCascadeRestriction;
2894 * Loads a string into mRestrictions array
2896 * @param ResultWrapper $res Resource restrictions as an SQL result.
2897 * @param string $oldFashionedRestrictions Comma-separated list of page
2898 * restrictions from page table (pre 1.10)
2900 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2901 $rows = array();
2903 foreach ( $res as $row ) {
2904 $rows[] = $row;
2907 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2911 * Compiles list of active page restrictions from both page table (pre 1.10)
2912 * and page_restrictions table for this existing page.
2913 * Public for usage by LiquidThreads.
2915 * @param array $rows Array of db result objects
2916 * @param string $oldFashionedRestrictions Comma-separated list of page
2917 * restrictions from page table (pre 1.10)
2919 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2920 global $wgContLang;
2921 $dbr = wfGetDB( DB_SLAVE );
2923 $restrictionTypes = $this->getRestrictionTypes();
2925 foreach ( $restrictionTypes as $type ) {
2926 $this->mRestrictions[$type] = array();
2927 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2930 $this->mCascadeRestriction = false;
2932 # Backwards-compatibility: also load the restrictions from the page record (old format).
2934 if ( $oldFashionedRestrictions === null ) {
2935 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2936 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2939 if ( $oldFashionedRestrictions != '' ) {
2941 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2942 $temp = explode( '=', trim( $restrict ) );
2943 if ( count( $temp ) == 1 ) {
2944 // old old format should be treated as edit/move restriction
2945 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2946 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2947 } else {
2948 $restriction = trim( $temp[1] );
2949 if ( $restriction != '' ) { //some old entries are empty
2950 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2955 $this->mOldRestrictions = true;
2959 if ( count( $rows ) ) {
2960 # Current system - load second to make them override.
2961 $now = wfTimestampNow();
2962 $purgeExpired = false;
2964 # Cycle through all the restrictions.
2965 foreach ( $rows as $row ) {
2967 // Don't take care of restrictions types that aren't allowed
2968 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2969 continue;
2972 // This code should be refactored, now that it's being used more generally,
2973 // But I don't really see any harm in leaving it in Block for now -werdna
2974 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2976 // Only apply the restrictions if they haven't expired!
2977 if ( !$expiry || $expiry > $now ) {
2978 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2979 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2981 $this->mCascadeRestriction |= $row->pr_cascade;
2982 } else {
2983 // Trigger a lazy purge of expired restrictions
2984 $purgeExpired = true;
2988 if ( $purgeExpired ) {
2989 Title::purgeExpiredRestrictions();
2993 $this->mRestrictionsLoaded = true;
2997 * Load restrictions from the page_restrictions table
2999 * @param string $oldFashionedRestrictions Comma-separated list of page
3000 * restrictions from page table (pre 1.10)
3002 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3003 global $wgContLang;
3004 if ( !$this->mRestrictionsLoaded ) {
3005 if ( $this->exists() ) {
3006 $dbr = wfGetDB( DB_SLAVE );
3008 $res = $dbr->select(
3009 'page_restrictions',
3010 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
3011 array( 'pr_page' => $this->getArticleID() ),
3012 __METHOD__
3015 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
3016 } else {
3017 $title_protection = $this->getTitleProtection();
3019 if ( $title_protection ) {
3020 $now = wfTimestampNow();
3021 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
3023 if ( !$expiry || $expiry > $now ) {
3024 // Apply the restrictions
3025 $this->mRestrictionsExpiry['create'] = $expiry;
3026 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
3027 } else { // Get rid of the old restrictions
3028 Title::purgeExpiredRestrictions();
3029 $this->mTitleProtection = false;
3031 } else {
3032 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
3034 $this->mRestrictionsLoaded = true;
3040 * Flush the protection cache in this object and force reload from the database.
3041 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3043 public function flushRestrictions() {
3044 $this->mRestrictionsLoaded = false;
3045 $this->mTitleProtection = null;
3049 * Purge expired restrictions from the page_restrictions table
3051 static function purgeExpiredRestrictions() {
3052 if ( wfReadOnly() ) {
3053 return;
3056 $method = __METHOD__;
3057 $dbw = wfGetDB( DB_MASTER );
3058 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
3059 $dbw->delete(
3060 'page_restrictions',
3061 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3062 $method
3064 $dbw->delete(
3065 'protected_titles',
3066 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3067 $method
3069 } );
3073 * Does this have subpages? (Warning, usually requires an extra DB query.)
3075 * @return bool
3077 public function hasSubpages() {
3078 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3079 # Duh
3080 return false;
3083 # We dynamically add a member variable for the purpose of this method
3084 # alone to cache the result. There's no point in having it hanging
3085 # around uninitialized in every Title object; therefore we only add it
3086 # if needed and don't declare it statically.
3087 if ( !isset( $this->mHasSubpages ) ) {
3088 $this->mHasSubpages = false;
3089 $subpages = $this->getSubpages( 1 );
3090 if ( $subpages instanceof TitleArray ) {
3091 $this->mHasSubpages = (bool)$subpages->count();
3095 return $this->mHasSubpages;
3099 * Get all subpages of this page.
3101 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3102 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3103 * doesn't allow subpages
3105 public function getSubpages( $limit = -1 ) {
3106 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3107 return array();
3110 $dbr = wfGetDB( DB_SLAVE );
3111 $conds['page_namespace'] = $this->getNamespace();
3112 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3113 $options = array();
3114 if ( $limit > -1 ) {
3115 $options['LIMIT'] = $limit;
3117 $this->mSubpages = TitleArray::newFromResult(
3118 $dbr->select( 'page',
3119 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3120 $conds,
3121 __METHOD__,
3122 $options
3125 return $this->mSubpages;
3129 * Is there a version of this page in the deletion archive?
3131 * @return int The number of archived revisions
3133 public function isDeleted() {
3134 if ( $this->getNamespace() < 0 ) {
3135 $n = 0;
3136 } else {
3137 $dbr = wfGetDB( DB_SLAVE );
3139 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3140 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3141 __METHOD__
3143 if ( $this->getNamespace() == NS_FILE ) {
3144 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3145 array( 'fa_name' => $this->getDBkey() ),
3146 __METHOD__
3150 return (int)$n;
3154 * Is there a version of this page in the deletion archive?
3156 * @return bool
3158 public function isDeletedQuick() {
3159 if ( $this->getNamespace() < 0 ) {
3160 return false;
3162 $dbr = wfGetDB( DB_SLAVE );
3163 $deleted = (bool)$dbr->selectField( 'archive', '1',
3164 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3165 __METHOD__
3167 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3168 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3169 array( 'fa_name' => $this->getDBkey() ),
3170 __METHOD__
3173 return $deleted;
3177 * Get the article ID for this Title from the link cache,
3178 * adding it if necessary
3180 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3181 * for update
3182 * @return int The ID
3184 public function getArticleID( $flags = 0 ) {
3185 if ( $this->getNamespace() < 0 ) {
3186 $this->mArticleID = 0;
3187 return $this->mArticleID;
3189 $linkCache = LinkCache::singleton();
3190 if ( $flags & self::GAID_FOR_UPDATE ) {
3191 $oldUpdate = $linkCache->forUpdate( true );
3192 $linkCache->clearLink( $this );
3193 $this->mArticleID = $linkCache->addLinkObj( $this );
3194 $linkCache->forUpdate( $oldUpdate );
3195 } else {
3196 if ( -1 == $this->mArticleID ) {
3197 $this->mArticleID = $linkCache->addLinkObj( $this );
3200 return $this->mArticleID;
3204 * Is this an article that is a redirect page?
3205 * Uses link cache, adding it if necessary
3207 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3208 * @return bool
3210 public function isRedirect( $flags = 0 ) {
3211 if ( !is_null( $this->mRedirect ) ) {
3212 return $this->mRedirect;
3214 # Calling getArticleID() loads the field from cache as needed
3215 if ( !$this->getArticleID( $flags ) ) {
3216 $this->mRedirect = false;
3217 return $this->mRedirect;
3220 $linkCache = LinkCache::singleton();
3221 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3222 if ( $cached === null ) {
3223 # Trust LinkCache's state over our own
3224 # LinkCache is telling us that the page doesn't exist, despite there being cached
3225 # data relating to an existing page in $this->mArticleID. Updaters should clear
3226 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3227 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3228 # LinkCache to refresh its data from the master.
3229 $this->mRedirect = false;
3230 return $this->mRedirect;
3233 $this->mRedirect = (bool)$cached;
3235 return $this->mRedirect;
3239 * What is the length of this page?
3240 * Uses link cache, adding it if necessary
3242 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3243 * @return int
3245 public function getLength( $flags = 0 ) {
3246 if ( $this->mLength != -1 ) {
3247 return $this->mLength;
3249 # Calling getArticleID() loads the field from cache as needed
3250 if ( !$this->getArticleID( $flags ) ) {
3251 $this->mLength = 0;
3252 return $this->mLength;
3254 $linkCache = LinkCache::singleton();
3255 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3256 if ( $cached === null ) {
3257 # Trust LinkCache's state over our own, as for isRedirect()
3258 $this->mLength = 0;
3259 return $this->mLength;
3262 $this->mLength = intval( $cached );
3264 return $this->mLength;
3268 * What is the page_latest field for this page?
3270 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3271 * @return int Int or 0 if the page doesn't exist
3273 public function getLatestRevID( $flags = 0 ) {
3274 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3275 return intval( $this->mLatestID );
3277 # Calling getArticleID() loads the field from cache as needed
3278 if ( !$this->getArticleID( $flags ) ) {
3279 $this->mLatestID = 0;
3280 return $this->mLatestID;
3282 $linkCache = LinkCache::singleton();
3283 $linkCache->addLinkObj( $this );
3284 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3285 if ( $cached === null ) {
3286 # Trust LinkCache's state over our own, as for isRedirect()
3287 $this->mLatestID = 0;
3288 return $this->mLatestID;
3291 $this->mLatestID = intval( $cached );
3293 return $this->mLatestID;
3297 * This clears some fields in this object, and clears any associated
3298 * keys in the "bad links" section of the link cache.
3300 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3301 * loading of the new page_id. It's also called from
3302 * WikiPage::doDeleteArticleReal()
3304 * @param int $newid The new Article ID
3306 public function resetArticleID( $newid ) {
3307 $linkCache = LinkCache::singleton();
3308 $linkCache->clearLink( $this );
3310 if ( $newid === false ) {
3311 $this->mArticleID = -1;
3312 } else {
3313 $this->mArticleID = intval( $newid );
3315 $this->mRestrictionsLoaded = false;
3316 $this->mRestrictions = array();
3317 $this->mRedirect = null;
3318 $this->mLength = -1;
3319 $this->mLatestID = false;
3320 $this->mContentModel = false;
3321 $this->mEstimateRevisions = null;
3322 $this->mPageLanguage = false;
3326 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3328 * @param string $text Containing title to capitalize
3329 * @param int $ns Namespace index, defaults to NS_MAIN
3330 * @return string Containing capitalized title
3332 public static function capitalize( $text, $ns = NS_MAIN ) {
3333 global $wgContLang;
3335 if ( MWNamespace::isCapitalized( $ns ) ) {
3336 return $wgContLang->ucfirst( $text );
3337 } else {
3338 return $text;
3343 * Secure and split - main initialisation function for this object
3345 * Assumes that mDbkeyform has been set, and is urldecoded
3346 * and uses underscores, but not otherwise munged. This function
3347 * removes illegal characters, splits off the interwiki and
3348 * namespace prefixes, sets the other forms, and canonicalizes
3349 * everything.
3351 * @return bool True on success
3353 private function secureAndSplit() {
3354 # Initialisation
3355 $this->mInterwiki = '';
3356 $this->mFragment = '';
3357 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3359 $dbkey = $this->mDbkeyform;
3361 try {
3362 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3363 // the parsing code with Title, while avoiding massive refactoring.
3364 // @todo: get rid of secureAndSplit, refactor parsing code.
3365 $parser = $this->getTitleParser();
3366 $parts = $parser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3367 } catch ( MalformedTitleException $ex ) {
3368 return false;
3371 # Fill fields
3372 $this->setFragment( '#' . $parts['fragment'] );
3373 $this->mInterwiki = $parts['interwiki'];
3374 $this->mNamespace = $parts['namespace'];
3375 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3377 $this->mDbkeyform = $parts['dbkey'];
3378 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3379 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3381 # We already know that some pages won't be in the database!
3382 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3383 $this->mArticleID = 0;
3386 return true;
3390 * Get an array of Title objects linking to this Title
3391 * Also stores the IDs in the link cache.
3393 * WARNING: do not use this function on arbitrary user-supplied titles!
3394 * On heavily-used templates it will max out the memory.
3396 * @param array $options May be FOR UPDATE
3397 * @param string $table Table name
3398 * @param string $prefix Fields prefix
3399 * @return Title[] Array of Title objects linking here
3401 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3402 if ( count( $options ) > 0 ) {
3403 $db = wfGetDB( DB_MASTER );
3404 } else {
3405 $db = wfGetDB( DB_SLAVE );
3408 $res = $db->select(
3409 array( 'page', $table ),
3410 self::getSelectFields(),
3411 array(
3412 "{$prefix}_from=page_id",
3413 "{$prefix}_namespace" => $this->getNamespace(),
3414 "{$prefix}_title" => $this->getDBkey() ),
3415 __METHOD__,
3416 $options
3419 $retVal = array();
3420 if ( $res->numRows() ) {
3421 $linkCache = LinkCache::singleton();
3422 foreach ( $res as $row ) {
3423 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3424 if ( $titleObj ) {
3425 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3426 $retVal[] = $titleObj;
3430 return $retVal;
3434 * Get an array of Title objects using this Title as a template
3435 * Also stores the IDs in the link cache.
3437 * WARNING: do not use this function on arbitrary user-supplied titles!
3438 * On heavily-used templates it will max out the memory.
3440 * @param array $options May be FOR UPDATE
3441 * @return Title[] Array of Title the Title objects linking here
3443 public function getTemplateLinksTo( $options = array() ) {
3444 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3448 * Get an array of Title objects linked from this Title
3449 * Also stores the IDs in the link cache.
3451 * WARNING: do not use this function on arbitrary user-supplied titles!
3452 * On heavily-used templates it will max out the memory.
3454 * @param array $options May be FOR UPDATE
3455 * @param string $table Table name
3456 * @param string $prefix Fields prefix
3457 * @return array Array of Title objects linking here
3459 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3460 global $wgContentHandlerUseDB;
3462 $id = $this->getArticleID();
3464 # If the page doesn't exist; there can't be any link from this page
3465 if ( !$id ) {
3466 return array();
3469 if ( count( $options ) > 0 ) {
3470 $db = wfGetDB( DB_MASTER );
3471 } else {
3472 $db = wfGetDB( DB_SLAVE );
3475 $namespaceFiled = "{$prefix}_namespace";
3476 $titleField = "{$prefix}_title";
3478 $fields = array(
3479 $namespaceFiled,
3480 $titleField,
3481 'page_id',
3482 'page_len',
3483 'page_is_redirect',
3484 'page_latest'
3487 if ( $wgContentHandlerUseDB ) {
3488 $fields[] = 'page_content_model';
3491 $res = $db->select(
3492 array( $table, 'page' ),
3493 $fields,
3494 array( "{$prefix}_from" => $id ),
3495 __METHOD__,
3496 $options,
3497 array( 'page' => array(
3498 'LEFT JOIN',
3499 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3503 $retVal = array();
3504 if ( $res->numRows() ) {
3505 $linkCache = LinkCache::singleton();
3506 foreach ( $res as $row ) {
3507 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3508 if ( $titleObj ) {
3509 if ( $row->page_id ) {
3510 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3511 } else {
3512 $linkCache->addBadLinkObj( $titleObj );
3514 $retVal[] = $titleObj;
3518 return $retVal;
3522 * Get an array of Title objects used on this Title as a template
3523 * Also stores the IDs in the link cache.
3525 * WARNING: do not use this function on arbitrary user-supplied titles!
3526 * On heavily-used templates it will max out the memory.
3528 * @param array $options May be FOR UPDATE
3529 * @return Title[] Array of Title the Title objects used here
3531 public function getTemplateLinksFrom( $options = array() ) {
3532 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3536 * Get an array of Title objects referring to non-existent articles linked
3537 * from this page.
3539 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3540 * should use redirect table in this case).
3541 * @return Title[] Array of Title the Title objects
3543 public function getBrokenLinksFrom() {
3544 if ( $this->getArticleID() == 0 ) {
3545 # All links from article ID 0 are false positives
3546 return array();
3549 $dbr = wfGetDB( DB_SLAVE );
3550 $res = $dbr->select(
3551 array( 'page', 'pagelinks' ),
3552 array( 'pl_namespace', 'pl_title' ),
3553 array(
3554 'pl_from' => $this->getArticleID(),
3555 'page_namespace IS NULL'
3557 __METHOD__, array(),
3558 array(
3559 'page' => array(
3560 'LEFT JOIN',
3561 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3566 $retVal = array();
3567 foreach ( $res as $row ) {
3568 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3570 return $retVal;
3574 * Get a list of URLs to purge from the Squid cache when this
3575 * page changes
3577 * @return string[] Array of String the URLs
3579 public function getSquidURLs() {
3580 $urls = array(
3581 $this->getInternalURL(),
3582 $this->getInternalURL( 'action=history' )
3585 $pageLang = $this->getPageLanguage();
3586 if ( $pageLang->hasVariants() ) {
3587 $variants = $pageLang->getVariants();
3588 foreach ( $variants as $vCode ) {
3589 $urls[] = $this->getInternalURL( '', $vCode );
3593 // If we are looking at a css/js user subpage, purge the action=raw.
3594 if ( $this->isJsSubpage() ) {
3595 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3596 } elseif ( $this->isCssSubpage() ) {
3597 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3600 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3601 return $urls;
3605 * Purge all applicable Squid URLs
3607 public function purgeSquid() {
3608 global $wgUseSquid;
3609 if ( $wgUseSquid ) {
3610 $urls = $this->getSquidURLs();
3611 $u = new SquidUpdate( $urls );
3612 $u->doUpdate();
3617 * Move this page without authentication
3619 * @param Title $nt The new page Title
3620 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3622 public function moveNoAuth( &$nt ) {
3623 return $this->moveTo( $nt, false );
3627 * Check whether a given move operation would be valid.
3628 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3630 * @param Title $nt The new title
3631 * @param bool $auth Indicates whether $wgUser's permissions
3632 * should be checked
3633 * @param string $reason Is the log summary of the move, used for spam checking
3634 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3636 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3637 global $wgUser, $wgContentHandlerUseDB;
3639 $errors = array();
3640 if ( !$nt ) {
3641 // Normally we'd add this to $errors, but we'll get
3642 // lots of syntax errors if $nt is not an object
3643 return array( array( 'badtitletext' ) );
3645 if ( $this->equals( $nt ) ) {
3646 $errors[] = array( 'selfmove' );
3648 if ( !$this->isMovable() ) {
3649 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3651 if ( $nt->isExternal() ) {
3652 $errors[] = array( 'immobile-target-namespace-iw' );
3654 if ( !$nt->isMovable() ) {
3655 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3658 $oldid = $this->getArticleID();
3659 $newid = $nt->getArticleID();
3661 if ( strlen( $nt->getDBkey() ) < 1 ) {
3662 $errors[] = array( 'articleexists' );
3664 if (
3665 ( $this->getDBkey() == '' ) ||
3666 ( !$oldid ) ||
3667 ( $nt->getDBkey() == '' )
3669 $errors[] = array( 'badarticleerror' );
3672 // Content model checks
3673 if ( !$wgContentHandlerUseDB &&
3674 $this->getContentModel() !== $nt->getContentModel() ) {
3675 // can't move a page if that would change the page's content model
3676 $errors[] = array(
3677 'bad-target-model',
3678 ContentHandler::getLocalizedName( $this->getContentModel() ),
3679 ContentHandler::getLocalizedName( $nt->getContentModel() )
3683 // Image-specific checks
3684 if ( $this->getNamespace() == NS_FILE ) {
3685 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3688 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3689 $errors[] = array( 'nonfile-cannot-move-to-file' );
3692 if ( $auth ) {
3693 $errors = wfMergeErrorArrays( $errors,
3694 $this->getUserPermissionsErrors( 'move', $wgUser ),
3695 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3696 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3697 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3700 $match = EditPage::matchSummarySpamRegex( $reason );
3701 if ( $match !== false ) {
3702 // This is kind of lame, won't display nice
3703 $errors[] = array( 'spamprotectiontext' );
3706 $err = null;
3707 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3708 $errors[] = array( 'hookaborted', $err );
3711 # The move is allowed only if (1) the target doesn't exist, or
3712 # (2) the target is a redirect to the source, and has no history
3713 # (so we can undo bad moves right after they're done).
3715 if ( 0 != $newid ) { # Target exists; check for validity
3716 if ( !$this->isValidMoveTarget( $nt ) ) {
3717 $errors[] = array( 'articleexists' );
3719 } else {
3720 $tp = $nt->getTitleProtection();
3721 $right = $tp['pt_create_perm'];
3722 if ( $right == 'sysop' ) {
3723 $right = 'editprotected'; // B/C
3725 if ( $right == 'autoconfirmed' ) {
3726 $right = 'editsemiprotected'; // B/C
3728 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3729 $errors[] = array( 'cantmove-titleprotected' );
3732 if ( empty( $errors ) ) {
3733 return true;
3735 return $errors;
3739 * Check if the requested move target is a valid file move target
3740 * @param Title $nt Target title
3741 * @return array List of errors
3743 protected function validateFileMoveOperation( $nt ) {
3744 global $wgUser;
3746 $errors = array();
3748 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3750 $file = wfLocalFile( $this );
3751 if ( $file->exists() ) {
3752 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3753 $errors[] = array( 'imageinvalidfilename' );
3755 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3756 $errors[] = array( 'imagetypemismatch' );
3760 if ( $nt->getNamespace() != NS_FILE ) {
3761 $errors[] = array( 'imagenocrossnamespace' );
3762 // From here we want to do checks on a file object, so if we can't
3763 // create one, we must return.
3764 return $errors;
3767 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3769 $destFile = wfLocalFile( $nt );
3770 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3771 $errors[] = array( 'file-exists-sharedrepo' );
3774 return $errors;
3778 * Move a title to a new location
3780 * @param Title $nt The new title
3781 * @param bool $auth Indicates whether $wgUser's permissions
3782 * should be checked
3783 * @param string $reason The reason for the move
3784 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3785 * Ignored if the user doesn't have the suppressredirect right.
3786 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3788 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3789 global $wgUser;
3790 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3791 if ( is_array( $err ) ) {
3792 // Auto-block user's IP if the account was "hard" blocked
3793 $wgUser->spreadAnyEditBlock();
3794 return $err;
3796 // Check suppressredirect permission
3797 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3798 $createRedirect = true;
3801 wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) );
3803 // If it is a file, move it first.
3804 // It is done before all other moving stuff is done because it's hard to revert.
3805 $dbw = wfGetDB( DB_MASTER );
3806 if ( $this->getNamespace() == NS_FILE ) {
3807 $file = wfLocalFile( $this );
3808 if ( $file->exists() ) {
3809 $status = $file->move( $nt );
3810 if ( !$status->isOk() ) {
3811 return $status->getErrorsArray();
3814 // Clear RepoGroup process cache
3815 RepoGroup::singleton()->clearCache( $this );
3816 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3819 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3820 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3821 $protected = $this->isProtected();
3823 // Do the actual move
3824 $this->moveToInternal( $nt, $reason, $createRedirect );
3826 // Refresh the sortkey for this row. Be careful to avoid resetting
3827 // cl_timestamp, which may disturb time-based lists on some sites.
3828 $prefixes = $dbw->select(
3829 'categorylinks',
3830 array( 'cl_sortkey_prefix', 'cl_to' ),
3831 array( 'cl_from' => $pageid ),
3832 __METHOD__
3834 foreach ( $prefixes as $prefixRow ) {
3835 $prefix = $prefixRow->cl_sortkey_prefix;
3836 $catTo = $prefixRow->cl_to;
3837 $dbw->update( 'categorylinks',
3838 array(
3839 'cl_sortkey' => Collation::singleton()->getSortKey(
3840 $nt->getCategorySortkey( $prefix ) ),
3841 'cl_timestamp=cl_timestamp' ),
3842 array(
3843 'cl_from' => $pageid,
3844 'cl_to' => $catTo ),
3845 __METHOD__
3849 $redirid = $this->getArticleID();
3851 if ( $protected ) {
3852 # Protect the redirect title as the title used to be...
3853 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3854 array(
3855 'pr_page' => $redirid,
3856 'pr_type' => 'pr_type',
3857 'pr_level' => 'pr_level',
3858 'pr_cascade' => 'pr_cascade',
3859 'pr_user' => 'pr_user',
3860 'pr_expiry' => 'pr_expiry'
3862 array( 'pr_page' => $pageid ),
3863 __METHOD__,
3864 array( 'IGNORE' )
3866 # Update the protection log
3867 $log = new LogPage( 'protect' );
3868 $comment = wfMessage(
3869 'prot_1movedto2',
3870 $this->getPrefixedText(),
3871 $nt->getPrefixedText()
3872 )->inContentLanguage()->text();
3873 if ( $reason ) {
3874 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3876 // @todo FIXME: $params?
3877 $logId = $log->addEntry(
3878 'move_prot',
3879 $nt,
3880 $comment,
3881 array( $this->getPrefixedText() ),
3882 $wgUser
3885 // reread inserted pr_ids for log relation
3886 $insertedPrIds = $dbw->select(
3887 'page_restrictions',
3888 'pr_id',
3889 array( 'pr_page' => $redirid ),
3890 __METHOD__
3892 $logRelationsValues = array();
3893 foreach ( $insertedPrIds as $prid ) {
3894 $logRelationsValues[] = $prid->pr_id;
3896 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
3899 # Update watchlists
3900 $oldnamespace = MWNamespace::getSubject( $this->getNamespace() );
3901 $newnamespace = MWNamespace::getSubject( $nt->getNamespace() );
3902 $oldtitle = $this->getDBkey();
3903 $newtitle = $nt->getDBkey();
3905 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3906 WatchedItem::duplicateEntries( $this, $nt );
3909 $dbw->commit( __METHOD__ );
3911 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid, $reason ) );
3912 return true;
3916 * Move page to a title which is either a redirect to the
3917 * source page or nonexistent
3919 * @param Title $nt The page to move to, which should be a redirect or nonexistent
3920 * @param string $reason The reason for the move
3921 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3922 * if the user has the suppressredirect right
3923 * @throws MWException
3925 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3926 global $wgUser, $wgContLang;
3928 if ( $nt->exists() ) {
3929 $moveOverRedirect = true;
3930 $logType = 'move_redir';
3931 } else {
3932 $moveOverRedirect = false;
3933 $logType = 'move';
3936 if ( $createRedirect ) {
3937 if ( $this->getNamespace() == NS_CATEGORY
3938 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
3940 $redirectContent = new WikitextContent(
3941 wfMessage( 'category-move-redirect-override' )
3942 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
3943 } else {
3944 $contentHandler = ContentHandler::getForTitle( $this );
3945 $redirectContent = $contentHandler->makeRedirectContent( $nt,
3946 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
3949 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3950 } else {
3951 $redirectContent = null;
3954 $logEntry = new ManualLogEntry( 'move', $logType );
3955 $logEntry->setPerformer( $wgUser );
3956 $logEntry->setTarget( $this );
3957 $logEntry->setComment( $reason );
3958 $logEntry->setParameters( array(
3959 '4::target' => $nt->getPrefixedText(),
3960 '5::noredir' => $redirectContent ? '0': '1',
3961 ) );
3963 $formatter = LogFormatter::newFromEntry( $logEntry );
3964 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3965 $comment = $formatter->getPlainActionText();
3966 if ( $reason ) {
3967 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3969 # Truncate for whole multibyte characters.
3970 $comment = $wgContLang->truncate( $comment, 255 );
3972 $oldid = $this->getArticleID();
3974 $dbw = wfGetDB( DB_MASTER );
3976 $newpage = WikiPage::factory( $nt );
3978 if ( $moveOverRedirect ) {
3979 $newid = $nt->getArticleID();
3980 $newcontent = $newpage->getContent();
3982 # Delete the old redirect. We don't save it to history since
3983 # by definition if we've got here it's rather uninteresting.
3984 # We have to remove it so that the next step doesn't trigger
3985 # a conflict on the unique namespace+title index...
3986 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3988 $newpage->doDeleteUpdates( $newid, $newcontent );
3991 # Save a null revision in the page's history notifying of the move
3992 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true, $wgUser );
3993 if ( !is_object( $nullRevision ) ) {
3994 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3997 $nullRevision->insertOn( $dbw );
3999 # Change the name of the target page:
4000 $dbw->update( 'page',
4001 /* SET */ array(
4002 'page_namespace' => $nt->getNamespace(),
4003 'page_title' => $nt->getDBkey(),
4005 /* WHERE */ array( 'page_id' => $oldid ),
4006 __METHOD__
4009 // clean up the old title before reset article id - bug 45348
4010 if ( !$redirectContent ) {
4011 WikiPage::onArticleDelete( $this );
4014 $this->resetArticleID( 0 ); // 0 == non existing
4015 $nt->resetArticleID( $oldid );
4016 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
4018 $newpage->updateRevisionOn( $dbw, $nullRevision );
4020 wfRunHooks( 'NewRevisionFromEditComplete',
4021 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
4023 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
4025 if ( !$moveOverRedirect ) {
4026 WikiPage::onArticleCreate( $nt );
4029 # Recreate the redirect, this time in the other direction.
4030 if ( $redirectContent ) {
4031 $redirectArticle = WikiPage::factory( $this );
4032 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
4033 $newid = $redirectArticle->insertOn( $dbw );
4034 if ( $newid ) { // sanity
4035 $this->resetArticleID( $newid );
4036 $redirectRevision = new Revision( array(
4037 'title' => $this, // for determining the default content model
4038 'page' => $newid,
4039 'user_text' => $wgUser->getName(),
4040 'user' => $wgUser->getId(),
4041 'comment' => $comment,
4042 'content' => $redirectContent ) );
4043 $redirectRevision->insertOn( $dbw );
4044 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
4046 wfRunHooks( 'NewRevisionFromEditComplete',
4047 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
4049 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
4053 # Log the move
4054 $logid = $logEntry->insert();
4055 $logEntry->publish( $logid );
4059 * Move this page's subpages to be subpages of $nt
4061 * @param Title $nt Move target
4062 * @param bool $auth Whether $wgUser's permissions should be checked
4063 * @param string $reason The reason for the move
4064 * @param bool $createRedirect Whether to create redirects from the old subpages to
4065 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4066 * @return array Array with old page titles as keys, and strings (new page titles) or
4067 * arrays (errors) as values, or an error array with numeric indices if no pages
4068 * were moved
4070 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
4071 global $wgMaximumMovedPages;
4072 // Check permissions
4073 if ( !$this->userCan( 'move-subpages' ) ) {
4074 return array( 'cant-move-subpages' );
4076 // Do the source and target namespaces support subpages?
4077 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4078 return array( 'namespace-nosubpages',
4079 MWNamespace::getCanonicalName( $this->getNamespace() ) );
4081 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
4082 return array( 'namespace-nosubpages',
4083 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
4086 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
4087 $retval = array();
4088 $count = 0;
4089 foreach ( $subpages as $oldSubpage ) {
4090 $count++;
4091 if ( $count > $wgMaximumMovedPages ) {
4092 $retval[$oldSubpage->getPrefixedText()] =
4093 array( 'movepage-max-pages',
4094 $wgMaximumMovedPages );
4095 break;
4098 // We don't know whether this function was called before
4099 // or after moving the root page, so check both
4100 // $this and $nt
4101 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4102 || $oldSubpage->getArticleID() == $nt->getArticleID()
4104 // When moving a page to a subpage of itself,
4105 // don't move it twice
4106 continue;
4108 $newPageName = preg_replace(
4109 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4110 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
4111 $oldSubpage->getDBkey() );
4112 if ( $oldSubpage->isTalkPage() ) {
4113 $newNs = $nt->getTalkPage()->getNamespace();
4114 } else {
4115 $newNs = $nt->getSubjectPage()->getNamespace();
4117 # Bug 14385: we need makeTitleSafe because the new page names may
4118 # be longer than 255 characters.
4119 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
4121 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
4122 if ( $success === true ) {
4123 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4124 } else {
4125 $retval[$oldSubpage->getPrefixedText()] = $success;
4128 return $retval;
4132 * Checks if this page is just a one-rev redirect.
4133 * Adds lock, so don't use just for light purposes.
4135 * @return bool
4137 public function isSingleRevRedirect() {
4138 global $wgContentHandlerUseDB;
4140 $dbw = wfGetDB( DB_MASTER );
4142 # Is it a redirect?
4143 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
4144 if ( $wgContentHandlerUseDB ) {
4145 $fields[] = 'page_content_model';
4148 $row = $dbw->selectRow( 'page',
4149 $fields,
4150 $this->pageCond(),
4151 __METHOD__,
4152 array( 'FOR UPDATE' )
4154 # Cache some fields we may want
4155 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4156 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4157 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4158 $this->mContentModel = $row && isset( $row->page_content_model )
4159 ? strval( $row->page_content_model )
4160 : false;
4162 if ( !$this->mRedirect ) {
4163 return false;
4165 # Does the article have a history?
4166 $row = $dbw->selectField( array( 'page', 'revision' ),
4167 'rev_id',
4168 array( 'page_namespace' => $this->getNamespace(),
4169 'page_title' => $this->getDBkey(),
4170 'page_id=rev_page',
4171 'page_latest != rev_id'
4173 __METHOD__,
4174 array( 'FOR UPDATE' )
4176 # Return true if there was no history
4177 return ( $row === false );
4181 * Checks if $this can be moved to a given Title
4182 * - Selects for update, so don't call it unless you mean business
4184 * @param Title $nt The new title to check
4185 * @return bool
4187 public function isValidMoveTarget( $nt ) {
4188 # Is it an existing file?
4189 if ( $nt->getNamespace() == NS_FILE ) {
4190 $file = wfLocalFile( $nt );
4191 if ( $file->exists() ) {
4192 wfDebug( __METHOD__ . ": file exists\n" );
4193 return false;
4196 # Is it a redirect with no history?
4197 if ( !$nt->isSingleRevRedirect() ) {
4198 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4199 return false;
4201 # Get the article text
4202 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4203 if ( !is_object( $rev ) ) {
4204 return false;
4206 $content = $rev->getContent();
4207 # Does the redirect point to the source?
4208 # Or is it a broken self-redirect, usually caused by namespace collisions?
4209 $redirTitle = $content ? $content->getRedirectTarget() : null;
4211 if ( $redirTitle ) {
4212 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4213 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4214 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4215 return false;
4216 } else {
4217 return true;
4219 } else {
4220 # Fail safe (not a redirect after all. strange.)
4221 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4222 " is a redirect, but it doesn't contain a valid redirect.\n" );
4223 return false;
4228 * Get categories to which this Title belongs and return an array of
4229 * categories' names.
4231 * @return array Array of parents in the form:
4232 * $parent => $currentarticle
4234 public function getParentCategories() {
4235 global $wgContLang;
4237 $data = array();
4239 $titleKey = $this->getArticleID();
4241 if ( $titleKey === 0 ) {
4242 return $data;
4245 $dbr = wfGetDB( DB_SLAVE );
4247 $res = $dbr->select(
4248 'categorylinks',
4249 'cl_to',
4250 array( 'cl_from' => $titleKey ),
4251 __METHOD__
4254 if ( $res->numRows() > 0 ) {
4255 foreach ( $res as $row ) {
4256 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4257 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
4260 return $data;
4264 * Get a tree of parent categories
4266 * @param array $children Array with the children in the keys, to check for circular refs
4267 * @return array Tree of parent categories
4269 public function getParentCategoryTree( $children = array() ) {
4270 $stack = array();
4271 $parents = $this->getParentCategories();
4273 if ( $parents ) {
4274 foreach ( $parents as $parent => $current ) {
4275 if ( array_key_exists( $parent, $children ) ) {
4276 # Circular reference
4277 $stack[$parent] = array();
4278 } else {
4279 $nt = Title::newFromText( $parent );
4280 if ( $nt ) {
4281 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
4287 return $stack;
4291 * Get an associative array for selecting this title from
4292 * the "page" table
4294 * @return array Array suitable for the $where parameter of DB::select()
4296 public function pageCond() {
4297 if ( $this->mArticleID > 0 ) {
4298 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4299 return array( 'page_id' => $this->mArticleID );
4300 } else {
4301 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
4306 * Get the revision ID of the previous revision
4308 * @param int $revId Revision ID. Get the revision that was before this one.
4309 * @param int $flags Title::GAID_FOR_UPDATE
4310 * @return int|bool Old revision ID, or false if none exists
4312 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4313 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4314 $revId = $db->selectField( 'revision', 'rev_id',
4315 array(
4316 'rev_page' => $this->getArticleID( $flags ),
4317 'rev_id < ' . intval( $revId )
4319 __METHOD__,
4320 array( 'ORDER BY' => 'rev_id DESC' )
4323 if ( $revId === false ) {
4324 return false;
4325 } else {
4326 return intval( $revId );
4331 * Get the revision ID of the next revision
4333 * @param int $revId Revision ID. Get the revision that was after this one.
4334 * @param int $flags Title::GAID_FOR_UPDATE
4335 * @return int|bool Next revision ID, or false if none exists
4337 public function getNextRevisionID( $revId, $flags = 0 ) {
4338 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4339 $revId = $db->selectField( 'revision', 'rev_id',
4340 array(
4341 'rev_page' => $this->getArticleID( $flags ),
4342 'rev_id > ' . intval( $revId )
4344 __METHOD__,
4345 array( 'ORDER BY' => 'rev_id' )
4348 if ( $revId === false ) {
4349 return false;
4350 } else {
4351 return intval( $revId );
4356 * Get the first revision of the page
4358 * @param int $flags Title::GAID_FOR_UPDATE
4359 * @return Revision|null If page doesn't exist
4361 public function getFirstRevision( $flags = 0 ) {
4362 $pageId = $this->getArticleID( $flags );
4363 if ( $pageId ) {
4364 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4365 $row = $db->selectRow( 'revision', Revision::selectFields(),
4366 array( 'rev_page' => $pageId ),
4367 __METHOD__,
4368 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4370 if ( $row ) {
4371 return new Revision( $row );
4374 return null;
4378 * Get the oldest revision timestamp of this page
4380 * @param int $flags Title::GAID_FOR_UPDATE
4381 * @return string MW timestamp
4383 public function getEarliestRevTime( $flags = 0 ) {
4384 $rev = $this->getFirstRevision( $flags );
4385 return $rev ? $rev->getTimestamp() : null;
4389 * Check if this is a new page
4391 * @return bool
4393 public function isNewPage() {
4394 $dbr = wfGetDB( DB_SLAVE );
4395 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4399 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4401 * @return bool
4403 public function isBigDeletion() {
4404 global $wgDeleteRevisionsLimit;
4406 if ( !$wgDeleteRevisionsLimit ) {
4407 return false;
4410 $revCount = $this->estimateRevisionCount();
4411 return $revCount > $wgDeleteRevisionsLimit;
4415 * Get the approximate revision count of this page.
4417 * @return int
4419 public function estimateRevisionCount() {
4420 if ( !$this->exists() ) {
4421 return 0;
4424 if ( $this->mEstimateRevisions === null ) {
4425 $dbr = wfGetDB( DB_SLAVE );
4426 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4427 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4430 return $this->mEstimateRevisions;
4434 * Get the number of revisions between the given revision.
4435 * Used for diffs and other things that really need it.
4437 * @param int|Revision $old Old revision or rev ID (first before range)
4438 * @param int|Revision $new New revision or rev ID (first after range)
4439 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4440 * @return int Number of revisions between these revisions.
4442 public function countRevisionsBetween( $old, $new, $max = null ) {
4443 if ( !( $old instanceof Revision ) ) {
4444 $old = Revision::newFromTitle( $this, (int)$old );
4446 if ( !( $new instanceof Revision ) ) {
4447 $new = Revision::newFromTitle( $this, (int)$new );
4449 if ( !$old || !$new ) {
4450 return 0; // nothing to compare
4452 $dbr = wfGetDB( DB_SLAVE );
4453 $conds = array(
4454 'rev_page' => $this->getArticleID(),
4455 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4456 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4458 if ( $max !== null ) {
4459 $res = $dbr->select( 'revision', '1',
4460 $conds,
4461 __METHOD__,
4462 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4464 return $res->numRows();
4465 } else {
4466 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4471 * Get the authors between the given revisions or revision IDs.
4472 * Used for diffs and other things that really need it.
4474 * @since 1.23
4476 * @param int|Revision $old Old revision or rev ID (first before range by default)
4477 * @param int|Revision $new New revision or rev ID (first after range by default)
4478 * @param int $limit Maximum number of authors
4479 * @param string|array $options (Optional): Single option, or an array of options:
4480 * 'include_old' Include $old in the range; $new is excluded.
4481 * 'include_new' Include $new in the range; $old is excluded.
4482 * 'include_both' Include both $old and $new in the range.
4483 * Unknown option values are ignored.
4484 * @return array|null Names of revision authors in the range; null if not both revisions exist
4486 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4487 if ( !( $old instanceof Revision ) ) {
4488 $old = Revision::newFromTitle( $this, (int)$old );
4490 if ( !( $new instanceof Revision ) ) {
4491 $new = Revision::newFromTitle( $this, (int)$new );
4493 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4494 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4495 // in the sanity check below?
4496 if ( !$old || !$new ) {
4497 return null; // nothing to compare
4499 $authors = array();
4500 $old_cmp = '>';
4501 $new_cmp = '<';
4502 $options = (array)$options;
4503 if ( in_array( 'include_old', $options ) ) {
4504 $old_cmp = '>=';
4506 if ( in_array( 'include_new', $options ) ) {
4507 $new_cmp = '<=';
4509 if ( in_array( 'include_both', $options ) ) {
4510 $old_cmp = '>=';
4511 $new_cmp = '<=';
4513 // No DB query needed if $old and $new are the same or successive revisions:
4514 if ( $old->getId() === $new->getId() ) {
4515 return ( $old_cmp === '>' && $new_cmp === '<' ) ? array() : array( $old->getRawUserText() );
4516 } elseif ( $old->getId() === $new->getParentId() ) {
4517 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4518 $authors[] = $old->getRawUserText();
4519 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4520 $authors[] = $new->getRawUserText();
4522 } elseif ( $old_cmp === '>=' ) {
4523 $authors[] = $old->getRawUserText();
4524 } elseif ( $new_cmp === '<=' ) {
4525 $authors[] = $new->getRawUserText();
4527 return $authors;
4529 $dbr = wfGetDB( DB_SLAVE );
4530 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4531 array(
4532 'rev_page' => $this->getArticleID(),
4533 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4534 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4535 ), __METHOD__,
4536 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4538 foreach ( $res as $row ) {
4539 $authors[] = $row->rev_user_text;
4541 return $authors;
4545 * Get the number of authors between the given revisions or revision IDs.
4546 * Used for diffs and other things that really need it.
4548 * @param int|Revision $old Old revision or rev ID (first before range by default)
4549 * @param int|Revision $new New revision or rev ID (first after range by default)
4550 * @param int $limit Maximum number of authors
4551 * @param string|array $options (Optional): Single option, or an array of options:
4552 * 'include_old' Include $old in the range; $new is excluded.
4553 * 'include_new' Include $new in the range; $old is excluded.
4554 * 'include_both' Include both $old and $new in the range.
4555 * Unknown option values are ignored.
4556 * @return int Number of revision authors in the range; zero if not both revisions exist
4558 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4559 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4560 return $authors ? count( $authors ) : 0;
4564 * Compare with another title.
4566 * @param Title $title
4567 * @return bool
4569 public function equals( Title $title ) {
4570 // Note: === is necessary for proper matching of number-like titles.
4571 return $this->getInterwiki() === $title->getInterwiki()
4572 && $this->getNamespace() == $title->getNamespace()
4573 && $this->getDBkey() === $title->getDBkey();
4577 * Check if this title is a subpage of another title
4579 * @param Title $title
4580 * @return bool
4582 public function isSubpageOf( Title $title ) {
4583 return $this->getInterwiki() === $title->getInterwiki()
4584 && $this->getNamespace() == $title->getNamespace()
4585 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4589 * Check if page exists. For historical reasons, this function simply
4590 * checks for the existence of the title in the page table, and will
4591 * thus return false for interwiki links, special pages and the like.
4592 * If you want to know if a title can be meaningfully viewed, you should
4593 * probably call the isKnown() method instead.
4595 * @return bool
4597 public function exists() {
4598 return $this->getArticleID() != 0;
4602 * Should links to this title be shown as potentially viewable (i.e. as
4603 * "bluelinks"), even if there's no record by this title in the page
4604 * table?
4606 * This function is semi-deprecated for public use, as well as somewhat
4607 * misleadingly named. You probably just want to call isKnown(), which
4608 * calls this function internally.
4610 * (ISSUE: Most of these checks are cheap, but the file existence check
4611 * can potentially be quite expensive. Including it here fixes a lot of
4612 * existing code, but we might want to add an optional parameter to skip
4613 * it and any other expensive checks.)
4615 * @return bool
4617 public function isAlwaysKnown() {
4618 $isKnown = null;
4621 * Allows overriding default behavior for determining if a page exists.
4622 * If $isKnown is kept as null, regular checks happen. If it's
4623 * a boolean, this value is returned by the isKnown method.
4625 * @since 1.20
4627 * @param Title $title
4628 * @param bool|null $isKnown
4630 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4632 if ( !is_null( $isKnown ) ) {
4633 return $isKnown;
4636 if ( $this->isExternal() ) {
4637 return true; // any interwiki link might be viewable, for all we know
4640 switch ( $this->mNamespace ) {
4641 case NS_MEDIA:
4642 case NS_FILE:
4643 // file exists, possibly in a foreign repo
4644 return (bool)wfFindFile( $this );
4645 case NS_SPECIAL:
4646 // valid special page
4647 return SpecialPageFactory::exists( $this->getDBkey() );
4648 case NS_MAIN:
4649 // selflink, possibly with fragment
4650 return $this->mDbkeyform == '';
4651 case NS_MEDIAWIKI:
4652 // known system message
4653 return $this->hasSourceText() !== false;
4654 default:
4655 return false;
4660 * Does this title refer to a page that can (or might) be meaningfully
4661 * viewed? In particular, this function may be used to determine if
4662 * links to the title should be rendered as "bluelinks" (as opposed to
4663 * "redlinks" to non-existent pages).
4664 * Adding something else to this function will cause inconsistency
4665 * since LinkHolderArray calls isAlwaysKnown() and does its own
4666 * page existence check.
4668 * @return bool
4670 public function isKnown() {
4671 return $this->isAlwaysKnown() || $this->exists();
4675 * Does this page have source text?
4677 * @return bool
4679 public function hasSourceText() {
4680 if ( $this->exists() ) {
4681 return true;
4684 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4685 // If the page doesn't exist but is a known system message, default
4686 // message content will be displayed, same for language subpages-
4687 // Use always content language to avoid loading hundreds of languages
4688 // to get the link color.
4689 global $wgContLang;
4690 list( $name, ) = MessageCache::singleton()->figureMessage(
4691 $wgContLang->lcfirst( $this->getText() )
4693 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4694 return $message->exists();
4697 return false;
4701 * Get the default message text or false if the message doesn't exist
4703 * @return string|bool
4705 public function getDefaultMessageText() {
4706 global $wgContLang;
4708 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4709 return false;
4712 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4713 $wgContLang->lcfirst( $this->getText() )
4715 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4717 if ( $message->exists() ) {
4718 return $message->plain();
4719 } else {
4720 return false;
4725 * Updates page_touched for this page; called from LinksUpdate.php
4727 * @return bool True if the update succeeded
4729 public function invalidateCache() {
4730 if ( wfReadOnly() ) {
4731 return false;
4734 if ( $this->mArticleID === 0 ) {
4735 return true; // avoid gap locking if we know it's not there
4738 $method = __METHOD__;
4739 $dbw = wfGetDB( DB_MASTER );
4740 $conds = $this->pageCond();
4741 $dbw->onTransactionIdle( function() use ( $dbw, $conds, $method ) {
4742 $dbw->update(
4743 'page',
4744 array( 'page_touched' => $dbw->timestamp() ),
4745 $conds,
4746 $method
4748 } );
4750 return true;
4754 * Update page_touched timestamps and send squid purge messages for
4755 * pages linking to this title. May be sent to the job queue depending
4756 * on the number of links. Typically called on create and delete.
4758 public function touchLinks() {
4759 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4760 $u->doUpdate();
4762 if ( $this->getNamespace() == NS_CATEGORY ) {
4763 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4764 $u->doUpdate();
4769 * Get the last touched timestamp
4771 * @param DatabaseBase $db Optional db
4772 * @return string Last-touched timestamp
4774 public function getTouched( $db = null ) {
4775 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4776 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4777 return $touched;
4781 * Get the timestamp when this page was updated since the user last saw it.
4783 * @param User $user
4784 * @return string|null
4786 public function getNotificationTimestamp( $user = null ) {
4787 global $wgUser, $wgShowUpdatedMarker;
4788 // Assume current user if none given
4789 if ( !$user ) {
4790 $user = $wgUser;
4792 // Check cache first
4793 $uid = $user->getId();
4794 // avoid isset here, as it'll return false for null entries
4795 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4796 return $this->mNotificationTimestamp[$uid];
4798 if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) {
4799 $this->mNotificationTimestamp[$uid] = false;
4800 return $this->mNotificationTimestamp[$uid];
4802 // Don't cache too much!
4803 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4804 $this->mNotificationTimestamp = array();
4806 $dbr = wfGetDB( DB_SLAVE );
4807 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4808 'wl_notificationtimestamp',
4809 array(
4810 'wl_user' => $user->getId(),
4811 'wl_namespace' => $this->getNamespace(),
4812 'wl_title' => $this->getDBkey(),
4814 __METHOD__
4816 return $this->mNotificationTimestamp[$uid];
4820 * Generate strings used for xml 'id' names in monobook tabs
4822 * @param string $prepend Defaults to 'nstab-'
4823 * @return string XML 'id' name
4825 public function getNamespaceKey( $prepend = 'nstab-' ) {
4826 global $wgContLang;
4827 // Gets the subject namespace if this title
4828 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4829 // Checks if canonical namespace name exists for namespace
4830 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4831 // Uses canonical namespace name
4832 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4833 } else {
4834 // Uses text of namespace
4835 $namespaceKey = $this->getSubjectNsText();
4837 // Makes namespace key lowercase
4838 $namespaceKey = $wgContLang->lc( $namespaceKey );
4839 // Uses main
4840 if ( $namespaceKey == '' ) {
4841 $namespaceKey = 'main';
4843 // Changes file to image for backwards compatibility
4844 if ( $namespaceKey == 'file' ) {
4845 $namespaceKey = 'image';
4847 return $prepend . $namespaceKey;
4851 * Get all extant redirects to this Title
4853 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4854 * @return Title[] Array of Title redirects to this title
4856 public function getRedirectsHere( $ns = null ) {
4857 $redirs = array();
4859 $dbr = wfGetDB( DB_SLAVE );
4860 $where = array(
4861 'rd_namespace' => $this->getNamespace(),
4862 'rd_title' => $this->getDBkey(),
4863 'rd_from = page_id'
4865 if ( $this->isExternal() ) {
4866 $where['rd_interwiki'] = $this->getInterwiki();
4867 } else {
4868 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4870 if ( !is_null( $ns ) ) {
4871 $where['page_namespace'] = $ns;
4874 $res = $dbr->select(
4875 array( 'redirect', 'page' ),
4876 array( 'page_namespace', 'page_title' ),
4877 $where,
4878 __METHOD__
4881 foreach ( $res as $row ) {
4882 $redirs[] = self::newFromRow( $row );
4884 return $redirs;
4888 * Check if this Title is a valid redirect target
4890 * @return bool
4892 public function isValidRedirectTarget() {
4893 global $wgInvalidRedirectTargets;
4895 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4896 if ( $this->isSpecial( 'Userlogout' ) ) {
4897 return false;
4900 foreach ( $wgInvalidRedirectTargets as $target ) {
4901 if ( $this->isSpecial( $target ) ) {
4902 return false;
4906 return true;
4910 * Get a backlink cache object
4912 * @return BacklinkCache
4914 public function getBacklinkCache() {
4915 return BacklinkCache::get( $this );
4919 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4921 * @return bool
4923 public function canUseNoindex() {
4924 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4926 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4927 ? $wgContentNamespaces
4928 : $wgExemptFromUserRobotsControl;
4930 return !in_array( $this->mNamespace, $bannedNamespaces );
4935 * Returns the raw sort key to be used for categories, with the specified
4936 * prefix. This will be fed to Collation::getSortKey() to get a
4937 * binary sortkey that can be used for actual sorting.
4939 * @param string $prefix The prefix to be used, specified using
4940 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4941 * prefix.
4942 * @return string
4944 public function getCategorySortkey( $prefix = '' ) {
4945 $unprefixed = $this->getText();
4947 // Anything that uses this hook should only depend
4948 // on the Title object passed in, and should probably
4949 // tell the users to run updateCollations.php --force
4950 // in order to re-sort existing category relations.
4951 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4952 if ( $prefix !== '' ) {
4953 # Separate with a line feed, so the unprefixed part is only used as
4954 # a tiebreaker when two pages have the exact same prefix.
4955 # In UCA, tab is the only character that can sort above LF
4956 # so we strip both of them from the original prefix.
4957 $prefix = strtr( $prefix, "\n\t", ' ' );
4958 return "$prefix\n$unprefixed";
4960 return $unprefixed;
4964 * Get the language in which the content of this page is written in
4965 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4966 * e.g. $wgLang (such as special pages, which are in the user language).
4968 * @since 1.18
4969 * @return Language
4971 public function getPageLanguage() {
4972 global $wgLang, $wgLanguageCode;
4973 wfProfileIn( __METHOD__ );
4974 if ( $this->isSpecialPage() ) {
4975 // special pages are in the user language
4976 wfProfileOut( __METHOD__ );
4977 return $wgLang;
4980 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4981 // Note that this may depend on user settings, so the cache should
4982 // be only per-request.
4983 // NOTE: ContentHandler::getPageLanguage() may need to load the
4984 // content to determine the page language!
4985 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4986 // tests.
4987 $contentHandler = ContentHandler::getForTitle( $this );
4988 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4989 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4990 } else {
4991 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4993 wfProfileOut( __METHOD__ );
4994 return $langObj;
4998 * Get the language in which the content of this page is written when
4999 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
5000 * e.g. $wgLang (such as special pages, which are in the user language).
5002 * @since 1.20
5003 * @return Language
5005 public function getPageViewLanguage() {
5006 global $wgLang;
5008 if ( $this->isSpecialPage() ) {
5009 // If the user chooses a variant, the content is actually
5010 // in a language whose code is the variant code.
5011 $variant = $wgLang->getPreferredVariant();
5012 if ( $wgLang->getCode() !== $variant ) {
5013 return Language::factory( $variant );
5016 return $wgLang;
5019 // @note Can't be cached persistently, depends on user settings.
5020 // @note ContentHandler::getPageViewLanguage() may need to load the
5021 // content to determine the page language!
5022 $contentHandler = ContentHandler::getForTitle( $this );
5023 $pageLang = $contentHandler->getPageViewLanguage( $this );
5024 return $pageLang;
5028 * Get a list of rendered edit notices for this page.
5030 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5031 * they will already be wrapped in paragraphs.
5033 * @since 1.21
5034 * @param int $oldid Revision ID that's being edited
5035 * @return array
5037 public function getEditNotices( $oldid = 0 ) {
5038 $notices = array();
5040 # Optional notices on a per-namespace and per-page basis
5041 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5042 $editnotice_ns_message = wfMessage( $editnotice_ns );
5043 if ( $editnotice_ns_message->exists() ) {
5044 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
5046 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
5047 $parts = explode( '/', $this->getDBkey() );
5048 $editnotice_base = $editnotice_ns;
5049 while ( count( $parts ) > 0 ) {
5050 $editnotice_base .= '-' . array_shift( $parts );
5051 $editnotice_base_msg = wfMessage( $editnotice_base );
5052 if ( $editnotice_base_msg->exists() ) {
5053 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
5056 } else {
5057 # Even if there are no subpages in namespace, we still don't want / in MW ns.
5058 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
5059 $editnoticeMsg = wfMessage( $editnoticeText );
5060 if ( $editnoticeMsg->exists() ) {
5061 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
5065 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
5066 return $notices;