Merge "Expose thumbnail file to extensions"
[mediawiki.git] / includes / Title.php
blob995deeb26d67fca2ace32a85bff049cd0bb6333e
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 $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix
65 var $mFragment = ''; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText = null; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 # Zero except in {{transclusion}} tags
83 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mHasSubpage; // /< Whether a page has any subpages
89 private $mPageLanguage = false; // /< The (string) language code of the page's language and content code.
90 private $mTitleValue = null; // /< A corresponding TitleValue object
91 // @}
93 /**
94 * B/C kludge: provide a TitleParser for use by Title.
95 * Ideally, Title would have no methods that need this.
96 * Avoid usage of this singleton by using TitleValue
97 * and the associated services when possible.
99 * @return TitleParser
101 private static function getTitleParser() {
102 global $wgContLang, $wgLocalInterwikis;
104 static $titleCodec = null;
105 static $titleCodecFingerprint = null;
107 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
108 // make sure we are using the right one. To detect changes over the course
109 // of a request, we remember a fingerprint of the config used to create the
110 // codec singleton, and re-create it if the fingerprint doesn't match.
111 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
113 if ( $fingerprint !== $titleCodecFingerprint ) {
114 $titleCodec = null;
117 if ( !$titleCodec ) {
118 $titleCodec = new MediaWikiTitleCodec( $wgContLang, GenderCache::singleton(), $wgLocalInterwikis );
119 $titleCodecFingerprint = $fingerprint;
122 return $titleCodec;
126 * B/C kludge: provide a TitleParser for use by Title.
127 * Ideally, Title would have no methods that need this.
128 * Avoid usage of this singleton by using TitleValue
129 * and the associated services when possible.
131 * @return TitleFormatter
133 private static function getTitleFormatter() {
134 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
135 // which implements TitleFormatter.
136 return self::getTitleParser();
140 * Constructor
142 /*protected*/ function __construct() { }
145 * Create a new Title from a prefixed DB key
147 * @param string $key the database key, which has underscores
148 * instead of spaces, possibly including namespace and
149 * interwiki prefixes
150 * @return Title, or NULL on an error
152 public static function newFromDBkey( $key ) {
153 $t = new Title();
154 $t->mDbkeyform = $key;
155 if ( $t->secureAndSplit() ) {
156 return $t;
157 } else {
158 return null;
163 * Create a new Title from a TitleValue
165 * @param TitleValue $titleValue, assumed to be safe.
167 * @return Title
169 public static function newFromTitleValue( TitleValue $titleValue ) {
170 return self::makeTitle(
171 $titleValue->getNamespace(),
172 $titleValue->getText(),
173 $titleValue->getFragment() );
177 * Create a new Title from text, such as what one would find in a link. De-
178 * codes any HTML entities in the text.
180 * @param string $text the link text; spaces, prefixes, and an
181 * initial ':' indicating the main namespace are accepted.
182 * @param int $defaultNamespace the namespace to use if none is specified
183 * by a prefix. If you want to force a specific namespace even if
184 * $text might begin with a namespace prefix, use makeTitle() or
185 * makeTitleSafe().
186 * @throws MWException
187 * @return Title|null - Title or null on an error.
189 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
190 if ( is_object( $text ) ) {
191 throw new MWException( 'Title::newFromText given an object' );
194 $cache = self::getTitleCache();
197 * Wiki pages often contain multiple links to the same page.
198 * Title normalization and parsing can become expensive on
199 * pages with many links, so we can save a little time by
200 * caching them.
202 * In theory these are value objects and won't get changed...
204 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
205 return $cache->get( $text );
208 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
209 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
211 $t = new Title();
212 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
213 $t->mDefaultNamespace = intval( $defaultNamespace );
215 if ( $t->secureAndSplit() ) {
216 if ( $defaultNamespace == NS_MAIN ) {
217 $cache->set( $text, $t );
219 return $t;
220 } else {
221 $ret = null;
222 return $ret;
227 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
229 * Example of wrong and broken code:
230 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
232 * Example of right code:
233 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
235 * Create a new Title from URL-encoded text. Ensures that
236 * the given title's length does not exceed the maximum.
238 * @param string $url the title, as might be taken from a URL
239 * @return Title the new object, or NULL on an error
241 public static function newFromURL( $url ) {
242 $t = new Title();
244 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
245 # but some URLs used it as a space replacement and they still come
246 # from some external search tools.
247 if ( strpos( self::legalChars(), '+' ) === false ) {
248 $url = str_replace( '+', ' ', $url );
251 $t->mDbkeyform = str_replace( ' ', '_', $url );
252 if ( $t->secureAndSplit() ) {
253 return $t;
254 } else {
255 return null;
260 * @return MapCacheLRU
262 private static function getTitleCache() {
263 if ( self::$titleCache == null ) {
264 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
266 return self::$titleCache;
270 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
271 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
273 * @return array
275 protected static function getSelectFields() {
276 global $wgContentHandlerUseDB;
278 $fields = array(
279 'page_namespace', 'page_title', 'page_id',
280 'page_len', 'page_is_redirect', 'page_latest',
283 if ( $wgContentHandlerUseDB ) {
284 $fields[] = 'page_content_model';
287 return $fields;
291 * Create a new Title from an article ID
293 * @param int $id the page_id corresponding to the Title to create
294 * @param int $flags use Title::GAID_FOR_UPDATE to use master
295 * @return Title|null the new object, or NULL on an error
297 public static function newFromID( $id, $flags = 0 ) {
298 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
299 $row = $db->selectRow(
300 'page',
301 self::getSelectFields(),
302 array( 'page_id' => $id ),
303 __METHOD__
305 if ( $row !== false ) {
306 $title = Title::newFromRow( $row );
307 } else {
308 $title = null;
310 return $title;
314 * Make an array of titles from an array of IDs
316 * @param array $ids of Int Array of IDs
317 * @return Array of Titles
319 public static function newFromIDs( $ids ) {
320 if ( !count( $ids ) ) {
321 return array();
323 $dbr = wfGetDB( DB_SLAVE );
325 $res = $dbr->select(
326 'page',
327 self::getSelectFields(),
328 array( 'page_id' => $ids ),
329 __METHOD__
332 $titles = array();
333 foreach ( $res as $row ) {
334 $titles[] = Title::newFromRow( $row );
336 return $titles;
340 * Make a Title object from a DB row
342 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
343 * @return Title corresponding Title
345 public static function newFromRow( $row ) {
346 $t = self::makeTitle( $row->page_namespace, $row->page_title );
347 $t->loadFromRow( $row );
348 return $t;
352 * Load Title object fields from a DB row.
353 * If false is given, the title will be treated as non-existing.
355 * @param $row stdClass|bool database row
357 public function loadFromRow( $row ) {
358 if ( $row ) { // page found
359 if ( isset( $row->page_id ) ) {
360 $this->mArticleID = (int)$row->page_id;
362 if ( isset( $row->page_len ) ) {
363 $this->mLength = (int)$row->page_len;
365 if ( isset( $row->page_is_redirect ) ) {
366 $this->mRedirect = (bool)$row->page_is_redirect;
368 if ( isset( $row->page_latest ) ) {
369 $this->mLatestID = (int)$row->page_latest;
371 if ( isset( $row->page_content_model ) ) {
372 $this->mContentModel = strval( $row->page_content_model );
373 } else {
374 $this->mContentModel = false; # initialized lazily in getContentModel()
376 } else { // page not found
377 $this->mArticleID = 0;
378 $this->mLength = 0;
379 $this->mRedirect = false;
380 $this->mLatestID = 0;
381 $this->mContentModel = false; # initialized lazily in getContentModel()
386 * Create a new Title from a namespace index and a DB key.
387 * It's assumed that $ns and $title are *valid*, for instance when
388 * they came directly from the database or a special page name.
389 * For convenience, spaces are converted to underscores so that
390 * eg user_text fields can be used directly.
392 * @param int $ns the namespace of the article
393 * @param string $title the unprefixed database key form
394 * @param string $fragment the link fragment (after the "#")
395 * @param string $interwiki the interwiki prefix
396 * @return Title the new object
398 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
399 $t = new Title();
400 $t->mInterwiki = $interwiki;
401 $t->mFragment = $fragment;
402 $t->mNamespace = $ns = intval( $ns );
403 $t->mDbkeyform = str_replace( ' ', '_', $title );
404 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
405 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
406 $t->mTextform = str_replace( '_', ' ', $title );
407 $t->mContentModel = false; # initialized lazily in getContentModel()
408 return $t;
412 * Create a new Title from a namespace index and a DB key.
413 * The parameters will be checked for validity, which is a bit slower
414 * than makeTitle() but safer for user-provided data.
416 * @param int $ns the namespace of the article
417 * @param string $title database key form
418 * @param string $fragment the link fragment (after the "#")
419 * @param string $interwiki interwiki prefix
420 * @return Title the new object, or NULL on an error
422 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
423 if ( !MWNamespace::exists( $ns ) ) {
424 return null;
427 $t = new Title();
428 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
429 if ( $t->secureAndSplit() ) {
430 return $t;
431 } else {
432 return null;
437 * Create a new Title for the Main Page
439 * @return Title the new object
441 public static function newMainPage() {
442 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
443 // Don't give fatal errors if the message is broken
444 if ( !$title ) {
445 $title = Title::newFromText( 'Main Page' );
447 return $title;
451 * Extract a redirect destination from a string and return the
452 * Title, or null if the text doesn't contain a valid redirect
453 * This will only return the very next target, useful for
454 * the redirect table and other checks that don't need full recursion
456 * @param string $text Text with possible redirect
457 * @return Title: The corresponding Title
458 * @deprecated since 1.21, use Content::getRedirectTarget instead.
460 public static function newFromRedirect( $text ) {
461 ContentHandler::deprecated( __METHOD__, '1.21' );
463 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
464 return $content->getRedirectTarget();
468 * Extract a redirect destination from a string and return the
469 * Title, or null if the text doesn't contain a valid redirect
470 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
471 * in order to provide (hopefully) the Title of the final destination instead of another redirect
473 * @param string $text Text with possible redirect
474 * @return Title
475 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
477 public static function newFromRedirectRecurse( $text ) {
478 ContentHandler::deprecated( __METHOD__, '1.21' );
480 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
481 return $content->getUltimateRedirectTarget();
485 * Extract a redirect destination from a string and return an
486 * array of Titles, or null if the text doesn't contain a valid redirect
487 * The last element in the array is the final destination after all redirects
488 * have been resolved (up to $wgMaxRedirects times)
490 * @param string $text Text with possible redirect
491 * @return Array of Titles, with the destination last
492 * @deprecated since 1.21, use Content::getRedirectChain instead.
494 public static function newFromRedirectArray( $text ) {
495 ContentHandler::deprecated( __METHOD__, '1.21' );
497 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
498 return $content->getRedirectChain();
502 * Get the prefixed DB key associated with an ID
504 * @param int $id the page_id of the article
505 * @return Title an object representing the article, or NULL if no such article was found
507 public static function nameOf( $id ) {
508 $dbr = wfGetDB( DB_SLAVE );
510 $s = $dbr->selectRow(
511 'page',
512 array( 'page_namespace', 'page_title' ),
513 array( 'page_id' => $id ),
514 __METHOD__
516 if ( $s === false ) {
517 return null;
520 $n = self::makeName( $s->page_namespace, $s->page_title );
521 return $n;
525 * Get a regex character class describing the legal characters in a link
527 * @return String the list of characters, not delimited
529 public static function legalChars() {
530 global $wgLegalTitleChars;
531 return $wgLegalTitleChars;
535 * Returns a simple regex that will match on characters and sequences invalid in titles.
536 * Note that this doesn't pick up many things that could be wrong with titles, but that
537 * replacing this regex with something valid will make many titles valid.
539 * @todo: move this into MediaWikiTitleCodec
541 * @return String regex string
543 static function getTitleInvalidRegex() {
544 static $rxTc = false;
545 if ( !$rxTc ) {
546 # Matching titles will be held as illegal.
547 $rxTc = '/' .
548 # Any character not allowed is forbidden...
549 '[^' . self::legalChars() . ']' .
550 # URL percent encoding sequences interfere with the ability
551 # to round-trip titles -- you can't link to them consistently.
552 '|%[0-9A-Fa-f]{2}' .
553 # XML/HTML character references produce similar issues.
554 '|&[A-Za-z0-9\x80-\xff]+;' .
555 '|&#[0-9]+;' .
556 '|&#x[0-9A-Fa-f]+;' .
557 '/S';
560 return $rxTc;
564 * Utility method for converting a character sequence from bytes to Unicode.
566 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
567 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
569 * @param string $byteClass
570 * @return string
572 public static function convertByteClassToUnicodeClass( $byteClass ) {
573 $length = strlen( $byteClass );
574 // Input token queue
575 $x0 = $x1 = $x2 = '';
576 // Decoded queue
577 $d0 = $d1 = $d2 = '';
578 // Decoded integer codepoints
579 $ord0 = $ord1 = $ord2 = 0;
580 // Re-encoded queue
581 $r0 = $r1 = $r2 = '';
582 // Output
583 $out = '';
584 // Flags
585 $allowUnicode = false;
586 for ( $pos = 0; $pos < $length; $pos++ ) {
587 // Shift the queues down
588 $x2 = $x1;
589 $x1 = $x0;
590 $d2 = $d1;
591 $d1 = $d0;
592 $ord2 = $ord1;
593 $ord1 = $ord0;
594 $r2 = $r1;
595 $r1 = $r0;
596 // Load the current input token and decoded values
597 $inChar = $byteClass[$pos];
598 if ( $inChar == '\\' ) {
599 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
600 $x0 = $inChar . $m[0];
601 $d0 = chr( hexdec( $m[1] ) );
602 $pos += strlen( $m[0] );
603 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
604 $x0 = $inChar . $m[0];
605 $d0 = chr( octdec( $m[0] ) );
606 $pos += strlen( $m[0] );
607 } elseif ( $pos + 1 >= $length ) {
608 $x0 = $d0 = '\\';
609 } else {
610 $d0 = $byteClass[$pos + 1];
611 $x0 = $inChar . $d0;
612 $pos += 1;
614 } else {
615 $x0 = $d0 = $inChar;
617 $ord0 = ord( $d0 );
618 // Load the current re-encoded value
619 if ( $ord0 < 32 || $ord0 == 0x7f ) {
620 $r0 = sprintf( '\x%02x', $ord0 );
621 } elseif ( $ord0 >= 0x80 ) {
622 // Allow unicode if a single high-bit character appears
623 $r0 = sprintf( '\x%02x', $ord0 );
624 $allowUnicode = true;
625 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
626 $r0 = '\\' . $d0;
627 } else {
628 $r0 = $d0;
630 // Do the output
631 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
632 // Range
633 if ( $ord2 > $ord0 ) {
634 // Empty range
635 } elseif ( $ord0 >= 0x80 ) {
636 // Unicode range
637 $allowUnicode = true;
638 if ( $ord2 < 0x80 ) {
639 // Keep the non-unicode section of the range
640 $out .= "$r2-\\x7F";
642 } else {
643 // Normal range
644 $out .= "$r2-$r0";
646 // Reset state to the initial value
647 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
648 } elseif ( $ord2 < 0x80 ) {
649 // ASCII character
650 $out .= $r2;
653 if ( $ord1 < 0x80 ) {
654 $out .= $r1;
656 if ( $ord0 < 0x80 ) {
657 $out .= $r0;
659 if ( $allowUnicode ) {
660 $out .= '\u0080-\uFFFF';
662 return $out;
666 * Get a string representation of a title suitable for
667 * including in a search index
669 * @param int $ns a namespace index
670 * @param string $title text-form main part
671 * @return String a stripped-down title string ready for the search index
673 public static function indexTitle( $ns, $title ) {
674 global $wgContLang;
676 $lc = SearchEngine::legalSearchChars() . '&#;';
677 $t = $wgContLang->normalizeForSearch( $title );
678 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
679 $t = $wgContLang->lc( $t );
681 # Handle 's, s'
682 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
683 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
685 $t = preg_replace( "/\\s+/", ' ', $t );
687 if ( $ns == NS_FILE ) {
688 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
690 return trim( $t );
694 * Make a prefixed DB key from a DB key and a namespace index
696 * @param int $ns numerical representation of the namespace
697 * @param string $title the DB key form the title
698 * @param string $fragment The link fragment (after the "#")
699 * @param string $interwiki The interwiki prefix
700 * @return String the prefixed form of the title
702 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
703 global $wgContLang;
705 $namespace = $wgContLang->getNsText( $ns );
706 $name = $namespace == '' ? $title : "$namespace:$title";
707 if ( strval( $interwiki ) != '' ) {
708 $name = "$interwiki:$name";
710 if ( strval( $fragment ) != '' ) {
711 $name .= '#' . $fragment;
713 return $name;
717 * Escape a text fragment, say from a link, for a URL
719 * @param string $fragment containing a URL or link fragment (after the "#")
720 * @return String: escaped string
722 static function escapeFragmentForURL( $fragment ) {
723 # Note that we don't urlencode the fragment. urlencoded Unicode
724 # fragments appear not to work in IE (at least up to 7) or in at least
725 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
726 # to care if they aren't encoded.
727 return Sanitizer::escapeId( $fragment, 'noninitial' );
731 * Callback for usort() to do title sorts by (namespace, title)
733 * @param $a Title
734 * @param $b Title
736 * @return Integer: result of string comparison, or namespace comparison
738 public static function compare( $a, $b ) {
739 if ( $a->getNamespace() == $b->getNamespace() ) {
740 return strcmp( $a->getText(), $b->getText() );
741 } else {
742 return $a->getNamespace() - $b->getNamespace();
747 * Determine whether the object refers to a page within
748 * this project.
750 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
752 public function isLocal() {
753 if ( $this->isExternal() ) {
754 $iw = Interwiki::fetch( $this->mInterwiki );
755 if ( $iw ) {
756 return $iw->isLocal();
759 return true;
763 * Is this Title interwiki?
765 * @return Bool
767 public function isExternal() {
768 return $this->mInterwiki !== '';
772 * Get the interwiki prefix
774 * Use Title::isExternal to check if a interwiki is set
776 * @return String Interwiki prefix
778 public function getInterwiki() {
779 return $this->mInterwiki;
783 * Determine whether the object refers to a page within
784 * this project and is transcludable.
786 * @return Bool TRUE if this is transcludable
788 public function isTrans() {
789 if ( !$this->isExternal() ) {
790 return false;
793 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
797 * Returns the DB name of the distant wiki which owns the object.
799 * @return String the DB name
801 public function getTransWikiID() {
802 if ( !$this->isExternal() ) {
803 return false;
806 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
810 * Get a TitleValue object representing this Title.
812 * @note: Not all valid Titles have a corresponding valid TitleValue
813 * (e.g. TitleValues cannot represent page-local links that have a
814 * fragment but no title text).
816 * @return TitleValue|null
818 public function getTitleValue() {
819 if ( $this->mTitleValue === null ) {
820 try {
821 $this->mTitleValue = new TitleValue(
822 $this->getNamespace(),
823 $this->getDBkey(),
824 $this->getFragment() );
825 } catch ( InvalidArgumentException $ex ) {
826 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
827 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
831 return $this->mTitleValue;
835 * Get the text form (spaces not underscores) of the main part
837 * @return String Main part of the title
839 public function getText() {
840 return $this->mTextform;
844 * Get the URL-encoded form of the main part
846 * @return String Main part of the title, URL-encoded
848 public function getPartialURL() {
849 return $this->mUrlform;
853 * Get the main part with underscores
855 * @return String: Main part of the title, with underscores
857 public function getDBkey() {
858 return $this->mDbkeyform;
862 * Get the DB key with the initial letter case as specified by the user
864 * @return String DB key
866 function getUserCaseDBKey() {
867 if ( !is_null( $this->mUserCaseDBKey ) ) {
868 return $this->mUserCaseDBKey;
869 } else {
870 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
871 return $this->mDbkeyform;
876 * Get the namespace index, i.e. one of the NS_xxxx constants.
878 * @return Integer: Namespace index
880 public function getNamespace() {
881 return $this->mNamespace;
885 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
887 * @throws MWException
888 * @return String: Content model id
890 public function getContentModel() {
891 if ( !$this->mContentModel ) {
892 $linkCache = LinkCache::singleton();
893 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
896 if ( !$this->mContentModel ) {
897 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
900 if ( !$this->mContentModel ) {
901 throw new MWException( 'Failed to determine content model!' );
904 return $this->mContentModel;
908 * Convenience method for checking a title's content model name
910 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
911 * @return Boolean true if $this->getContentModel() == $id
913 public function hasContentModel( $id ) {
914 return $this->getContentModel() == $id;
918 * Get the namespace text
920 * @return String: Namespace text
922 public function getNsText() {
923 if ( $this->isExternal() ) {
924 // This probably shouldn't even happen. ohh man, oh yuck.
925 // But for interwiki transclusion it sometimes does.
926 // Shit. Shit shit shit.
928 // Use the canonical namespaces if possible to try to
929 // resolve a foreign namespace.
930 if ( MWNamespace::exists( $this->mNamespace ) ) {
931 return MWNamespace::getCanonicalName( $this->mNamespace );
935 try {
936 $formatter = $this->getTitleFormatter();
937 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
938 } catch ( InvalidArgumentException $ex ) {
939 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
940 return false;
945 * Get the namespace text of the subject (rather than talk) page
947 * @return String Namespace text
949 public function getSubjectNsText() {
950 global $wgContLang;
951 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
955 * Get the namespace text of the talk page
957 * @return String Namespace text
959 public function getTalkNsText() {
960 global $wgContLang;
961 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
965 * Could this title have a corresponding talk page?
967 * @return Bool TRUE or FALSE
969 public function canTalk() {
970 return MWNamespace::canTalk( $this->mNamespace );
974 * Is this in a namespace that allows actual pages?
976 * @return Bool
977 * @internal note -- uses hardcoded namespace index instead of constants
979 public function canExist() {
980 return $this->mNamespace >= NS_MAIN;
984 * Can this title be added to a user's watchlist?
986 * @return Bool TRUE or FALSE
988 public function isWatchable() {
989 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
993 * Returns true if this is a special page.
995 * @return boolean
997 public function isSpecialPage() {
998 return $this->getNamespace() == NS_SPECIAL;
1002 * Returns true if this title resolves to the named special page
1004 * @param string $name The special page name
1005 * @return boolean
1007 public function isSpecial( $name ) {
1008 if ( $this->isSpecialPage() ) {
1009 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1010 if ( $name == $thisName ) {
1011 return true;
1014 return false;
1018 * If the Title refers to a special page alias which is not the local default, resolve
1019 * the alias, and localise the name as necessary. Otherwise, return $this
1021 * @return Title
1023 public function fixSpecialName() {
1024 if ( $this->isSpecialPage() ) {
1025 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1026 if ( $canonicalName ) {
1027 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1028 if ( $localName != $this->mDbkeyform ) {
1029 return Title::makeTitle( NS_SPECIAL, $localName );
1033 return $this;
1037 * Returns true if the title is inside the specified namespace.
1039 * Please make use of this instead of comparing to getNamespace()
1040 * This function is much more resistant to changes we may make
1041 * to namespaces than code that makes direct comparisons.
1042 * @param int $ns The namespace
1043 * @return bool
1044 * @since 1.19
1046 public function inNamespace( $ns ) {
1047 return MWNamespace::equals( $this->getNamespace(), $ns );
1051 * Returns true if the title is inside one of the specified namespaces.
1053 * @param ...$namespaces The namespaces to check for
1054 * @return bool
1055 * @since 1.19
1057 public function inNamespaces( /* ... */ ) {
1058 $namespaces = func_get_args();
1059 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1060 $namespaces = $namespaces[0];
1063 foreach ( $namespaces as $ns ) {
1064 if ( $this->inNamespace( $ns ) ) {
1065 return true;
1069 return false;
1073 * Returns true if the title has the same subject namespace as the
1074 * namespace specified.
1075 * For example this method will take NS_USER and return true if namespace
1076 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1077 * as their subject namespace.
1079 * This is MUCH simpler than individually testing for equivalence
1080 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1081 * @since 1.19
1082 * @param $ns int
1083 * @return bool
1085 public function hasSubjectNamespace( $ns ) {
1086 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1090 * Is this Title in a namespace which contains content?
1091 * In other words, is this a content page, for the purposes of calculating
1092 * statistics, etc?
1094 * @return Boolean
1096 public function isContentPage() {
1097 return MWNamespace::isContent( $this->getNamespace() );
1101 * Would anybody with sufficient privileges be able to move this page?
1102 * Some pages just aren't movable.
1104 * @return Bool TRUE or FALSE
1106 public function isMovable() {
1107 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1108 // Interwiki title or immovable namespace. Hooks don't get to override here
1109 return false;
1112 $result = true;
1113 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1114 return $result;
1118 * Is this the mainpage?
1119 * @note Title::newFromText seems to be sufficiently optimized by the title
1120 * cache that we don't need to over-optimize by doing direct comparisons and
1121 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1122 * ends up reporting something differently than $title->isMainPage();
1124 * @since 1.18
1125 * @return Bool
1127 public function isMainPage() {
1128 return $this->equals( Title::newMainPage() );
1132 * Is this a subpage?
1134 * @return Bool
1136 public function isSubpage() {
1137 return MWNamespace::hasSubpages( $this->mNamespace )
1138 ? strpos( $this->getText(), '/' ) !== false
1139 : false;
1143 * Is this a conversion table for the LanguageConverter?
1145 * @return Bool
1147 public function isConversionTable() {
1148 // @todo ConversionTable should become a separate content model.
1150 return $this->getNamespace() == NS_MEDIAWIKI &&
1151 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1155 * Does that page contain wikitext, or it is JS, CSS or whatever?
1157 * @return Bool
1159 public function isWikitextPage() {
1160 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1164 * Could this page contain custom CSS or JavaScript for the global UI.
1165 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1166 * or CONTENT_MODEL_JAVASCRIPT.
1168 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
1170 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
1172 * @return Bool
1174 public function isCssOrJsPage() {
1175 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1176 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1177 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1179 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
1180 # hook functions can force this method to return true even outside the mediawiki namespace.
1182 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1184 return $isCssOrJsPage;
1188 * Is this a .css or .js subpage of a user page?
1189 * @return Bool
1191 public function isCssJsSubpage() {
1192 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1193 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1194 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1198 * Trim down a .css or .js subpage title to get the corresponding skin name
1200 * @return string containing skin name from .css or .js subpage title
1202 public function getSkinFromCssJsSubpage() {
1203 $subpage = explode( '/', $this->mTextform );
1204 $subpage = $subpage[count( $subpage ) - 1];
1205 $lastdot = strrpos( $subpage, '.' );
1206 if ( $lastdot === false ) {
1207 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1209 return substr( $subpage, 0, $lastdot );
1213 * Is this a .css subpage of a user page?
1215 * @return Bool
1217 public function isCssSubpage() {
1218 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1219 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1223 * Is this a .js subpage of a user page?
1225 * @return Bool
1227 public function isJsSubpage() {
1228 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1229 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1233 * Is this a talk page of some sort?
1235 * @return Bool
1237 public function isTalkPage() {
1238 return MWNamespace::isTalk( $this->getNamespace() );
1242 * Get a Title object associated with the talk page of this article
1244 * @return Title the object for the talk page
1246 public function getTalkPage() {
1247 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1251 * Get a title object associated with the subject page of this
1252 * talk page
1254 * @return Title the object for the subject page
1256 public function getSubjectPage() {
1257 // Is this the same title?
1258 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1259 if ( $this->getNamespace() == $subjectNS ) {
1260 return $this;
1262 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1266 * Get the default namespace index, for when there is no namespace
1268 * @return Int Default namespace index
1270 public function getDefaultNamespace() {
1271 return $this->mDefaultNamespace;
1275 * Get title for search index
1277 * @return String a stripped-down title string ready for the
1278 * search index
1280 public function getIndexTitle() {
1281 return Title::indexTitle( $this->mNamespace, $this->mTextform );
1285 * Get the Title fragment (i.e.\ the bit after the #) in text form
1287 * Use Title::hasFragment to check for a fragment
1289 * @return String Title fragment
1291 public function getFragment() {
1292 return $this->mFragment;
1296 * Check if a Title fragment is set
1298 * @return bool
1299 * @since 1.23
1301 public function hasFragment() {
1302 return $this->mFragment !== '';
1306 * Get the fragment in URL form, including the "#" character if there is one
1307 * @return String Fragment in URL form
1309 public function getFragmentForURL() {
1310 if ( !$this->hasFragment() ) {
1311 return '';
1312 } else {
1313 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1318 * Set the fragment for this title. Removes the first character from the
1319 * specified fragment before setting, so it assumes you're passing it with
1320 * an initial "#".
1322 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1323 * Still in active use privately.
1325 * @param string $fragment text
1327 public function setFragment( $fragment ) {
1328 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1332 * Prefix some arbitrary text with the namespace or interwiki prefix
1333 * of this object
1335 * @param string $name the text
1336 * @return String the prefixed text
1337 * @private
1339 private function prefix( $name ) {
1340 $p = '';
1341 if ( $this->isExternal() ) {
1342 $p = $this->mInterwiki . ':';
1345 if ( 0 != $this->mNamespace ) {
1346 $p .= $this->getNsText() . ':';
1348 return $p . $name;
1352 * Get the prefixed database key form
1354 * @return String the prefixed title, with underscores and
1355 * any interwiki and namespace prefixes
1357 public function getPrefixedDBkey() {
1358 $s = $this->prefix( $this->mDbkeyform );
1359 $s = str_replace( ' ', '_', $s );
1360 return $s;
1364 * Get the prefixed title with spaces.
1365 * This is the form usually used for display
1367 * @return String the prefixed title, with spaces
1369 public function getPrefixedText() {
1370 if ( $this->mPrefixedText === null ) {
1371 $s = $this->prefix( $this->mTextform );
1372 $s = str_replace( '_', ' ', $s );
1373 $this->mPrefixedText = $s;
1375 return $this->mPrefixedText;
1379 * Return a string representation of this title
1381 * @return String representation of this title
1383 public function __toString() {
1384 return $this->getPrefixedText();
1388 * Get the prefixed title with spaces, plus any fragment
1389 * (part beginning with '#')
1391 * @return String the prefixed title, with spaces and the fragment, including '#'
1393 public function getFullText() {
1394 $text = $this->getPrefixedText();
1395 if ( $this->hasFragment() ) {
1396 $text .= '#' . $this->getFragment();
1398 return $text;
1402 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1404 * @par Example:
1405 * @code
1406 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1407 * # returns: 'Foo'
1408 * @endcode
1410 * @return String Root name
1411 * @since 1.20
1413 public function getRootText() {
1414 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1415 return $this->getText();
1418 return strtok( $this->getText(), '/' );
1422 * Get the root page name title, i.e. the leftmost part before any slashes
1424 * @par Example:
1425 * @code
1426 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1427 * # returns: Title{User:Foo}
1428 * @endcode
1430 * @return Title Root title
1431 * @since 1.20
1433 public function getRootTitle() {
1434 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1438 * Get the base page name without a namespace, i.e. the part before the subpage name
1440 * @par Example:
1441 * @code
1442 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1443 * # returns: 'Foo/Bar'
1444 * @endcode
1446 * @return String Base name
1448 public function getBaseText() {
1449 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1450 return $this->getText();
1453 $parts = explode( '/', $this->getText() );
1454 # Don't discard the real title if there's no subpage involved
1455 if ( count( $parts ) > 1 ) {
1456 unset( $parts[count( $parts ) - 1] );
1458 return implode( '/', $parts );
1462 * Get the base page name title, i.e. the part before the subpage name
1464 * @par Example:
1465 * @code
1466 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1467 * # returns: Title{User:Foo/Bar}
1468 * @endcode
1470 * @return Title Base title
1471 * @since 1.20
1473 public function getBaseTitle() {
1474 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1478 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1480 * @par Example:
1481 * @code
1482 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1483 * # returns: "Baz"
1484 * @endcode
1486 * @return String Subpage name
1488 public function getSubpageText() {
1489 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1490 return $this->mTextform;
1492 $parts = explode( '/', $this->mTextform );
1493 return $parts[count( $parts ) - 1];
1497 * Get the title for a subpage of the current page
1499 * @par Example:
1500 * @code
1501 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1502 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1503 * @endcode
1505 * @param string $text The subpage name to add to the title
1506 * @return Title Subpage title
1507 * @since 1.20
1509 public function getSubpage( $text ) {
1510 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1514 * Get the HTML-escaped displayable text form.
1515 * Used for the title field in <a> tags.
1517 * @return String the text, including any prefixes
1518 * @deprecated since 1.19
1520 public function getEscapedText() {
1521 wfDeprecated( __METHOD__, '1.19' );
1522 return htmlspecialchars( $this->getPrefixedText() );
1526 * Get a URL-encoded form of the subpage text
1528 * @return String URL-encoded subpage name
1530 public function getSubpageUrlForm() {
1531 $text = $this->getSubpageText();
1532 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1533 return $text;
1537 * Get a URL-encoded title (not an actual URL) including interwiki
1539 * @return String the URL-encoded form
1541 public function getPrefixedURL() {
1542 $s = $this->prefix( $this->mDbkeyform );
1543 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1544 return $s;
1548 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1549 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1550 * second argument named variant. This was deprecated in favor
1551 * of passing an array of option with a "variant" key
1552 * Once $query2 is removed for good, this helper can be dropped
1553 * and the wfArrayToCgi moved to getLocalURL();
1555 * @since 1.19 (r105919)
1556 * @param $query
1557 * @param $query2 bool
1558 * @return String
1560 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1561 if ( $query2 !== false ) {
1562 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1563 "method called with a second parameter is deprecated. Add your " .
1564 "parameter to an array passed as the first parameter.", "1.19" );
1566 if ( is_array( $query ) ) {
1567 $query = wfArrayToCgi( $query );
1569 if ( $query2 ) {
1570 if ( is_string( $query2 ) ) {
1571 // $query2 is a string, we will consider this to be
1572 // a deprecated $variant argument and add it to the query
1573 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1574 } else {
1575 $query2 = wfArrayToCgi( $query2 );
1577 // If we have $query content add a & to it first
1578 if ( $query ) {
1579 $query .= '&';
1581 // Now append the queries together
1582 $query .= $query2;
1584 return $query;
1588 * Get a real URL referring to this title, with interwiki link and
1589 * fragment
1591 * @see self::getLocalURL for the arguments.
1592 * @see wfExpandUrl
1593 * @param $query
1594 * @param $query2 bool
1595 * @param $proto Protocol type to use in URL
1596 * @return String the URL
1598 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1599 $query = self::fixUrlQueryArgs( $query, $query2 );
1601 # Hand off all the decisions on urls to getLocalURL
1602 $url = $this->getLocalURL( $query );
1604 # Expand the url to make it a full url. Note that getLocalURL has the
1605 # potential to output full urls for a variety of reasons, so we use
1606 # wfExpandUrl instead of simply prepending $wgServer
1607 $url = wfExpandUrl( $url, $proto );
1609 # Finally, add the fragment.
1610 $url .= $this->getFragmentForURL();
1612 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1613 return $url;
1617 * Get a URL with no fragment or server name (relative URL) from a Title object.
1618 * If this page is generated with action=render, however,
1619 * $wgServer is prepended to make an absolute URL.
1621 * @see self::getFullURL to always get an absolute URL.
1622 * @see self::newFromText to produce a Title object.
1624 * @param string|array $query an optional query string,
1625 * not used for interwiki links. Can be specified as an associative array as well,
1626 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1627 * Some query patterns will trigger various shorturl path replacements.
1628 * @param $query2 Mixed: An optional secondary query array. This one MUST
1629 * be an array. If a string is passed it will be interpreted as a deprecated
1630 * variant argument and urlencoded into a variant= argument.
1631 * This second query argument will be added to the $query
1632 * The second parameter is deprecated since 1.19. Pass it as a key,value
1633 * pair in the first parameter array instead.
1635 * @return String of the URL.
1637 public function getLocalURL( $query = '', $query2 = false ) {
1638 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1640 $query = self::fixUrlQueryArgs( $query, $query2 );
1642 $interwiki = Interwiki::fetch( $this->mInterwiki );
1643 if ( $interwiki ) {
1644 $namespace = $this->getNsText();
1645 if ( $namespace != '' ) {
1646 # Can this actually happen? Interwikis shouldn't be parsed.
1647 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1648 $namespace .= ':';
1650 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1651 $url = wfAppendQuery( $url, $query );
1652 } else {
1653 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1654 if ( $query == '' ) {
1655 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1656 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1657 } else {
1658 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1659 $url = false;
1660 $matches = array();
1662 if ( !empty( $wgActionPaths )
1663 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1665 $action = urldecode( $matches[2] );
1666 if ( isset( $wgActionPaths[$action] ) ) {
1667 $query = $matches[1];
1668 if ( isset( $matches[4] ) ) {
1669 $query .= $matches[4];
1671 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1672 if ( $query != '' ) {
1673 $url = wfAppendQuery( $url, $query );
1678 if ( $url === false
1679 && $wgVariantArticlePath
1680 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1681 && $this->getPageLanguage()->hasVariants()
1682 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1684 $variant = urldecode( $matches[1] );
1685 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1686 // Only do the variant replacement if the given variant is a valid
1687 // variant for the page's language.
1688 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1689 $url = str_replace( '$1', $dbkey, $url );
1693 if ( $url === false ) {
1694 if ( $query == '-' ) {
1695 $query = '';
1697 $url = "{$wgScript}?title={$dbkey}&{$query}";
1701 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1703 // @todo FIXME: This causes breakage in various places when we
1704 // actually expected a local URL and end up with dupe prefixes.
1705 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1706 $url = $wgServer . $url;
1709 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1710 return $url;
1714 * Get a URL that's the simplest URL that will be valid to link, locally,
1715 * to the current Title. It includes the fragment, but does not include
1716 * the server unless action=render is used (or the link is external). If
1717 * there's a fragment but the prefixed text is empty, we just return a link
1718 * to the fragment.
1720 * The result obviously should not be URL-escaped, but does need to be
1721 * HTML-escaped if it's being output in HTML.
1723 * @param $query
1724 * @param $query2 bool
1725 * @param $proto Protocol to use; setting this will cause a full URL to be used
1726 * @see self::getLocalURL for the arguments.
1727 * @return String the URL
1729 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1730 wfProfileIn( __METHOD__ );
1731 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1732 $ret = $this->getFullURL( $query, $query2, $proto );
1733 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1734 $ret = $this->getFragmentForURL();
1735 } else {
1736 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1738 wfProfileOut( __METHOD__ );
1739 return $ret;
1743 * Get an HTML-escaped version of the URL form, suitable for
1744 * using in a link, without a server name or fragment
1746 * @see self::getLocalURL for the arguments.
1747 * @param $query string
1748 * @param $query2 bool|string
1749 * @return String the URL
1750 * @deprecated since 1.19
1752 public function escapeLocalURL( $query = '', $query2 = false ) {
1753 wfDeprecated( __METHOD__, '1.19' );
1754 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1758 * Get an HTML-escaped version of the URL form, suitable for
1759 * using in a link, including the server name and fragment
1761 * @see self::getLocalURL for the arguments.
1762 * @return String the URL
1763 * @deprecated since 1.19
1765 public function escapeFullURL( $query = '', $query2 = false ) {
1766 wfDeprecated( __METHOD__, '1.19' );
1767 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1771 * Get the URL form for an internal link.
1772 * - Used in various Squid-related code, in case we have a different
1773 * internal hostname for the server from the exposed one.
1775 * This uses $wgInternalServer to qualify the path, or $wgServer
1776 * if $wgInternalServer is not set. If the server variable used is
1777 * protocol-relative, the URL will be expanded to http://
1779 * @see self::getLocalURL for the arguments.
1780 * @return String the URL
1782 public function getInternalURL( $query = '', $query2 = false ) {
1783 global $wgInternalServer, $wgServer;
1784 $query = self::fixUrlQueryArgs( $query, $query2 );
1785 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1786 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1787 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1788 return $url;
1792 * Get the URL for a canonical link, for use in things like IRC and
1793 * e-mail notifications. Uses $wgCanonicalServer and the
1794 * GetCanonicalURL hook.
1796 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1798 * @see self::getLocalURL for the arguments.
1799 * @return string The URL
1800 * @since 1.18
1802 public function getCanonicalURL( $query = '', $query2 = false ) {
1803 $query = self::fixUrlQueryArgs( $query, $query2 );
1804 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1805 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1806 return $url;
1810 * HTML-escaped version of getCanonicalURL()
1812 * @see self::getLocalURL for the arguments.
1813 * @since 1.18
1814 * @return string
1815 * @deprecated since 1.19
1817 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1818 wfDeprecated( __METHOD__, '1.19' );
1819 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1823 * Get the edit URL for this Title
1825 * @return String the URL, or a null string if this is an
1826 * interwiki link
1828 public function getEditURL() {
1829 if ( $this->isExternal() ) {
1830 return '';
1832 $s = $this->getLocalURL( 'action=edit' );
1834 return $s;
1838 * Is $wgUser watching this page?
1840 * @deprecated in 1.20; use User::isWatched() instead.
1841 * @return Bool
1843 public function userIsWatching() {
1844 global $wgUser;
1846 if ( is_null( $this->mWatched ) ) {
1847 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1848 $this->mWatched = false;
1849 } else {
1850 $this->mWatched = $wgUser->isWatched( $this );
1853 return $this->mWatched;
1857 * Can $wgUser read this page?
1859 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1860 * @return Bool
1862 public function userCanRead() {
1863 wfDeprecated( __METHOD__, '1.19' );
1864 return $this->userCan( 'read' );
1868 * Can $user perform $action on this page?
1869 * This skips potentially expensive cascading permission checks
1870 * as well as avoids expensive error formatting
1872 * Suitable for use for nonessential UI controls in common cases, but
1873 * _not_ for functional access control.
1875 * May provide false positives, but should never provide a false negative.
1877 * @param string $action action that permission needs to be checked for
1878 * @param $user User to check (since 1.19); $wgUser will be used if not
1879 * provided.
1880 * @return Bool
1882 public function quickUserCan( $action, $user = null ) {
1883 return $this->userCan( $action, $user, false );
1887 * Can $user perform $action on this page?
1889 * @param string $action action that permission needs to be checked for
1890 * @param $user User to check (since 1.19); $wgUser will be used if not
1891 * provided.
1892 * @param bool $doExpensiveQueries Set this to false to avoid doing
1893 * unnecessary queries.
1894 * @return Bool
1896 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1897 if ( !$user instanceof User ) {
1898 global $wgUser;
1899 $user = $wgUser;
1901 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1905 * Can $user perform $action on this page?
1907 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1909 * @param string $action action that permission needs to be checked for
1910 * @param $user User to check
1911 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1912 * queries by skipping checks for cascading protections and user blocks.
1913 * @param array $ignoreErrors of Strings Set this to a list of message keys
1914 * whose corresponding errors may be ignored.
1915 * @return Array of arguments to wfMessage to explain permissions problems.
1917 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1918 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1920 // Remove the errors being ignored.
1921 foreach ( $errors as $index => $error ) {
1922 $error_key = is_array( $error ) ? $error[0] : $error;
1924 if ( in_array( $error_key, $ignoreErrors ) ) {
1925 unset( $errors[$index] );
1929 return $errors;
1933 * Permissions checks that fail most often, and which are easiest to test.
1935 * @param string $action the action to check
1936 * @param $user User user to check
1937 * @param array $errors list of current errors
1938 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1939 * @param $short Boolean short circuit on first error
1941 * @return Array list of errors
1943 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1944 if ( !wfRunHooks( 'TitleQuickPermissions', array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) ) ) {
1945 return $errors;
1948 if ( $action == 'create' ) {
1949 if (
1950 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1951 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1953 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1955 } elseif ( $action == 'move' ) {
1956 if ( !$user->isAllowed( 'move-rootuserpages' )
1957 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1958 // Show user page-specific message only if the user can move other pages
1959 $errors[] = array( 'cant-move-user-page' );
1962 // Check if user is allowed to move files if it's a file
1963 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1964 $errors[] = array( 'movenotallowedfile' );
1967 if ( !$user->isAllowed( 'move' ) ) {
1968 // User can't move anything
1969 $userCanMove = User::groupHasPermission( 'user', 'move' );
1970 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1971 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1972 // custom message if logged-in users without any special rights can move
1973 $errors[] = array( 'movenologintext' );
1974 } else {
1975 $errors[] = array( 'movenotallowed' );
1978 } elseif ( $action == 'move-target' ) {
1979 if ( !$user->isAllowed( 'move' ) ) {
1980 // User can't move anything
1981 $errors[] = array( 'movenotallowed' );
1982 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1983 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1984 // Show user page-specific message only if the user can move other pages
1985 $errors[] = array( 'cant-move-to-user-page' );
1987 } elseif ( !$user->isAllowed( $action ) ) {
1988 $errors[] = $this->missingPermissionError( $action, $short );
1991 return $errors;
1995 * Add the resulting error code to the errors array
1997 * @param array $errors list of current errors
1998 * @param $result Mixed result of errors
2000 * @return Array list of errors
2002 private function resultToError( $errors, $result ) {
2003 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2004 // A single array representing an error
2005 $errors[] = $result;
2006 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2007 // A nested array representing multiple errors
2008 $errors = array_merge( $errors, $result );
2009 } elseif ( $result !== '' && is_string( $result ) ) {
2010 // A string representing a message-id
2011 $errors[] = array( $result );
2012 } elseif ( $result === false ) {
2013 // a generic "We don't want them to do that"
2014 $errors[] = array( 'badaccess-group0' );
2016 return $errors;
2020 * Check various permission hooks
2022 * @param string $action the action to check
2023 * @param $user User user to check
2024 * @param array $errors list of current errors
2025 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2026 * @param $short Boolean short circuit on first error
2028 * @return Array list of errors
2030 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2031 // Use getUserPermissionsErrors instead
2032 $result = '';
2033 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2034 return $result ? array() : array( array( 'badaccess-group0' ) );
2036 // Check getUserPermissionsErrors hook
2037 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2038 $errors = $this->resultToError( $errors, $result );
2040 // Check getUserPermissionsErrorsExpensive hook
2041 if (
2042 $doExpensiveQueries
2043 && !( $short && count( $errors ) > 0 )
2044 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2046 $errors = $this->resultToError( $errors, $result );
2049 return $errors;
2053 * Check permissions on special pages & namespaces
2055 * @param string $action the action to check
2056 * @param $user User user to check
2057 * @param array $errors list of current errors
2058 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2059 * @param $short Boolean short circuit on first error
2061 * @return Array list of errors
2063 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2064 # Only 'createaccount' can be performed on special pages,
2065 # which don't actually exist in the DB.
2066 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2067 $errors[] = array( 'ns-specialprotected' );
2070 # Check $wgNamespaceProtection for restricted namespaces
2071 if ( $this->isNamespaceProtected( $user ) ) {
2072 $ns = $this->mNamespace == NS_MAIN ?
2073 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2074 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2075 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
2078 return $errors;
2082 * Check CSS/JS sub-page permissions
2084 * @param string $action the action to check
2085 * @param $user User user to check
2086 * @param array $errors list of current errors
2087 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2088 * @param $short Boolean short circuit on first error
2090 * @return Array list of errors
2092 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2093 # Protect css/js subpages of user pages
2094 # XXX: this might be better using restrictions
2095 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2096 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2097 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2098 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2099 $errors[] = array( 'mycustomcssprotected' );
2100 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2101 $errors[] = array( 'mycustomjsprotected' );
2103 } else {
2104 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2105 $errors[] = array( 'customcssprotected' );
2106 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2107 $errors[] = array( 'customjsprotected' );
2112 return $errors;
2116 * Check against page_restrictions table requirements on this
2117 * page. The user must possess all required rights for this
2118 * action.
2120 * @param string $action the action to check
2121 * @param $user User user to check
2122 * @param array $errors list of current errors
2123 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2124 * @param $short Boolean short circuit on first error
2126 * @return Array list of errors
2128 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2129 foreach ( $this->getRestrictions( $action ) as $right ) {
2130 // Backwards compatibility, rewrite sysop -> editprotected
2131 if ( $right == 'sysop' ) {
2132 $right = 'editprotected';
2134 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2135 if ( $right == 'autoconfirmed' ) {
2136 $right = 'editsemiprotected';
2138 if ( $right == '' ) {
2139 continue;
2141 if ( !$user->isAllowed( $right ) ) {
2142 $errors[] = array( 'protectedpagetext', $right );
2143 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2144 $errors[] = array( 'protectedpagetext', 'protect' );
2148 return $errors;
2152 * Check restrictions on cascading pages.
2154 * @param string $action the action to check
2155 * @param $user User to check
2156 * @param array $errors list of current errors
2157 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2158 * @param $short Boolean short circuit on first error
2160 * @return Array list of errors
2162 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2163 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2164 # We /could/ use the protection level on the source page, but it's
2165 # fairly ugly as we have to establish a precedence hierarchy for pages
2166 # included by multiple cascade-protected pages. So just restrict
2167 # it to people with 'protect' permission, as they could remove the
2168 # protection anyway.
2169 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2170 # Cascading protection depends on more than this page...
2171 # Several cascading protected pages may include this page...
2172 # Check each cascading level
2173 # This is only for protection restrictions, not for all actions
2174 if ( isset( $restrictions[$action] ) ) {
2175 foreach ( $restrictions[$action] as $right ) {
2176 // Backwards compatibility, rewrite sysop -> editprotected
2177 if ( $right == 'sysop' ) {
2178 $right = 'editprotected';
2180 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2181 if ( $right == 'autoconfirmed' ) {
2182 $right = 'editsemiprotected';
2184 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2185 $pages = '';
2186 foreach ( $cascadingSources as $page ) {
2187 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2189 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
2195 return $errors;
2199 * Check action permissions not already checked in checkQuickPermissions
2201 * @param string $action the action to check
2202 * @param $user User to check
2203 * @param array $errors list of current errors
2204 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2205 * @param $short Boolean short circuit on first error
2207 * @return Array list of errors
2209 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2210 global $wgDeleteRevisionsLimit, $wgLang;
2212 if ( $action == 'protect' ) {
2213 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
2214 // If they can't edit, they shouldn't protect.
2215 $errors[] = array( 'protect-cantedit' );
2217 } elseif ( $action == 'create' ) {
2218 $title_protection = $this->getTitleProtection();
2219 if ( $title_protection ) {
2220 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
2221 $title_protection['pt_create_perm'] = 'editprotected'; // B/C
2223 if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) {
2224 $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C
2226 if ( $title_protection['pt_create_perm'] == ''
2227 || !$user->isAllowed( $title_protection['pt_create_perm'] )
2229 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
2232 } elseif ( $action == 'move' ) {
2233 // Check for immobile pages
2234 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2235 // Specific message for this case
2236 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2237 } elseif ( !$this->isMovable() ) {
2238 // Less specific message for rarer cases
2239 $errors[] = array( 'immobile-source-page' );
2241 } elseif ( $action == 'move-target' ) {
2242 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2243 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2244 } elseif ( !$this->isMovable() ) {
2245 $errors[] = array( 'immobile-target-page' );
2247 } elseif ( $action == 'delete' ) {
2248 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2249 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2251 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2254 return $errors;
2258 * Check that the user isn't blocked from editing.
2260 * @param string $action the action to check
2261 * @param $user User to check
2262 * @param array $errors list of current errors
2263 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2264 * @param $short Boolean short circuit on first error
2266 * @return Array list of errors
2268 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2269 // Account creation blocks handled at userlogin.
2270 // Unblocking handled in SpecialUnblock
2271 if ( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2272 return $errors;
2275 global $wgEmailConfirmToEdit;
2277 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2278 $errors[] = array( 'confirmedittext' );
2281 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2282 // Don't block the user from editing their own talk page unless they've been
2283 // explicitly blocked from that too.
2284 } elseif ( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2285 // @todo FIXME: Pass the relevant context into this function.
2286 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2289 return $errors;
2293 * Check that the user is allowed to read this page.
2295 * @param string $action the action to check
2296 * @param $user User to check
2297 * @param array $errors list of current errors
2298 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2299 * @param $short Boolean short circuit on first error
2301 * @return Array list of errors
2303 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2304 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2306 $whitelisted = false;
2307 if ( User::isEveryoneAllowed( 'read' ) ) {
2308 # Shortcut for public wikis, allows skipping quite a bit of code
2309 $whitelisted = true;
2310 } elseif ( $user->isAllowed( 'read' ) ) {
2311 # If the user is allowed to read pages, he is allowed to read all pages
2312 $whitelisted = true;
2313 } elseif ( $this->isSpecial( 'Userlogin' )
2314 || $this->isSpecial( 'ChangePassword' )
2315 || $this->isSpecial( 'PasswordReset' )
2317 # Always grant access to the login page.
2318 # Even anons need to be able to log in.
2319 $whitelisted = true;
2320 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2321 # Time to check the whitelist
2322 # Only do these checks is there's something to check against
2323 $name = $this->getPrefixedText();
2324 $dbName = $this->getPrefixedDBkey();
2326 // Check for explicit whitelisting with and without underscores
2327 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2328 $whitelisted = true;
2329 } elseif ( $this->getNamespace() == NS_MAIN ) {
2330 # Old settings might have the title prefixed with
2331 # a colon for main-namespace pages
2332 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2333 $whitelisted = true;
2335 } elseif ( $this->isSpecialPage() ) {
2336 # If it's a special page, ditch the subpage bit and check again
2337 $name = $this->getDBkey();
2338 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2339 if ( $name ) {
2340 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2341 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2342 $whitelisted = true;
2348 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2349 $name = $this->getPrefixedText();
2350 // Check for regex whitelisting
2351 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2352 if ( preg_match( $listItem, $name ) ) {
2353 $whitelisted = true;
2354 break;
2359 if ( !$whitelisted ) {
2360 # If the title is not whitelisted, give extensions a chance to do so...
2361 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2362 if ( !$whitelisted ) {
2363 $errors[] = $this->missingPermissionError( $action, $short );
2367 return $errors;
2371 * Get a description array when the user doesn't have the right to perform
2372 * $action (i.e. when User::isAllowed() returns false)
2374 * @param string $action the action to check
2375 * @param $short Boolean short circuit on first error
2376 * @return Array list of errors
2378 private function missingPermissionError( $action, $short ) {
2379 // We avoid expensive display logic for quickUserCan's and such
2380 if ( $short ) {
2381 return array( 'badaccess-group0' );
2384 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2385 User::getGroupsWithPermission( $action ) );
2387 if ( count( $groups ) ) {
2388 global $wgLang;
2389 return array(
2390 'badaccess-groups',
2391 $wgLang->commaList( $groups ),
2392 count( $groups )
2394 } else {
2395 return array( 'badaccess-group0' );
2400 * Can $user perform $action on this page? This is an internal function,
2401 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2402 * checks on wfReadOnly() and blocks)
2404 * @param string $action action that permission needs to be checked for
2405 * @param $user User to check
2406 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2407 * @param bool $short Set this to true to stop after the first permission error.
2408 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2410 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2411 wfProfileIn( __METHOD__ );
2413 # Read has special handling
2414 if ( $action == 'read' ) {
2415 $checks = array(
2416 'checkPermissionHooks',
2417 'checkReadPermissions',
2419 } else {
2420 $checks = array(
2421 'checkQuickPermissions',
2422 'checkPermissionHooks',
2423 'checkSpecialsAndNSPermissions',
2424 'checkCSSandJSPermissions',
2425 'checkPageRestrictions',
2426 'checkCascadingSourcesRestrictions',
2427 'checkActionPermissions',
2428 'checkUserBlock'
2432 $errors = array();
2433 while ( count( $checks ) > 0 &&
2434 !( $short && count( $errors ) > 0 ) ) {
2435 $method = array_shift( $checks );
2436 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2439 wfProfileOut( __METHOD__ );
2440 return $errors;
2444 * Get a filtered list of all restriction types supported by this wiki.
2445 * @param bool $exists True to get all restriction types that apply to
2446 * titles that do exist, False for all restriction types that apply to
2447 * titles that do not exist
2448 * @return array
2450 public static function getFilteredRestrictionTypes( $exists = true ) {
2451 global $wgRestrictionTypes;
2452 $types = $wgRestrictionTypes;
2453 if ( $exists ) {
2454 # Remove the create restriction for existing titles
2455 $types = array_diff( $types, array( 'create' ) );
2456 } else {
2457 # Only the create and upload restrictions apply to non-existing titles
2458 $types = array_intersect( $types, array( 'create', 'upload' ) );
2460 return $types;
2464 * Returns restriction types for the current Title
2466 * @return array applicable restriction types
2468 public function getRestrictionTypes() {
2469 if ( $this->isSpecialPage() ) {
2470 return array();
2473 $types = self::getFilteredRestrictionTypes( $this->exists() );
2475 if ( $this->getNamespace() != NS_FILE ) {
2476 # Remove the upload restriction for non-file titles
2477 $types = array_diff( $types, array( 'upload' ) );
2480 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2482 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2483 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2485 return $types;
2489 * Is this title subject to title protection?
2490 * Title protection is the one applied against creation of such title.
2492 * @return Mixed An associative array representing any existent title
2493 * protection, or false if there's none.
2495 private function getTitleProtection() {
2496 // Can't protect pages in special namespaces
2497 if ( $this->getNamespace() < 0 ) {
2498 return false;
2501 // Can't protect pages that exist.
2502 if ( $this->exists() ) {
2503 return false;
2506 if ( !isset( $this->mTitleProtection ) ) {
2507 $dbr = wfGetDB( DB_SLAVE );
2508 $res = $dbr->select(
2509 'protected_titles',
2510 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2511 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2512 __METHOD__
2515 // fetchRow returns false if there are no rows.
2516 $this->mTitleProtection = $dbr->fetchRow( $res );
2518 return $this->mTitleProtection;
2522 * Update the title protection status
2524 * @deprecated in 1.19; use WikiPage::doUpdateRestrictions() instead.
2525 * @param $create_perm String Permission required for creation
2526 * @param string $reason Reason for protection
2527 * @param string $expiry Expiry timestamp
2528 * @return boolean true
2530 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2531 wfDeprecated( __METHOD__, '1.19' );
2533 global $wgUser;
2535 $limit = array( 'create' => $create_perm );
2536 $expiry = array( 'create' => $expiry );
2538 $page = WikiPage::factory( $this );
2539 $cascade = false;
2540 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2542 return $status->isOK();
2546 * Remove any title protection due to page existing
2548 public function deleteTitleProtection() {
2549 $dbw = wfGetDB( DB_MASTER );
2551 $dbw->delete(
2552 'protected_titles',
2553 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2554 __METHOD__
2556 $this->mTitleProtection = false;
2560 * Is this page "semi-protected" - the *only* protection levels are listed
2561 * in $wgSemiprotectedRestrictionLevels?
2563 * @param string $action Action to check (default: edit)
2564 * @return Bool
2566 public function isSemiProtected( $action = 'edit' ) {
2567 global $wgSemiprotectedRestrictionLevels;
2569 $restrictions = $this->getRestrictions( $action );
2570 $semi = $wgSemiprotectedRestrictionLevels;
2571 if ( !$restrictions || !$semi ) {
2572 // Not protected, or all protection is full protection
2573 return false;
2576 // Remap autoconfirmed to editsemiprotected for BC
2577 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2578 $semi[$key] = 'editsemiprotected';
2580 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2581 $restrictions[$key] = 'editsemiprotected';
2584 return !array_diff( $restrictions, $semi );
2588 * Does the title correspond to a protected article?
2590 * @param string $action the action the page is protected from,
2591 * by default checks all actions.
2592 * @return Bool
2594 public function isProtected( $action = '' ) {
2595 global $wgRestrictionLevels;
2597 $restrictionTypes = $this->getRestrictionTypes();
2599 # Special pages have inherent protection
2600 if ( $this->isSpecialPage() ) {
2601 return true;
2604 # Check regular protection levels
2605 foreach ( $restrictionTypes as $type ) {
2606 if ( $action == $type || $action == '' ) {
2607 $r = $this->getRestrictions( $type );
2608 foreach ( $wgRestrictionLevels as $level ) {
2609 if ( in_array( $level, $r ) && $level != '' ) {
2610 return true;
2616 return false;
2620 * Determines if $user is unable to edit this page because it has been protected
2621 * by $wgNamespaceProtection.
2623 * @param $user User object to check permissions
2624 * @return Bool
2626 public function isNamespaceProtected( User $user ) {
2627 global $wgNamespaceProtection;
2629 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2630 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2631 if ( $right != '' && !$user->isAllowed( $right ) ) {
2632 return true;
2636 return false;
2640 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2642 * @return Bool If the page is subject to cascading restrictions.
2644 public function isCascadeProtected() {
2645 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2646 return ( $sources > 0 );
2650 * Determines whether cascading protection sources have already been loaded from
2651 * the database.
2653 * @param bool $getPages True to check if the pages are loaded, or false to check
2654 * if the status is loaded.
2655 * @return bool Whether or not the specified information has been loaded
2656 * @since 1.23
2658 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2659 return $getPages ? isset( $this->mCascadeSources ) : isset( $this->mHasCascadingRestrictions );
2663 * Cascading protection: Get the source of any cascading restrictions on this page.
2665 * @param bool $getPages Whether or not to retrieve the actual pages
2666 * that the restrictions have come from.
2667 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2668 * have come, false for none, or true if such restrictions exist, but $getPages
2669 * was not set. The restriction array is an array of each type, each of which
2670 * contains a array of unique groups.
2672 public function getCascadeProtectionSources( $getPages = true ) {
2673 global $wgContLang;
2674 $pagerestrictions = array();
2676 if ( isset( $this->mCascadeSources ) && $getPages ) {
2677 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2678 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2679 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2682 wfProfileIn( __METHOD__ );
2684 $dbr = wfGetDB( DB_SLAVE );
2686 if ( $this->getNamespace() == NS_FILE ) {
2687 $tables = array( 'imagelinks', 'page_restrictions' );
2688 $where_clauses = array(
2689 'il_to' => $this->getDBkey(),
2690 'il_from=pr_page',
2691 'pr_cascade' => 1
2693 } else {
2694 $tables = array( 'templatelinks', 'page_restrictions' );
2695 $where_clauses = array(
2696 'tl_namespace' => $this->getNamespace(),
2697 'tl_title' => $this->getDBkey(),
2698 'tl_from=pr_page',
2699 'pr_cascade' => 1
2703 if ( $getPages ) {
2704 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2705 'pr_expiry', 'pr_type', 'pr_level' );
2706 $where_clauses[] = 'page_id=pr_page';
2707 $tables[] = 'page';
2708 } else {
2709 $cols = array( 'pr_expiry' );
2712 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2714 $sources = $getPages ? array() : false;
2715 $now = wfTimestampNow();
2716 $purgeExpired = false;
2718 foreach ( $res as $row ) {
2719 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2720 if ( $expiry > $now ) {
2721 if ( $getPages ) {
2722 $page_id = $row->pr_page;
2723 $page_ns = $row->page_namespace;
2724 $page_title = $row->page_title;
2725 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2726 # Add groups needed for each restriction type if its not already there
2727 # Make sure this restriction type still exists
2729 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2730 $pagerestrictions[$row->pr_type] = array();
2733 if (
2734 isset( $pagerestrictions[$row->pr_type] )
2735 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2737 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2739 } else {
2740 $sources = true;
2742 } else {
2743 // Trigger lazy purge of expired restrictions from the db
2744 $purgeExpired = true;
2747 if ( $purgeExpired ) {
2748 Title::purgeExpiredRestrictions();
2751 if ( $getPages ) {
2752 $this->mCascadeSources = $sources;
2753 $this->mCascadingRestrictions = $pagerestrictions;
2754 } else {
2755 $this->mHasCascadingRestrictions = $sources;
2758 wfProfileOut( __METHOD__ );
2759 return array( $sources, $pagerestrictions );
2763 * Accessor for mRestrictionsLoaded
2765 * @return bool Whether or not the page's restrictions have already been
2766 * loaded from the database
2767 * @since 1.23
2769 public function areRestrictionsLoaded() {
2770 return $this->mRestrictionsLoaded;
2774 * Accessor/initialisation for mRestrictions
2776 * @param string $action action that permission needs to be checked for
2777 * @return Array of Strings the array of groups allowed to edit this article
2779 public function getRestrictions( $action ) {
2780 if ( !$this->mRestrictionsLoaded ) {
2781 $this->loadRestrictions();
2783 return isset( $this->mRestrictions[$action] )
2784 ? $this->mRestrictions[$action]
2785 : array();
2789 * Accessor/initialisation for mRestrictions
2791 * @return Array of Arrays of Strings the first level indexed by
2792 * action, the second level containing the names of the groups
2793 * allowed to perform each action
2794 * @since 1.23
2796 public function getAllRestrictions() {
2797 if ( !$this->mRestrictionsLoaded ) {
2798 $this->loadRestrictions();
2800 return $this->mRestrictions;
2804 * Get the expiry time for the restriction against a given action
2806 * @param $action
2807 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2808 * or not protected at all, or false if the action is not recognised.
2810 public function getRestrictionExpiry( $action ) {
2811 if ( !$this->mRestrictionsLoaded ) {
2812 $this->loadRestrictions();
2814 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2818 * Returns cascading restrictions for the current article
2820 * @return Boolean
2822 function areRestrictionsCascading() {
2823 if ( !$this->mRestrictionsLoaded ) {
2824 $this->loadRestrictions();
2827 return $this->mCascadeRestriction;
2831 * Loads a string into mRestrictions array
2833 * @param $res Resource restrictions as an SQL result.
2834 * @param string $oldFashionedRestrictions comma-separated list of page
2835 * restrictions from page table (pre 1.10)
2837 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2838 $rows = array();
2840 foreach ( $res as $row ) {
2841 $rows[] = $row;
2844 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2848 * Compiles list of active page restrictions from both page table (pre 1.10)
2849 * and page_restrictions table for this existing page.
2850 * Public for usage by LiquidThreads.
2852 * @param array $rows of db result objects
2853 * @param string $oldFashionedRestrictions comma-separated list of page
2854 * restrictions from page table (pre 1.10)
2856 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2857 global $wgContLang;
2858 $dbr = wfGetDB( DB_SLAVE );
2860 $restrictionTypes = $this->getRestrictionTypes();
2862 foreach ( $restrictionTypes as $type ) {
2863 $this->mRestrictions[$type] = array();
2864 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2867 $this->mCascadeRestriction = false;
2869 # Backwards-compatibility: also load the restrictions from the page record (old format).
2871 if ( $oldFashionedRestrictions === null ) {
2872 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2873 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2876 if ( $oldFashionedRestrictions != '' ) {
2878 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2879 $temp = explode( '=', trim( $restrict ) );
2880 if ( count( $temp ) == 1 ) {
2881 // old old format should be treated as edit/move restriction
2882 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2883 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2884 } else {
2885 $restriction = trim( $temp[1] );
2886 if ( $restriction != '' ) { //some old entries are empty
2887 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2892 $this->mOldRestrictions = true;
2896 if ( count( $rows ) ) {
2897 # Current system - load second to make them override.
2898 $now = wfTimestampNow();
2899 $purgeExpired = false;
2901 # Cycle through all the restrictions.
2902 foreach ( $rows as $row ) {
2904 // Don't take care of restrictions types that aren't allowed
2905 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2906 continue;
2909 // This code should be refactored, now that it's being used more generally,
2910 // But I don't really see any harm in leaving it in Block for now -werdna
2911 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2913 // Only apply the restrictions if they haven't expired!
2914 if ( !$expiry || $expiry > $now ) {
2915 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2916 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2918 $this->mCascadeRestriction |= $row->pr_cascade;
2919 } else {
2920 // Trigger a lazy purge of expired restrictions
2921 $purgeExpired = true;
2925 if ( $purgeExpired ) {
2926 Title::purgeExpiredRestrictions();
2930 $this->mRestrictionsLoaded = true;
2934 * Load restrictions from the page_restrictions table
2936 * @param string $oldFashionedRestrictions comma-separated list of page
2937 * restrictions from page table (pre 1.10)
2939 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2940 global $wgContLang;
2941 if ( !$this->mRestrictionsLoaded ) {
2942 if ( $this->exists() ) {
2943 $dbr = wfGetDB( DB_SLAVE );
2945 $res = $dbr->select(
2946 'page_restrictions',
2947 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2948 array( 'pr_page' => $this->getArticleID() ),
2949 __METHOD__
2952 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2953 } else {
2954 $title_protection = $this->getTitleProtection();
2956 if ( $title_protection ) {
2957 $now = wfTimestampNow();
2958 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2960 if ( !$expiry || $expiry > $now ) {
2961 // Apply the restrictions
2962 $this->mRestrictionsExpiry['create'] = $expiry;
2963 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2964 } else { // Get rid of the old restrictions
2965 Title::purgeExpiredRestrictions();
2966 $this->mTitleProtection = false;
2968 } else {
2969 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2971 $this->mRestrictionsLoaded = true;
2977 * Flush the protection cache in this object and force reload from the database.
2978 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2980 public function flushRestrictions() {
2981 $this->mRestrictionsLoaded = false;
2982 $this->mTitleProtection = null;
2986 * Purge expired restrictions from the page_restrictions table
2988 static function purgeExpiredRestrictions() {
2989 if ( wfReadOnly() ) {
2990 return;
2993 $method = __METHOD__;
2994 $dbw = wfGetDB( DB_MASTER );
2995 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
2996 $dbw->delete(
2997 'page_restrictions',
2998 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2999 $method
3001 $dbw->delete(
3002 'protected_titles',
3003 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3004 $method
3006 } );
3010 * Does this have subpages? (Warning, usually requires an extra DB query.)
3012 * @return Bool
3014 public function hasSubpages() {
3015 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3016 # Duh
3017 return false;
3020 # We dynamically add a member variable for the purpose of this method
3021 # alone to cache the result. There's no point in having it hanging
3022 # around uninitialized in every Title object; therefore we only add it
3023 # if needed and don't declare it statically.
3024 if ( !isset( $this->mHasSubpages ) ) {
3025 $this->mHasSubpages = false;
3026 $subpages = $this->getSubpages( 1 );
3027 if ( $subpages instanceof TitleArray ) {
3028 $this->mHasSubpages = (bool)$subpages->count();
3032 return $this->mHasSubpages;
3036 * Get all subpages of this page.
3038 * @param int $limit maximum number of subpages to fetch; -1 for no limit
3039 * @return mixed TitleArray, or empty array if this page's namespace
3040 * doesn't allow subpages
3042 public function getSubpages( $limit = -1 ) {
3043 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3044 return array();
3047 $dbr = wfGetDB( DB_SLAVE );
3048 $conds['page_namespace'] = $this->getNamespace();
3049 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3050 $options = array();
3051 if ( $limit > -1 ) {
3052 $options['LIMIT'] = $limit;
3054 $this->mSubpages = TitleArray::newFromResult(
3055 $dbr->select( 'page',
3056 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3057 $conds,
3058 __METHOD__,
3059 $options
3062 return $this->mSubpages;
3066 * Is there a version of this page in the deletion archive?
3068 * @return Int the number of archived revisions
3070 public function isDeleted() {
3071 if ( $this->getNamespace() < 0 ) {
3072 $n = 0;
3073 } else {
3074 $dbr = wfGetDB( DB_SLAVE );
3076 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3077 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3078 __METHOD__
3080 if ( $this->getNamespace() == NS_FILE ) {
3081 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3082 array( 'fa_name' => $this->getDBkey() ),
3083 __METHOD__
3087 return (int)$n;
3091 * Is there a version of this page in the deletion archive?
3093 * @return Boolean
3095 public function isDeletedQuick() {
3096 if ( $this->getNamespace() < 0 ) {
3097 return false;
3099 $dbr = wfGetDB( DB_SLAVE );
3100 $deleted = (bool)$dbr->selectField( 'archive', '1',
3101 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3102 __METHOD__
3104 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3105 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3106 array( 'fa_name' => $this->getDBkey() ),
3107 __METHOD__
3110 return $deleted;
3114 * Get the article ID for this Title from the link cache,
3115 * adding it if necessary
3117 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select
3118 * for update
3119 * @return Int the ID
3121 public function getArticleID( $flags = 0 ) {
3122 if ( $this->getNamespace() < 0 ) {
3123 $this->mArticleID = 0;
3124 return $this->mArticleID;
3126 $linkCache = LinkCache::singleton();
3127 if ( $flags & self::GAID_FOR_UPDATE ) {
3128 $oldUpdate = $linkCache->forUpdate( true );
3129 $linkCache->clearLink( $this );
3130 $this->mArticleID = $linkCache->addLinkObj( $this );
3131 $linkCache->forUpdate( $oldUpdate );
3132 } else {
3133 if ( -1 == $this->mArticleID ) {
3134 $this->mArticleID = $linkCache->addLinkObj( $this );
3137 return $this->mArticleID;
3141 * Is this an article that is a redirect page?
3142 * Uses link cache, adding it if necessary
3144 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3145 * @return Bool
3147 public function isRedirect( $flags = 0 ) {
3148 if ( !is_null( $this->mRedirect ) ) {
3149 return $this->mRedirect;
3151 # Calling getArticleID() loads the field from cache as needed
3152 if ( !$this->getArticleID( $flags ) ) {
3153 $this->mRedirect = false;
3154 return $this->mRedirect;
3157 $linkCache = LinkCache::singleton();
3158 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3159 if ( $cached === null ) {
3160 # Trust LinkCache's state over our own
3161 # LinkCache is telling us that the page doesn't exist, despite there being cached
3162 # data relating to an existing page in $this->mArticleID. Updaters should clear
3163 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3164 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3165 # LinkCache to refresh its data from the master.
3166 $this->mRedirect = false;
3167 return $this->mRedirect;
3170 $this->mRedirect = (bool)$cached;
3172 return $this->mRedirect;
3176 * What is the length of this page?
3177 * Uses link cache, adding it if necessary
3179 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3180 * @return Int
3182 public function getLength( $flags = 0 ) {
3183 if ( $this->mLength != -1 ) {
3184 return $this->mLength;
3186 # Calling getArticleID() loads the field from cache as needed
3187 if ( !$this->getArticleID( $flags ) ) {
3188 $this->mLength = 0;
3189 return $this->mLength;
3191 $linkCache = LinkCache::singleton();
3192 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3193 if ( $cached === null ) {
3194 # Trust LinkCache's state over our own, as for isRedirect()
3195 $this->mLength = 0;
3196 return $this->mLength;
3199 $this->mLength = intval( $cached );
3201 return $this->mLength;
3205 * What is the page_latest field for this page?
3207 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3208 * @return Int or 0 if the page doesn't exist
3210 public function getLatestRevID( $flags = 0 ) {
3211 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3212 return intval( $this->mLatestID );
3214 # Calling getArticleID() loads the field from cache as needed
3215 if ( !$this->getArticleID( $flags ) ) {
3216 $this->mLatestID = 0;
3217 return $this->mLatestID;
3219 $linkCache = LinkCache::singleton();
3220 $linkCache->addLinkObj( $this );
3221 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3222 if ( $cached === null ) {
3223 # Trust LinkCache's state over our own, as for isRedirect()
3224 $this->mLatestID = 0;
3225 return $this->mLatestID;
3228 $this->mLatestID = intval( $cached );
3230 return $this->mLatestID;
3234 * This clears some fields in this object, and clears any associated
3235 * keys in the "bad links" section of the link cache.
3237 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3238 * loading of the new page_id. It's also called from
3239 * WikiPage::doDeleteArticleReal()
3241 * @param int $newid the new Article ID
3243 public function resetArticleID( $newid ) {
3244 $linkCache = LinkCache::singleton();
3245 $linkCache->clearLink( $this );
3247 if ( $newid === false ) {
3248 $this->mArticleID = -1;
3249 } else {
3250 $this->mArticleID = intval( $newid );
3252 $this->mRestrictionsLoaded = false;
3253 $this->mRestrictions = array();
3254 $this->mRedirect = null;
3255 $this->mLength = -1;
3256 $this->mLatestID = false;
3257 $this->mContentModel = false;
3258 $this->mEstimateRevisions = null;
3259 $this->mPageLanguage = false;
3263 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3265 * @param string $text containing title to capitalize
3266 * @param int $ns namespace index, defaults to NS_MAIN
3267 * @return String containing capitalized title
3269 public static function capitalize( $text, $ns = NS_MAIN ) {
3270 global $wgContLang;
3272 if ( MWNamespace::isCapitalized( $ns ) ) {
3273 return $wgContLang->ucfirst( $text );
3274 } else {
3275 return $text;
3280 * Secure and split - main initialisation function for this object
3282 * Assumes that mDbkeyform has been set, and is urldecoded
3283 * and uses underscores, but not otherwise munged. This function
3284 * removes illegal characters, splits off the interwiki and
3285 * namespace prefixes, sets the other forms, and canonicalizes
3286 * everything.
3288 * @return Bool true on success
3290 private function secureAndSplit() {
3291 # Initialisation
3292 $this->mInterwiki = '';
3293 $this->mFragment = '';
3294 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3296 $dbkey = $this->mDbkeyform;
3298 try {
3299 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3300 // the parsing code with Title, while avoiding massive refactoring.
3301 // @todo: get rid of secureAndSplit, refactor parsing code.
3302 $parser = $this->getTitleParser();
3303 $parts = $parser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3304 } catch ( MalformedTitleException $ex ) {
3305 return false;
3308 # Fill fields
3309 $this->setFragment( '#' . $parts['fragment'] );
3310 $this->mInterwiki = $parts['interwiki'];
3311 $this->mNamespace = $parts['namespace'];
3312 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3314 $this->mDbkeyform = $parts['dbkey'];
3315 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3316 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3318 # We already know that some pages won't be in the database!
3319 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3320 $this->mArticleID = 0;
3323 return true;
3327 * Get an array of Title objects linking to this Title
3328 * Also stores the IDs in the link cache.
3330 * WARNING: do not use this function on arbitrary user-supplied titles!
3331 * On heavily-used templates it will max out the memory.
3333 * @param array $options may be FOR UPDATE
3334 * @param string $table table name
3335 * @param string $prefix fields prefix
3336 * @return Array of Title objects linking here
3338 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3339 if ( count( $options ) > 0 ) {
3340 $db = wfGetDB( DB_MASTER );
3341 } else {
3342 $db = wfGetDB( DB_SLAVE );
3345 $res = $db->select(
3346 array( 'page', $table ),
3347 self::getSelectFields(),
3348 array(
3349 "{$prefix}_from=page_id",
3350 "{$prefix}_namespace" => $this->getNamespace(),
3351 "{$prefix}_title" => $this->getDBkey() ),
3352 __METHOD__,
3353 $options
3356 $retVal = array();
3357 if ( $res->numRows() ) {
3358 $linkCache = LinkCache::singleton();
3359 foreach ( $res as $row ) {
3360 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3361 if ( $titleObj ) {
3362 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3363 $retVal[] = $titleObj;
3367 return $retVal;
3371 * Get an array of Title objects using this Title as a template
3372 * Also stores the IDs in the link cache.
3374 * WARNING: do not use this function on arbitrary user-supplied titles!
3375 * On heavily-used templates it will max out the memory.
3377 * @param array $options may be FOR UPDATE
3378 * @return Array of Title the Title objects linking here
3380 public function getTemplateLinksTo( $options = array() ) {
3381 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3385 * Get an array of Title objects linked from this Title
3386 * Also stores the IDs in the link cache.
3388 * WARNING: do not use this function on arbitrary user-supplied titles!
3389 * On heavily-used templates it will max out the memory.
3391 * @param array $options may be FOR UPDATE
3392 * @param string $table table name
3393 * @param string $prefix fields prefix
3394 * @return Array of Title objects linking here
3396 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3397 global $wgContentHandlerUseDB;
3399 $id = $this->getArticleID();
3401 # If the page doesn't exist; there can't be any link from this page
3402 if ( !$id ) {
3403 return array();
3406 if ( count( $options ) > 0 ) {
3407 $db = wfGetDB( DB_MASTER );
3408 } else {
3409 $db = wfGetDB( DB_SLAVE );
3412 $namespaceFiled = "{$prefix}_namespace";
3413 $titleField = "{$prefix}_title";
3415 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3416 if ( $wgContentHandlerUseDB ) {
3417 $fields[] = 'page_content_model';
3420 $res = $db->select(
3421 array( $table, 'page' ),
3422 $fields,
3423 array( "{$prefix}_from" => $id ),
3424 __METHOD__,
3425 $options,
3426 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3429 $retVal = array();
3430 if ( $res->numRows() ) {
3431 $linkCache = LinkCache::singleton();
3432 foreach ( $res as $row ) {
3433 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3434 if ( $titleObj ) {
3435 if ( $row->page_id ) {
3436 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3437 } else {
3438 $linkCache->addBadLinkObj( $titleObj );
3440 $retVal[] = $titleObj;
3444 return $retVal;
3448 * Get an array of Title objects used on this Title as a template
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 * @return Array of Title the Title objects used here
3457 public function getTemplateLinksFrom( $options = array() ) {
3458 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3462 * Get an array of Title objects referring to non-existent articles linked from this page
3464 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3465 * @return Array of Title the Title objects
3467 public function getBrokenLinksFrom() {
3468 if ( $this->getArticleID() == 0 ) {
3469 # All links from article ID 0 are false positives
3470 return array();
3473 $dbr = wfGetDB( DB_SLAVE );
3474 $res = $dbr->select(
3475 array( 'page', 'pagelinks' ),
3476 array( 'pl_namespace', 'pl_title' ),
3477 array(
3478 'pl_from' => $this->getArticleID(),
3479 'page_namespace IS NULL'
3481 __METHOD__, array(),
3482 array(
3483 'page' => array(
3484 'LEFT JOIN',
3485 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3490 $retVal = array();
3491 foreach ( $res as $row ) {
3492 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3494 return $retVal;
3498 * Get a list of URLs to purge from the Squid cache when this
3499 * page changes
3501 * @return Array of String the URLs
3503 public function getSquidURLs() {
3504 $urls = array(
3505 $this->getInternalURL(),
3506 $this->getInternalURL( 'action=history' )
3509 $pageLang = $this->getPageLanguage();
3510 if ( $pageLang->hasVariants() ) {
3511 $variants = $pageLang->getVariants();
3512 foreach ( $variants as $vCode ) {
3513 $urls[] = $this->getInternalURL( '', $vCode );
3517 // If we are looking at a css/js user subpage, purge the action=raw.
3518 if ( $this->isJsSubpage() ) {
3519 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3520 } elseif ( $this->isCssSubpage() ) {
3521 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3524 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3525 return $urls;
3529 * Purge all applicable Squid URLs
3531 public function purgeSquid() {
3532 global $wgUseSquid;
3533 if ( $wgUseSquid ) {
3534 $urls = $this->getSquidURLs();
3535 $u = new SquidUpdate( $urls );
3536 $u->doUpdate();
3541 * Move this page without authentication
3543 * @param $nt Title the new page Title
3544 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3546 public function moveNoAuth( &$nt ) {
3547 return $this->moveTo( $nt, false );
3551 * Check whether a given move operation would be valid.
3552 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3554 * @param $nt Title the new title
3555 * @param bool $auth indicates whether $wgUser's permissions
3556 * should be checked
3557 * @param string $reason is the log summary of the move, used for spam checking
3558 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3560 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3561 global $wgUser, $wgContentHandlerUseDB;
3563 $errors = array();
3564 if ( !$nt ) {
3565 // Normally we'd add this to $errors, but we'll get
3566 // lots of syntax errors if $nt is not an object
3567 return array( array( 'badtitletext' ) );
3569 if ( $this->equals( $nt ) ) {
3570 $errors[] = array( 'selfmove' );
3572 if ( !$this->isMovable() ) {
3573 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3575 if ( $nt->isExternal() ) {
3576 $errors[] = array( 'immobile-target-namespace-iw' );
3578 if ( !$nt->isMovable() ) {
3579 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3582 $oldid = $this->getArticleID();
3583 $newid = $nt->getArticleID();
3585 if ( strlen( $nt->getDBkey() ) < 1 ) {
3586 $errors[] = array( 'articleexists' );
3588 if (
3589 ( $this->getDBkey() == '' ) ||
3590 ( !$oldid ) ||
3591 ( $nt->getDBkey() == '' )
3593 $errors[] = array( 'badarticleerror' );
3596 // Content model checks
3597 if ( !$wgContentHandlerUseDB &&
3598 $this->getContentModel() !== $nt->getContentModel() ) {
3599 // can't move a page if that would change the page's content model
3600 $errors[] = array(
3601 'bad-target-model',
3602 ContentHandler::getLocalizedName( $this->getContentModel() ),
3603 ContentHandler::getLocalizedName( $nt->getContentModel() )
3607 // Image-specific checks
3608 if ( $this->getNamespace() == NS_FILE ) {
3609 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3612 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3613 $errors[] = array( 'nonfile-cannot-move-to-file' );
3616 if ( $auth ) {
3617 $errors = wfMergeErrorArrays( $errors,
3618 $this->getUserPermissionsErrors( 'move', $wgUser ),
3619 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3620 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3621 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3624 $match = EditPage::matchSummarySpamRegex( $reason );
3625 if ( $match !== false ) {
3626 // This is kind of lame, won't display nice
3627 $errors[] = array( 'spamprotectiontext' );
3630 $err = null;
3631 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3632 $errors[] = array( 'hookaborted', $err );
3635 # The move is allowed only if (1) the target doesn't exist, or
3636 # (2) the target is a redirect to the source, and has no history
3637 # (so we can undo bad moves right after they're done).
3639 if ( 0 != $newid ) { # Target exists; check for validity
3640 if ( !$this->isValidMoveTarget( $nt ) ) {
3641 $errors[] = array( 'articleexists' );
3643 } else {
3644 $tp = $nt->getTitleProtection();
3645 $right = $tp['pt_create_perm'];
3646 if ( $right == 'sysop' ) {
3647 $right = 'editprotected'; // B/C
3649 if ( $right == 'autoconfirmed' ) {
3650 $right = 'editsemiprotected'; // B/C
3652 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3653 $errors[] = array( 'cantmove-titleprotected' );
3656 if ( empty( $errors ) ) {
3657 return true;
3659 return $errors;
3663 * Check if the requested move target is a valid file move target
3664 * @param Title $nt Target title
3665 * @return array List of errors
3667 protected function validateFileMoveOperation( $nt ) {
3668 global $wgUser;
3670 $errors = array();
3672 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3674 $file = wfLocalFile( $this );
3675 if ( $file->exists() ) {
3676 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3677 $errors[] = array( 'imageinvalidfilename' );
3679 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3680 $errors[] = array( 'imagetypemismatch' );
3684 if ( $nt->getNamespace() != NS_FILE ) {
3685 $errors[] = array( 'imagenocrossnamespace' );
3686 // From here we want to do checks on a file object, so if we can't
3687 // create one, we must return.
3688 return $errors;
3691 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3693 $destFile = wfLocalFile( $nt );
3694 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3695 $errors[] = array( 'file-exists-sharedrepo' );
3698 return $errors;
3702 * Move a title to a new location
3704 * @param $nt Title the new title
3705 * @param bool $auth indicates whether $wgUser's permissions
3706 * should be checked
3707 * @param string $reason the reason for the move
3708 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3709 * Ignored if the user doesn't have the suppressredirect right.
3710 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3712 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3713 global $wgUser;
3714 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3715 if ( is_array( $err ) ) {
3716 // Auto-block user's IP if the account was "hard" blocked
3717 $wgUser->spreadAnyEditBlock();
3718 return $err;
3720 // Check suppressredirect permission
3721 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3722 $createRedirect = true;
3725 wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) );
3727 // If it is a file, move it first.
3728 // It is done before all other moving stuff is done because it's hard to revert.
3729 $dbw = wfGetDB( DB_MASTER );
3730 if ( $this->getNamespace() == NS_FILE ) {
3731 $file = wfLocalFile( $this );
3732 if ( $file->exists() ) {
3733 $status = $file->move( $nt );
3734 if ( !$status->isOk() ) {
3735 return $status->getErrorsArray();
3738 // Clear RepoGroup process cache
3739 RepoGroup::singleton()->clearCache( $this );
3740 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3743 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3744 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3745 $protected = $this->isProtected();
3747 // Do the actual move
3748 $this->moveToInternal( $nt, $reason, $createRedirect );
3750 // Refresh the sortkey for this row. Be careful to avoid resetting
3751 // cl_timestamp, which may disturb time-based lists on some sites.
3752 $prefixes = $dbw->select(
3753 'categorylinks',
3754 array( 'cl_sortkey_prefix', 'cl_to' ),
3755 array( 'cl_from' => $pageid ),
3756 __METHOD__
3758 foreach ( $prefixes as $prefixRow ) {
3759 $prefix = $prefixRow->cl_sortkey_prefix;
3760 $catTo = $prefixRow->cl_to;
3761 $dbw->update( 'categorylinks',
3762 array(
3763 'cl_sortkey' => Collation::singleton()->getSortKey(
3764 $nt->getCategorySortkey( $prefix ) ),
3765 'cl_timestamp=cl_timestamp' ),
3766 array(
3767 'cl_from' => $pageid,
3768 'cl_to' => $catTo ),
3769 __METHOD__
3773 $redirid = $this->getArticleID();
3775 if ( $protected ) {
3776 # Protect the redirect title as the title used to be...
3777 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3778 array(
3779 'pr_page' => $redirid,
3780 'pr_type' => 'pr_type',
3781 'pr_level' => 'pr_level',
3782 'pr_cascade' => 'pr_cascade',
3783 'pr_user' => 'pr_user',
3784 'pr_expiry' => 'pr_expiry'
3786 array( 'pr_page' => $pageid ),
3787 __METHOD__,
3788 array( 'IGNORE' )
3790 # Update the protection log
3791 $log = new LogPage( 'protect' );
3792 $comment = wfMessage(
3793 'prot_1movedto2',
3794 $this->getPrefixedText(),
3795 $nt->getPrefixedText()
3796 )->inContentLanguage()->text();
3797 if ( $reason ) {
3798 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3800 // @todo FIXME: $params?
3801 $logId = $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ), $wgUser );
3803 // reread inserted pr_ids for log relation
3804 $insertedPrIds = $dbw->select(
3805 'page_restrictions',
3806 'pr_id',
3807 array( 'pr_page' => $redirid ),
3808 __METHOD__
3810 $logRelationsValues = array();
3811 foreach ( $insertedPrIds as $prid ) {
3812 $logRelationsValues[] = $prid->pr_id;
3814 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
3817 # Update watchlists
3818 $oldnamespace = MWNamespace::getSubject( $this->getNamespace() );
3819 $newnamespace = MWNamespace::getSubject( $nt->getNamespace() );
3820 $oldtitle = $this->getDBkey();
3821 $newtitle = $nt->getDBkey();
3823 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3824 WatchedItem::duplicateEntries( $this, $nt );
3827 $dbw->commit( __METHOD__ );
3829 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid, $reason ) );
3830 return true;
3834 * Move page to a title which is either a redirect to the
3835 * source page or nonexistent
3837 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3838 * @param string $reason The reason for the move
3839 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3840 * if the user has the suppressredirect right
3841 * @throws MWException
3843 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3844 global $wgUser, $wgContLang;
3846 if ( $nt->exists() ) {
3847 $moveOverRedirect = true;
3848 $logType = 'move_redir';
3849 } else {
3850 $moveOverRedirect = false;
3851 $logType = 'move';
3854 if ( $createRedirect ) {
3855 $contentHandler = ContentHandler::getForTitle( $this );
3856 $redirectContent = $contentHandler->makeRedirectContent( $nt,
3857 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
3859 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3860 } else {
3861 $redirectContent = null;
3864 $logEntry = new ManualLogEntry( 'move', $logType );
3865 $logEntry->setPerformer( $wgUser );
3866 $logEntry->setTarget( $this );
3867 $logEntry->setComment( $reason );
3868 $logEntry->setParameters( array(
3869 '4::target' => $nt->getPrefixedText(),
3870 '5::noredir' => $redirectContent ? '0': '1',
3871 ) );
3873 $formatter = LogFormatter::newFromEntry( $logEntry );
3874 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3875 $comment = $formatter->getPlainActionText();
3876 if ( $reason ) {
3877 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3879 # Truncate for whole multibyte characters.
3880 $comment = $wgContLang->truncate( $comment, 255 );
3882 $oldid = $this->getArticleID();
3884 $dbw = wfGetDB( DB_MASTER );
3886 $newpage = WikiPage::factory( $nt );
3888 if ( $moveOverRedirect ) {
3889 $newid = $nt->getArticleID();
3890 $newcontent = $newpage->getContent();
3892 # Delete the old redirect. We don't save it to history since
3893 # by definition if we've got here it's rather uninteresting.
3894 # We have to remove it so that the next step doesn't trigger
3895 # a conflict on the unique namespace+title index...
3896 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3898 $newpage->doDeleteUpdates( $newid, $newcontent );
3901 # Save a null revision in the page's history notifying of the move
3902 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3903 if ( !is_object( $nullRevision ) ) {
3904 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3907 $nullRevision->insertOn( $dbw );
3909 # Change the name of the target page:
3910 $dbw->update( 'page',
3911 /* SET */ array(
3912 'page_namespace' => $nt->getNamespace(),
3913 'page_title' => $nt->getDBkey(),
3915 /* WHERE */ array( 'page_id' => $oldid ),
3916 __METHOD__
3919 // clean up the old title before reset article id - bug 45348
3920 if ( !$redirectContent ) {
3921 WikiPage::onArticleDelete( $this );
3924 $this->resetArticleID( 0 ); // 0 == non existing
3925 $nt->resetArticleID( $oldid );
3926 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
3928 $newpage->updateRevisionOn( $dbw, $nullRevision );
3930 wfRunHooks( 'NewRevisionFromEditComplete',
3931 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3933 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3935 if ( !$moveOverRedirect ) {
3936 WikiPage::onArticleCreate( $nt );
3939 # Recreate the redirect, this time in the other direction.
3940 if ( $redirectContent ) {
3941 $redirectArticle = WikiPage::factory( $this );
3942 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
3943 $newid = $redirectArticle->insertOn( $dbw );
3944 if ( $newid ) { // sanity
3945 $this->resetArticleID( $newid );
3946 $redirectRevision = new Revision( array(
3947 'title' => $this, // for determining the default content model
3948 'page' => $newid,
3949 'comment' => $comment,
3950 'content' => $redirectContent ) );
3951 $redirectRevision->insertOn( $dbw );
3952 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3954 wfRunHooks( 'NewRevisionFromEditComplete',
3955 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3957 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3961 # Log the move
3962 $logid = $logEntry->insert();
3963 $logEntry->publish( $logid );
3967 * Move this page's subpages to be subpages of $nt
3969 * @param $nt Title Move target
3970 * @param bool $auth Whether $wgUser's permissions should be checked
3971 * @param string $reason The reason for the move
3972 * @param bool $createRedirect Whether to create redirects from the old subpages to
3973 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3974 * @return mixed array with old page titles as keys, and strings (new page titles) or
3975 * arrays (errors) as values, or an error array with numeric indices if no pages
3976 * were moved
3978 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3979 global $wgMaximumMovedPages;
3980 // Check permissions
3981 if ( !$this->userCan( 'move-subpages' ) ) {
3982 return array( 'cant-move-subpages' );
3984 // Do the source and target namespaces support subpages?
3985 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3986 return array( 'namespace-nosubpages',
3987 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3989 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3990 return array( 'namespace-nosubpages',
3991 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3994 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3995 $retval = array();
3996 $count = 0;
3997 foreach ( $subpages as $oldSubpage ) {
3998 $count++;
3999 if ( $count > $wgMaximumMovedPages ) {
4000 $retval[$oldSubpage->getPrefixedText()] =
4001 array( 'movepage-max-pages',
4002 $wgMaximumMovedPages );
4003 break;
4006 // We don't know whether this function was called before
4007 // or after moving the root page, so check both
4008 // $this and $nt
4009 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4010 || $oldSubpage->getArticleID() == $nt->getArticleID()
4012 // When moving a page to a subpage of itself,
4013 // don't move it twice
4014 continue;
4016 $newPageName = preg_replace(
4017 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4018 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
4019 $oldSubpage->getDBkey() );
4020 if ( $oldSubpage->isTalkPage() ) {
4021 $newNs = $nt->getTalkPage()->getNamespace();
4022 } else {
4023 $newNs = $nt->getSubjectPage()->getNamespace();
4025 # Bug 14385: we need makeTitleSafe because the new page names may
4026 # be longer than 255 characters.
4027 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
4029 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
4030 if ( $success === true ) {
4031 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4032 } else {
4033 $retval[$oldSubpage->getPrefixedText()] = $success;
4036 return $retval;
4040 * Checks if this page is just a one-rev redirect.
4041 * Adds lock, so don't use just for light purposes.
4043 * @return Bool
4045 public function isSingleRevRedirect() {
4046 global $wgContentHandlerUseDB;
4048 $dbw = wfGetDB( DB_MASTER );
4050 # Is it a redirect?
4051 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
4052 if ( $wgContentHandlerUseDB ) {
4053 $fields[] = 'page_content_model';
4056 $row = $dbw->selectRow( 'page',
4057 $fields,
4058 $this->pageCond(),
4059 __METHOD__,
4060 array( 'FOR UPDATE' )
4062 # Cache some fields we may want
4063 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4064 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4065 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4066 $this->mContentModel = $row && isset( $row->page_content_model ) ? strval( $row->page_content_model ) : false;
4067 if ( !$this->mRedirect ) {
4068 return false;
4070 # Does the article have a history?
4071 $row = $dbw->selectField( array( 'page', 'revision' ),
4072 'rev_id',
4073 array( 'page_namespace' => $this->getNamespace(),
4074 'page_title' => $this->getDBkey(),
4075 'page_id=rev_page',
4076 'page_latest != rev_id'
4078 __METHOD__,
4079 array( 'FOR UPDATE' )
4081 # Return true if there was no history
4082 return ( $row === false );
4086 * Checks if $this can be moved to a given Title
4087 * - Selects for update, so don't call it unless you mean business
4089 * @param $nt Title the new title to check
4090 * @return Bool
4092 public function isValidMoveTarget( $nt ) {
4093 # Is it an existing file?
4094 if ( $nt->getNamespace() == NS_FILE ) {
4095 $file = wfLocalFile( $nt );
4096 if ( $file->exists() ) {
4097 wfDebug( __METHOD__ . ": file exists\n" );
4098 return false;
4101 # Is it a redirect with no history?
4102 if ( !$nt->isSingleRevRedirect() ) {
4103 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4104 return false;
4106 # Get the article text
4107 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4108 if ( !is_object( $rev ) ) {
4109 return false;
4111 $content = $rev->getContent();
4112 # Does the redirect point to the source?
4113 # Or is it a broken self-redirect, usually caused by namespace collisions?
4114 $redirTitle = $content ? $content->getRedirectTarget() : null;
4116 if ( $redirTitle ) {
4117 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4118 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4119 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4120 return false;
4121 } else {
4122 return true;
4124 } else {
4125 # Fail safe (not a redirect after all. strange.)
4126 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4127 " is a redirect, but it doesn't contain a valid redirect.\n" );
4128 return false;
4133 * Get categories to which this Title belongs and return an array of
4134 * categories' names.
4136 * @return Array of parents in the form:
4137 * $parent => $currentarticle
4139 public function getParentCategories() {
4140 global $wgContLang;
4142 $data = array();
4144 $titleKey = $this->getArticleID();
4146 if ( $titleKey === 0 ) {
4147 return $data;
4150 $dbr = wfGetDB( DB_SLAVE );
4152 $res = $dbr->select(
4153 'categorylinks',
4154 'cl_to',
4155 array( 'cl_from' => $titleKey ),
4156 __METHOD__
4159 if ( $res->numRows() > 0 ) {
4160 foreach ( $res as $row ) {
4161 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4162 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
4165 return $data;
4169 * Get a tree of parent categories
4171 * @param array $children with the children in the keys, to check for circular refs
4172 * @return Array Tree of parent categories
4174 public function getParentCategoryTree( $children = array() ) {
4175 $stack = array();
4176 $parents = $this->getParentCategories();
4178 if ( $parents ) {
4179 foreach ( $parents as $parent => $current ) {
4180 if ( array_key_exists( $parent, $children ) ) {
4181 # Circular reference
4182 $stack[$parent] = array();
4183 } else {
4184 $nt = Title::newFromText( $parent );
4185 if ( $nt ) {
4186 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
4192 return $stack;
4196 * Get an associative array for selecting this title from
4197 * the "page" table
4199 * @return Array suitable for the $where parameter of DB::select()
4201 public function pageCond() {
4202 if ( $this->mArticleID > 0 ) {
4203 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4204 return array( 'page_id' => $this->mArticleID );
4205 } else {
4206 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
4211 * Get the revision ID of the previous revision
4213 * @param int $revId Revision ID. Get the revision that was before this one.
4214 * @param int $flags Title::GAID_FOR_UPDATE
4215 * @return Int|Bool Old revision ID, or FALSE if none exists
4217 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4218 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4219 $revId = $db->selectField( 'revision', 'rev_id',
4220 array(
4221 'rev_page' => $this->getArticleID( $flags ),
4222 'rev_id < ' . intval( $revId )
4224 __METHOD__,
4225 array( 'ORDER BY' => 'rev_id DESC' )
4228 if ( $revId === false ) {
4229 return false;
4230 } else {
4231 return intval( $revId );
4236 * Get the revision ID of the next revision
4238 * @param int $revId Revision ID. Get the revision that was after this one.
4239 * @param int $flags Title::GAID_FOR_UPDATE
4240 * @return Int|Bool Next revision ID, or FALSE if none exists
4242 public function getNextRevisionID( $revId, $flags = 0 ) {
4243 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4244 $revId = $db->selectField( 'revision', 'rev_id',
4245 array(
4246 'rev_page' => $this->getArticleID( $flags ),
4247 'rev_id > ' . intval( $revId )
4249 __METHOD__,
4250 array( 'ORDER BY' => 'rev_id' )
4253 if ( $revId === false ) {
4254 return false;
4255 } else {
4256 return intval( $revId );
4261 * Get the first revision of the page
4263 * @param int $flags Title::GAID_FOR_UPDATE
4264 * @return Revision|Null if page doesn't exist
4266 public function getFirstRevision( $flags = 0 ) {
4267 $pageId = $this->getArticleID( $flags );
4268 if ( $pageId ) {
4269 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4270 $row = $db->selectRow( 'revision', Revision::selectFields(),
4271 array( 'rev_page' => $pageId ),
4272 __METHOD__,
4273 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4275 if ( $row ) {
4276 return new Revision( $row );
4279 return null;
4283 * Get the oldest revision timestamp of this page
4285 * @param int $flags Title::GAID_FOR_UPDATE
4286 * @return String: MW timestamp
4288 public function getEarliestRevTime( $flags = 0 ) {
4289 $rev = $this->getFirstRevision( $flags );
4290 return $rev ? $rev->getTimestamp() : null;
4294 * Check if this is a new page
4296 * @return bool
4298 public function isNewPage() {
4299 $dbr = wfGetDB( DB_SLAVE );
4300 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4304 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4306 * @return bool
4308 public function isBigDeletion() {
4309 global $wgDeleteRevisionsLimit;
4311 if ( !$wgDeleteRevisionsLimit ) {
4312 return false;
4315 $revCount = $this->estimateRevisionCount();
4316 return $revCount > $wgDeleteRevisionsLimit;
4320 * Get the approximate revision count of this page.
4322 * @return int
4324 public function estimateRevisionCount() {
4325 if ( !$this->exists() ) {
4326 return 0;
4329 if ( $this->mEstimateRevisions === null ) {
4330 $dbr = wfGetDB( DB_SLAVE );
4331 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4332 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4335 return $this->mEstimateRevisions;
4339 * Get the number of revisions between the given revision.
4340 * Used for diffs and other things that really need it.
4342 * @param int|Revision $old Old revision or rev ID (first before range)
4343 * @param int|Revision $new New revision or rev ID (first after range)
4344 * @return Int Number of revisions between these revisions.
4346 public function countRevisionsBetween( $old, $new ) {
4347 if ( !( $old instanceof Revision ) ) {
4348 $old = Revision::newFromTitle( $this, (int)$old );
4350 if ( !( $new instanceof Revision ) ) {
4351 $new = Revision::newFromTitle( $this, (int)$new );
4353 if ( !$old || !$new ) {
4354 return 0; // nothing to compare
4356 $dbr = wfGetDB( DB_SLAVE );
4357 return (int)$dbr->selectField( 'revision', 'count(*)',
4358 array(
4359 'rev_page' => $this->getArticleID(),
4360 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4361 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4363 __METHOD__
4368 * Get the authors between the given revisions or revision IDs.
4369 * Used for diffs and other things that really need it.
4371 * @since 1.23
4373 * @param int|Revision $old Old revision or rev ID (first before range by default)
4374 * @param int|Revision $new New revision or rev ID (first after range by default)
4375 * @param int $limit Maximum number of authors
4376 * @param string|array $options (Optional): Single option, or an array of options:
4377 * 'include_old' Include $old in the range; $new is excluded.
4378 * 'include_new' Include $new in the range; $old is excluded.
4379 * 'include_both' Include both $old and $new in the range.
4380 * Unknown option values are ignored.
4381 * @return array|null Names of revision authors in the range; null if not both revisions exist
4383 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4384 if ( !( $old instanceof Revision ) ) {
4385 $old = Revision::newFromTitle( $this, (int)$old );
4387 if ( !( $new instanceof Revision ) ) {
4388 $new = Revision::newFromTitle( $this, (int)$new );
4390 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4391 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4392 // in the sanity check below?
4393 if ( !$old || !$new ) {
4394 return null; // nothing to compare
4396 $authors = array();
4397 $old_cmp = '>';
4398 $new_cmp = '<';
4399 $options = (array)$options;
4400 if ( in_array( 'include_old', $options ) ) {
4401 $old_cmp = '>=';
4403 if ( in_array( 'include_new', $options ) ) {
4404 $new_cmp = '<=';
4406 if ( in_array( 'include_both', $options ) ) {
4407 $old_cmp = '>=';
4408 $new_cmp = '<=';
4410 // No DB query needed if $old and $new are the same or successive revisions:
4411 if ( $old->getId() === $new->getId() ) {
4412 return ( $old_cmp === '>' && $new_cmp === '<' ) ? array() : array( $old->getRawUserText() );
4413 } elseif ( $old->getId() === $new->getParentId() ) {
4414 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4415 $authors[] = $old->getRawUserText();
4416 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4417 $authors[] = $new->getRawUserText();
4419 } elseif ( $old_cmp === '>=' ) {
4420 $authors[] = $old->getRawUserText();
4421 } elseif ( $new_cmp === '<=' ) {
4422 $authors[] = $new->getRawUserText();
4424 return $authors;
4426 $dbr = wfGetDB( DB_SLAVE );
4427 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4428 array(
4429 'rev_page' => $this->getArticleID(),
4430 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4431 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4432 ), __METHOD__,
4433 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4435 foreach ( $res as $row ) {
4436 $authors[] = $row->rev_user_text;
4438 return $authors;
4442 * Get the number of authors between the given revisions or revision IDs.
4443 * Used for diffs and other things that really need it.
4445 * @param int|Revision $old Old revision or rev ID (first before range by default)
4446 * @param int|Revision $new New revision or rev ID (first after range by default)
4447 * @param int $limit Maximum number of authors
4448 * @param string|array $options (Optional): Single option, or an array of options:
4449 * 'include_old' Include $old in the range; $new is excluded.
4450 * 'include_new' Include $new in the range; $old is excluded.
4451 * 'include_both' Include both $old and $new in the range.
4452 * Unknown option values are ignored.
4453 * @return int Number of revision authors in the range; zero if not both revisions exist
4455 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4456 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4457 return $authors ? count( $authors ) : 0;
4461 * Compare with another title.
4463 * @param $title Title
4464 * @return Bool
4466 public function equals( Title $title ) {
4467 // Note: === is necessary for proper matching of number-like titles.
4468 return $this->getInterwiki() === $title->getInterwiki()
4469 && $this->getNamespace() == $title->getNamespace()
4470 && $this->getDBkey() === $title->getDBkey();
4474 * Check if this title is a subpage of another title
4476 * @param $title Title
4477 * @return Bool
4479 public function isSubpageOf( Title $title ) {
4480 return $this->getInterwiki() === $title->getInterwiki()
4481 && $this->getNamespace() == $title->getNamespace()
4482 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4486 * Check if page exists. For historical reasons, this function simply
4487 * checks for the existence of the title in the page table, and will
4488 * thus return false for interwiki links, special pages and the like.
4489 * If you want to know if a title can be meaningfully viewed, you should
4490 * probably call the isKnown() method instead.
4492 * @return Bool
4494 public function exists() {
4495 return $this->getArticleID() != 0;
4499 * Should links to this title be shown as potentially viewable (i.e. as
4500 * "bluelinks"), even if there's no record by this title in the page
4501 * table?
4503 * This function is semi-deprecated for public use, as well as somewhat
4504 * misleadingly named. You probably just want to call isKnown(), which
4505 * calls this function internally.
4507 * (ISSUE: Most of these checks are cheap, but the file existence check
4508 * can potentially be quite expensive. Including it here fixes a lot of
4509 * existing code, but we might want to add an optional parameter to skip
4510 * it and any other expensive checks.)
4512 * @return Bool
4514 public function isAlwaysKnown() {
4515 $isKnown = null;
4518 * Allows overriding default behavior for determining if a page exists.
4519 * If $isKnown is kept as null, regular checks happen. If it's
4520 * a boolean, this value is returned by the isKnown method.
4522 * @since 1.20
4524 * @param Title $title
4525 * @param boolean|null $isKnown
4527 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4529 if ( !is_null( $isKnown ) ) {
4530 return $isKnown;
4533 if ( $this->isExternal() ) {
4534 return true; // any interwiki link might be viewable, for all we know
4537 switch ( $this->mNamespace ) {
4538 case NS_MEDIA:
4539 case NS_FILE:
4540 // file exists, possibly in a foreign repo
4541 return (bool)wfFindFile( $this );
4542 case NS_SPECIAL:
4543 // valid special page
4544 return SpecialPageFactory::exists( $this->getDBkey() );
4545 case NS_MAIN:
4546 // selflink, possibly with fragment
4547 return $this->mDbkeyform == '';
4548 case NS_MEDIAWIKI:
4549 // known system message
4550 return $this->hasSourceText() !== false;
4551 default:
4552 return false;
4557 * Does this title refer to a page that can (or might) be meaningfully
4558 * viewed? In particular, this function may be used to determine if
4559 * links to the title should be rendered as "bluelinks" (as opposed to
4560 * "redlinks" to non-existent pages).
4561 * Adding something else to this function will cause inconsistency
4562 * since LinkHolderArray calls isAlwaysKnown() and does its own
4563 * page existence check.
4565 * @return Bool
4567 public function isKnown() {
4568 return $this->isAlwaysKnown() || $this->exists();
4572 * Does this page have source text?
4574 * @return Boolean
4576 public function hasSourceText() {
4577 if ( $this->exists() ) {
4578 return true;
4581 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4582 // If the page doesn't exist but is a known system message, default
4583 // message content will be displayed, same for language subpages-
4584 // Use always content language to avoid loading hundreds of languages
4585 // to get the link color.
4586 global $wgContLang;
4587 list( $name, ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4588 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4589 return $message->exists();
4592 return false;
4596 * Get the default message text or false if the message doesn't exist
4598 * @return String or false
4600 public function getDefaultMessageText() {
4601 global $wgContLang;
4603 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4604 return false;
4607 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4608 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4610 if ( $message->exists() ) {
4611 return $message->plain();
4612 } else {
4613 return false;
4618 * Updates page_touched for this page; called from LinksUpdate.php
4620 * @return Bool true if the update succeeded
4622 public function invalidateCache() {
4623 if ( wfReadOnly() ) {
4624 return false;
4627 $method = __METHOD__;
4628 $dbw = wfGetDB( DB_MASTER );
4629 $conds = $this->pageCond();
4630 $dbw->onTransactionIdle( function() use ( $dbw, $conds, $method ) {
4631 $dbw->update(
4632 'page',
4633 array( 'page_touched' => $dbw->timestamp() ),
4634 $conds,
4635 $method
4637 } );
4639 return true;
4643 * Update page_touched timestamps and send squid purge messages for
4644 * pages linking to this title. May be sent to the job queue depending
4645 * on the number of links. Typically called on create and delete.
4647 public function touchLinks() {
4648 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4649 $u->doUpdate();
4651 if ( $this->getNamespace() == NS_CATEGORY ) {
4652 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4653 $u->doUpdate();
4658 * Get the last touched timestamp
4660 * @param $db DatabaseBase: optional db
4661 * @return String last-touched timestamp
4663 public function getTouched( $db = null ) {
4664 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4665 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4666 return $touched;
4670 * Get the timestamp when this page was updated since the user last saw it.
4672 * @param $user User
4673 * @return String|Null
4675 public function getNotificationTimestamp( $user = null ) {
4676 global $wgUser, $wgShowUpdatedMarker;
4677 // Assume current user if none given
4678 if ( !$user ) {
4679 $user = $wgUser;
4681 // Check cache first
4682 $uid = $user->getId();
4683 // avoid isset here, as it'll return false for null entries
4684 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4685 return $this->mNotificationTimestamp[$uid];
4687 if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) {
4688 $this->mNotificationTimestamp[$uid] = false;
4689 return $this->mNotificationTimestamp[$uid];
4691 // Don't cache too much!
4692 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4693 $this->mNotificationTimestamp = array();
4695 $dbr = wfGetDB( DB_SLAVE );
4696 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4697 'wl_notificationtimestamp',
4698 array(
4699 'wl_user' => $user->getId(),
4700 'wl_namespace' => $this->getNamespace(),
4701 'wl_title' => $this->getDBkey(),
4703 __METHOD__
4705 return $this->mNotificationTimestamp[$uid];
4709 * Generate strings used for xml 'id' names in monobook tabs
4711 * @param string $prepend defaults to 'nstab-'
4712 * @return String XML 'id' name
4714 public function getNamespaceKey( $prepend = 'nstab-' ) {
4715 global $wgContLang;
4716 // Gets the subject namespace if this title
4717 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4718 // Checks if canonical namespace name exists for namespace
4719 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4720 // Uses canonical namespace name
4721 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4722 } else {
4723 // Uses text of namespace
4724 $namespaceKey = $this->getSubjectNsText();
4726 // Makes namespace key lowercase
4727 $namespaceKey = $wgContLang->lc( $namespaceKey );
4728 // Uses main
4729 if ( $namespaceKey == '' ) {
4730 $namespaceKey = 'main';
4732 // Changes file to image for backwards compatibility
4733 if ( $namespaceKey == 'file' ) {
4734 $namespaceKey = 'image';
4736 return $prepend . $namespaceKey;
4740 * Get all extant redirects to this Title
4742 * @param int|Null $ns Single namespace to consider; NULL to consider all namespaces
4743 * @return Title[] Array of Title redirects to this title
4745 public function getRedirectsHere( $ns = null ) {
4746 $redirs = array();
4748 $dbr = wfGetDB( DB_SLAVE );
4749 $where = array(
4750 'rd_namespace' => $this->getNamespace(),
4751 'rd_title' => $this->getDBkey(),
4752 'rd_from = page_id'
4754 if ( $this->isExternal() ) {
4755 $where['rd_interwiki'] = $this->getInterwiki();
4756 } else {
4757 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4759 if ( !is_null( $ns ) ) {
4760 $where['page_namespace'] = $ns;
4763 $res = $dbr->select(
4764 array( 'redirect', 'page' ),
4765 array( 'page_namespace', 'page_title' ),
4766 $where,
4767 __METHOD__
4770 foreach ( $res as $row ) {
4771 $redirs[] = self::newFromRow( $row );
4773 return $redirs;
4777 * Check if this Title is a valid redirect target
4779 * @return Bool
4781 public function isValidRedirectTarget() {
4782 global $wgInvalidRedirectTargets;
4784 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4785 if ( $this->isSpecial( 'Userlogout' ) ) {
4786 return false;
4789 foreach ( $wgInvalidRedirectTargets as $target ) {
4790 if ( $this->isSpecial( $target ) ) {
4791 return false;
4795 return true;
4799 * Get a backlink cache object
4801 * @return BacklinkCache
4803 public function getBacklinkCache() {
4804 return BacklinkCache::get( $this );
4808 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4810 * @return Boolean
4812 public function canUseNoindex() {
4813 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4815 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4816 ? $wgContentNamespaces
4817 : $wgExemptFromUserRobotsControl;
4819 return !in_array( $this->mNamespace, $bannedNamespaces );
4824 * Returns the raw sort key to be used for categories, with the specified
4825 * prefix. This will be fed to Collation::getSortKey() to get a
4826 * binary sortkey that can be used for actual sorting.
4828 * @param string $prefix The prefix to be used, specified using
4829 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4830 * prefix.
4831 * @return string
4833 public function getCategorySortkey( $prefix = '' ) {
4834 $unprefixed = $this->getText();
4836 // Anything that uses this hook should only depend
4837 // on the Title object passed in, and should probably
4838 // tell the users to run updateCollations.php --force
4839 // in order to re-sort existing category relations.
4840 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4841 if ( $prefix !== '' ) {
4842 # Separate with a line feed, so the unprefixed part is only used as
4843 # a tiebreaker when two pages have the exact same prefix.
4844 # In UCA, tab is the only character that can sort above LF
4845 # so we strip both of them from the original prefix.
4846 $prefix = strtr( $prefix, "\n\t", ' ' );
4847 return "$prefix\n$unprefixed";
4849 return $unprefixed;
4853 * Get the language in which the content of this page is written in
4854 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4855 * e.g. $wgLang (such as special pages, which are in the user language).
4857 * @since 1.18
4858 * @return Language
4860 public function getPageLanguage() {
4861 global $wgLang, $wgLanguageCode;
4862 wfProfileIn( __METHOD__ );
4863 if ( $this->isSpecialPage() ) {
4864 // special pages are in the user language
4865 wfProfileOut( __METHOD__ );
4866 return $wgLang;
4869 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4870 // Note that this may depend on user settings, so the cache should be only per-request.
4871 // NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4872 // Checking $wgLanguageCode hasn't changed for the benefit of unit tests.
4873 $contentHandler = ContentHandler::getForTitle( $this );
4874 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4875 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4876 } else {
4877 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4879 wfProfileOut( __METHOD__ );
4880 return $langObj;
4884 * Get the language in which the content of this page is written when
4885 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4886 * e.g. $wgLang (such as special pages, which are in the user language).
4888 * @since 1.20
4889 * @return Language
4891 public function getPageViewLanguage() {
4892 global $wgLang;
4894 if ( $this->isSpecialPage() ) {
4895 // If the user chooses a variant, the content is actually
4896 // in a language whose code is the variant code.
4897 $variant = $wgLang->getPreferredVariant();
4898 if ( $wgLang->getCode() !== $variant ) {
4899 return Language::factory( $variant );
4902 return $wgLang;
4905 //NOTE: can't be cached persistently, depends on user settings
4906 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4907 $contentHandler = ContentHandler::getForTitle( $this );
4908 $pageLang = $contentHandler->getPageViewLanguage( $this );
4909 return $pageLang;
4913 * Get a list of rendered edit notices for this page.
4915 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4916 * they will already be wrapped in paragraphs.
4918 * @since 1.21
4919 * @param int oldid Revision ID that's being edited
4920 * @return Array
4922 public function getEditNotices( $oldid = 0 ) {
4923 $notices = array();
4925 # Optional notices on a per-namespace and per-page basis
4926 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4927 $editnotice_ns_message = wfMessage( $editnotice_ns );
4928 if ( $editnotice_ns_message->exists() ) {
4929 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4931 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4932 $parts = explode( '/', $this->getDBkey() );
4933 $editnotice_base = $editnotice_ns;
4934 while ( count( $parts ) > 0 ) {
4935 $editnotice_base .= '-' . array_shift( $parts );
4936 $editnotice_base_msg = wfMessage( $editnotice_base );
4937 if ( $editnotice_base_msg->exists() ) {
4938 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4941 } else {
4942 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4943 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4944 $editnoticeMsg = wfMessage( $editnoticeText );
4945 if ( $editnoticeMsg->exists() ) {
4946 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4950 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4951 return $notices;