3 * Representation of a title within %MediaWiki.
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
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.
34 /** @var MapCacheLRU */
35 static private $titleCache = null;
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 /** @var string Text form (spaces not underscores) of the main part */
58 public $mTextform = '';
60 /** @var string URL-encoded form of the main part */
61 public $mUrlform = '';
63 /** @var string Main part with underscores */
64 public $mDbkeyform = '';
66 /** @var string Database key with the initial letter in the case specified by the user */
67 protected $mUserCaseDBKey;
69 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
70 public $mNamespace = NS_MAIN
;
72 /** @var string Interwiki prefix */
73 public $mInterwiki = '';
75 /** @var bool Was this Title created from a string with a local interwiki prefix? */
76 private $mLocalInterwiki = false;
78 /** @var string Title fragment (i.e. the bit after the #) */
79 public $mFragment = '';
81 /** @var int Article ID, fetched from the link cache on demand */
82 public $mArticleID = -1;
84 /** @var bool|int ID of most recent revision */
85 protected $mLatestID = false;
88 * @var bool|string ID of the page's content model, i.e. one of the
89 * CONTENT_MODEL_XXX constants
91 public $mContentModel = false;
93 /** @var int Estimated number of revisions; null of not loaded */
94 private $mEstimateRevisions;
96 /** @var array Array of groups allowed to edit this article */
97 public $mRestrictions = array();
99 /** @var string|bool */
100 protected $mOldRestrictions = false;
102 /** @var bool Cascade restrictions on this page to included templates and images? */
103 public $mCascadeRestriction;
105 /** Caching the results of getCascadeProtectionSources */
106 public $mCascadingRestrictions;
108 /** @var array When do the restrictions on this page expire? */
109 protected $mRestrictionsExpiry = array();
111 /** @var bool Are cascading restrictions in effect on this page? */
112 protected $mHasCascadingRestrictions;
114 /** @var array Where are the cascading restrictions coming from on this page? */
115 public $mCascadeSources;
117 /** @var bool Boolean for initialisation on demand */
118 public $mRestrictionsLoaded = false;
120 /** @var string Text form including namespace/interwiki, initialised on demand */
121 protected $mPrefixedText = null;
123 /** @var mixed Cached value for getTitleProtection (create protection) */
124 public $mTitleProtection;
127 * @var int Namespace index when there is no namespace. Don't change the
128 * following default, NS_MAIN is hardcoded in several places. See bug 696.
129 * Zero except in {{transclusion}} tags.
131 public $mDefaultNamespace = NS_MAIN
;
134 * @var bool Is $wgUser watching this page? null if unfilled, accessed
135 * through userIsWatching()
137 protected $mWatched = null;
139 /** @var int The page length, 0 for special pages */
140 protected $mLength = -1;
142 /** @var null Is the article at this title a redirect? */
143 public $mRedirect = null;
145 /** @var array Associative array of user ID -> timestamp/false */
146 private $mNotificationTimestamp = array();
148 /** @var bool Whether a page has any subpages */
149 private $mHasSubpages;
151 /** @var bool The (string) language code of the page's language and content code. */
152 private $mPageLanguage = false;
154 /** @var string The page language code from the database */
155 private $mDbPageLanguage = null;
157 /** @var TitleValue A corresponding TitleValue object */
158 private $mTitleValue = null;
160 /** @var bool Would deleting this page be a big deletion? */
161 private $mIsBigDeletion = null;
165 * B/C kludge: provide a TitleParser for use by Title.
166 * Ideally, Title would have no methods that need this.
167 * Avoid usage of this singleton by using TitleValue
168 * and the associated services when possible.
170 * @return TitleParser
172 private static function getTitleParser() {
173 global $wgContLang, $wgLocalInterwikis;
175 static $titleCodec = null;
176 static $titleCodecFingerprint = null;
178 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
179 // make sure we are using the right one. To detect changes over the course
180 // of a request, we remember a fingerprint of the config used to create the
181 // codec singleton, and re-create it if the fingerprint doesn't match.
182 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
184 if ( $fingerprint !== $titleCodecFingerprint ) {
188 if ( !$titleCodec ) {
189 $titleCodec = new MediaWikiTitleCodec(
191 GenderCache
::singleton(),
194 $titleCodecFingerprint = $fingerprint;
201 * B/C kludge: provide a TitleParser for use by Title.
202 * Ideally, Title would have no methods that need this.
203 * Avoid usage of this singleton by using TitleValue
204 * and the associated services when possible.
206 * @return TitleFormatter
208 private static function getTitleFormatter() {
209 // NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
210 // which implements TitleFormatter.
211 return self
::getTitleParser();
214 function __construct() {
218 * Create a new Title from a prefixed DB key
220 * @param string $key The database key, which has underscores
221 * instead of spaces, possibly including namespace and
223 * @return Title|null Title, or null on an error
225 public static function newFromDBkey( $key ) {
227 $t->mDbkeyform
= $key;
230 $t->secureAndSplit();
232 } catch ( MalformedTitleException
$ex ) {
238 * Create a new Title from a TitleValue
240 * @param TitleValue $titleValue Assumed to be safe.
244 public static function newFromTitleValue( TitleValue
$titleValue ) {
245 return self
::makeTitle(
246 $titleValue->getNamespace(),
247 $titleValue->getText(),
248 $titleValue->getFragment() );
252 * Create a new Title from text, such as what one would find in a link. De-
253 * codes any HTML entities in the text.
255 * @param string $text The link text; spaces, prefixes, and an
256 * initial ':' indicating the main namespace are accepted.
257 * @param int $defaultNamespace The namespace to use if none is specified
258 * by a prefix. If you want to force a specific namespace even if
259 * $text might begin with a namespace prefix, use makeTitle() or
261 * @throws InvalidArgumentException
262 * @return Title|null Title or null on an error.
264 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
265 if ( is_object( $text ) ) {
266 throw new InvalidArgumentException( '$text must be a string.' );
267 } elseif ( !is_string( $text ) ) {
268 wfDebugLog( 'T76305', wfGetAllCallers( 5 ) );
270 __METHOD__
. ': $text must be a string. ' .
271 'This will throw an InvalidArgumentException in future.',
277 return Title
::newFromTextThrow( $text, $defaultNamespace );
278 } catch ( MalformedTitleException
$ex ) {
284 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
285 * rather than returning null.
287 * The exception subclasses encode detailed information about why the title is invalid.
289 * @see Title::newFromText
292 * @param string $text Title text to check
293 * @param int $defaultNamespace
294 * @throws MalformedTitleException If the title is invalid
297 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
298 if ( is_object( $text ) ) {
299 throw new MWException( 'Title::newFromTextThrow given an object' );
302 $cache = self
::getTitleCache();
305 * Wiki pages often contain multiple links to the same page.
306 * Title normalization and parsing can become expensive on
307 * pages with many links, so we can save a little time by
310 * In theory these are value objects and won't get changed...
312 if ( $defaultNamespace == NS_MAIN
&& $cache->has( $text ) ) {
313 return $cache->get( $text );
316 # Convert things like é ā or 〗 into normalized (bug 14952) text
317 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
320 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
321 $t->mDefaultNamespace
= intval( $defaultNamespace );
323 $t->secureAndSplit();
324 if ( $defaultNamespace == NS_MAIN
) {
325 $cache->set( $text, $t );
331 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
333 * Example of wrong and broken code:
334 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
336 * Example of right code:
337 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
339 * Create a new Title from URL-encoded text. Ensures that
340 * the given title's length does not exceed the maximum.
342 * @param string $url The title, as might be taken from a URL
343 * @return Title|null The new object, or null on an error
345 public static function newFromURL( $url ) {
348 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
349 # but some URLs used it as a space replacement and they still come
350 # from some external search tools.
351 if ( strpos( self
::legalChars(), '+' ) === false ) {
352 $url = strtr( $url, '+', ' ' );
355 $t->mDbkeyform
= strtr( $url, ' ', '_' );
358 $t->secureAndSplit();
360 } catch ( MalformedTitleException
$ex ) {
366 * @return MapCacheLRU
368 private static function getTitleCache() {
369 if ( self
::$titleCache == null ) {
370 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
372 return self
::$titleCache;
376 * Returns a list of fields that are to be selected for initializing Title
377 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
378 * whether to include page_content_model.
382 protected static function getSelectFields() {
383 global $wgContentHandlerUseDB;
386 'page_namespace', 'page_title', 'page_id',
387 'page_len', 'page_is_redirect', 'page_latest',
390 if ( $wgContentHandlerUseDB ) {
391 $fields[] = 'page_content_model';
398 * Create a new Title from an article ID
400 * @param int $id The page_id corresponding to the Title to create
401 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
402 * @return Title|null The new object, or null on an error
404 public static function newFromID( $id, $flags = 0 ) {
405 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
406 $row = $db->selectRow(
408 self
::getSelectFields(),
409 array( 'page_id' => $id ),
412 if ( $row !== false ) {
413 $title = Title
::newFromRow( $row );
421 * Make an array of titles from an array of IDs
423 * @param int[] $ids Array of IDs
424 * @return Title[] Array of Titles
426 public static function newFromIDs( $ids ) {
427 if ( !count( $ids ) ) {
430 $dbr = wfGetDB( DB_SLAVE
);
434 self
::getSelectFields(),
435 array( 'page_id' => $ids ),
440 foreach ( $res as $row ) {
441 $titles[] = Title
::newFromRow( $row );
447 * Make a Title object from a DB row
449 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
450 * @return Title Corresponding Title
452 public static function newFromRow( $row ) {
453 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
454 $t->loadFromRow( $row );
459 * Load Title object fields from a DB row.
460 * If false is given, the title will be treated as non-existing.
462 * @param stdClass|bool $row Database row
464 public function loadFromRow( $row ) {
465 if ( $row ) { // page found
466 if ( isset( $row->page_id
) ) {
467 $this->mArticleID
= (int)$row->page_id
;
469 if ( isset( $row->page_len
) ) {
470 $this->mLength
= (int)$row->page_len
;
472 if ( isset( $row->page_is_redirect
) ) {
473 $this->mRedirect
= (bool)$row->page_is_redirect
;
475 if ( isset( $row->page_latest
) ) {
476 $this->mLatestID
= (int)$row->page_latest
;
478 if ( isset( $row->page_content_model
) ) {
479 $this->mContentModel
= strval( $row->page_content_model
);
481 $this->mContentModel
= false; # initialized lazily in getContentModel()
483 if ( isset( $row->page_lang
) ) {
484 $this->mDbPageLanguage
= (string)$row->page_lang
;
486 if ( isset( $row->page_restrictions
) ) {
487 $this->mOldRestrictions
= $row->page_restrictions
;
489 } else { // page not found
490 $this->mArticleID
= 0;
492 $this->mRedirect
= false;
493 $this->mLatestID
= 0;
494 $this->mContentModel
= false; # initialized lazily in getContentModel()
499 * Create a new Title from a namespace index and a DB key.
500 * It's assumed that $ns and $title are *valid*, for instance when
501 * they came directly from the database or a special page name.
502 * For convenience, spaces are converted to underscores so that
503 * eg user_text fields can be used directly.
505 * @param int $ns The namespace of the article
506 * @param string $title The unprefixed database key form
507 * @param string $fragment The link fragment (after the "#")
508 * @param string $interwiki The interwiki prefix
509 * @return Title The new object
511 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
513 $t->mInterwiki
= $interwiki;
514 $t->mFragment
= $fragment;
515 $t->mNamespace
= $ns = intval( $ns );
516 $t->mDbkeyform
= strtr( $title, ' ', '_' );
517 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
518 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
519 $t->mTextform
= strtr( $title, '_', ' ' );
520 $t->mContentModel
= false; # initialized lazily in getContentModel()
525 * Create a new Title from a namespace index and a DB key.
526 * The parameters will be checked for validity, which is a bit slower
527 * than makeTitle() but safer for user-provided data.
529 * @param int $ns The namespace of the article
530 * @param string $title Database key form
531 * @param string $fragment The link fragment (after the "#")
532 * @param string $interwiki Interwiki prefix
533 * @return Title|null The new object, or null on an error
535 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
536 if ( !MWNamespace
::exists( $ns ) ) {
541 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
544 $t->secureAndSplit();
546 } catch ( MalformedTitleException
$ex ) {
552 * Create a new Title for the Main Page
554 * @return Title The new object
556 public static function newMainPage() {
557 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
558 // Don't give fatal errors if the message is broken
560 $title = Title
::newFromText( 'Main Page' );
566 * Extract a redirect destination from a string and return the
567 * Title, or null if the text doesn't contain a valid redirect
568 * This will only return the very next target, useful for
569 * the redirect table and other checks that don't need full recursion
571 * @param string $text Text with possible redirect
572 * @return Title The corresponding Title
573 * @deprecated since 1.21, use Content::getRedirectTarget instead.
575 public static function newFromRedirect( $text ) {
576 ContentHandler
::deprecated( __METHOD__
, '1.21' );
578 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
579 return $content->getRedirectTarget();
583 * Extract a redirect destination from a string and return the
584 * Title, or null if the text doesn't contain a valid redirect
585 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
586 * in order to provide (hopefully) the Title of the final destination instead of another redirect
588 * @param string $text Text with possible redirect
590 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
592 public static function newFromRedirectRecurse( $text ) {
593 ContentHandler
::deprecated( __METHOD__
, '1.21' );
595 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
596 return $content->getUltimateRedirectTarget();
600 * Extract a redirect destination from a string and return an
601 * array of Titles, or null if the text doesn't contain a valid redirect
602 * The last element in the array is the final destination after all redirects
603 * have been resolved (up to $wgMaxRedirects times)
605 * @param string $text Text with possible redirect
606 * @return Title[] Array of Titles, with the destination last
607 * @deprecated since 1.21, use Content::getRedirectChain instead.
609 public static function newFromRedirectArray( $text ) {
610 ContentHandler
::deprecated( __METHOD__
, '1.21' );
612 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
613 return $content->getRedirectChain();
617 * Get the prefixed DB key associated with an ID
619 * @param int $id The page_id of the article
620 * @return Title|null An object representing the article, or null if no such article was found
622 public static function nameOf( $id ) {
623 $dbr = wfGetDB( DB_SLAVE
);
625 $s = $dbr->selectRow(
627 array( 'page_namespace', 'page_title' ),
628 array( 'page_id' => $id ),
631 if ( $s === false ) {
635 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
640 * Get a regex character class describing the legal characters in a link
642 * @return string The list of characters, not delimited
644 public static function legalChars() {
645 global $wgLegalTitleChars;
646 return $wgLegalTitleChars;
650 * Returns a simple regex that will match on characters and sequences invalid in titles.
651 * Note that this doesn't pick up many things that could be wrong with titles, but that
652 * replacing this regex with something valid will make many titles valid.
654 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
656 * @return string Regex string
658 static function getTitleInvalidRegex() {
659 wfDeprecated( __METHOD__
, '1.25' );
660 return MediaWikiTitleCodec
::getTitleInvalidRegex();
664 * Utility method for converting a character sequence from bytes to Unicode.
666 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
667 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
669 * @param string $byteClass
672 public static function convertByteClassToUnicodeClass( $byteClass ) {
673 $length = strlen( $byteClass );
675 $x0 = $x1 = $x2 = '';
677 $d0 = $d1 = $d2 = '';
678 // Decoded integer codepoints
679 $ord0 = $ord1 = $ord2 = 0;
681 $r0 = $r1 = $r2 = '';
685 $allowUnicode = false;
686 for ( $pos = 0; $pos < $length; $pos++
) {
687 // Shift the queues down
696 // Load the current input token and decoded values
697 $inChar = $byteClass[$pos];
698 if ( $inChar == '\\' ) {
699 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
700 $x0 = $inChar . $m[0];
701 $d0 = chr( hexdec( $m[1] ) );
702 $pos +
= strlen( $m[0] );
703 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
704 $x0 = $inChar . $m[0];
705 $d0 = chr( octdec( $m[0] ) );
706 $pos +
= strlen( $m[0] );
707 } elseif ( $pos +
1 >= $length ) {
710 $d0 = $byteClass[$pos +
1];
718 // Load the current re-encoded value
719 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
720 $r0 = sprintf( '\x%02x', $ord0 );
721 } elseif ( $ord0 >= 0x80 ) {
722 // Allow unicode if a single high-bit character appears
723 $r0 = sprintf( '\x%02x', $ord0 );
724 $allowUnicode = true;
725 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
731 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
733 if ( $ord2 > $ord0 ) {
735 } elseif ( $ord0 >= 0x80 ) {
737 $allowUnicode = true;
738 if ( $ord2 < 0x80 ) {
739 // Keep the non-unicode section of the range
746 // Reset state to the initial value
747 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
748 } elseif ( $ord2 < 0x80 ) {
753 if ( $ord1 < 0x80 ) {
756 if ( $ord0 < 0x80 ) {
759 if ( $allowUnicode ) {
760 $out .= '\u0080-\uFFFF';
766 * Make a prefixed DB key from a DB key and a namespace index
768 * @param int $ns Numerical representation of the namespace
769 * @param string $title The DB key form the title
770 * @param string $fragment The link fragment (after the "#")
771 * @param string $interwiki The interwiki prefix
772 * @param bool $canoncialNamespace If true, use the canonical name for
773 * $ns instead of the localized version.
774 * @return string The prefixed form of the title
776 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
777 $canoncialNamespace = false
781 if ( $canoncialNamespace ) {
782 $namespace = MWNamespace
::getCanonicalName( $ns );
784 $namespace = $wgContLang->getNsText( $ns );
786 $name = $namespace == '' ?
$title : "$namespace:$title";
787 if ( strval( $interwiki ) != '' ) {
788 $name = "$interwiki:$name";
790 if ( strval( $fragment ) != '' ) {
791 $name .= '#' . $fragment;
797 * Escape a text fragment, say from a link, for a URL
799 * @param string $fragment Containing a URL or link fragment (after the "#")
800 * @return string Escaped string
802 static function escapeFragmentForURL( $fragment ) {
803 # Note that we don't urlencode the fragment. urlencoded Unicode
804 # fragments appear not to work in IE (at least up to 7) or in at least
805 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
806 # to care if they aren't encoded.
807 return Sanitizer
::escapeId( $fragment, 'noninitial' );
811 * Callback for usort() to do title sorts by (namespace, title)
816 * @return int Result of string comparison, or namespace comparison
818 public static function compare( $a, $b ) {
819 if ( $a->getNamespace() == $b->getNamespace() ) {
820 return strcmp( $a->getText(), $b->getText() );
822 return $a->getNamespace() - $b->getNamespace();
827 * Determine whether the object refers to a page within
828 * this project (either this wiki or a wiki with a local
829 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
831 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
833 public function isLocal() {
834 if ( $this->isExternal() ) {
835 $iw = Interwiki
::fetch( $this->mInterwiki
);
837 return $iw->isLocal();
844 * Is this Title interwiki?
848 public function isExternal() {
849 return $this->mInterwiki
!== '';
853 * Get the interwiki prefix
855 * Use Title::isExternal to check if a interwiki is set
857 * @return string Interwiki prefix
859 public function getInterwiki() {
860 return $this->mInterwiki
;
864 * Was this a local interwiki link?
868 public function wasLocalInterwiki() {
869 return $this->mLocalInterwiki
;
873 * Determine whether the object refers to a page within
874 * this project and is transcludable.
876 * @return bool True if this is transcludable
878 public function isTrans() {
879 if ( !$this->isExternal() ) {
883 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
887 * Returns the DB name of the distant wiki which owns the object.
889 * @return string The DB name
891 public function getTransWikiID() {
892 if ( !$this->isExternal() ) {
896 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
900 * Get a TitleValue object representing this Title.
902 * @note Not all valid Titles have a corresponding valid TitleValue
903 * (e.g. TitleValues cannot represent page-local links that have a
904 * fragment but no title text).
906 * @return TitleValue|null
908 public function getTitleValue() {
909 if ( $this->mTitleValue
=== null ) {
911 $this->mTitleValue
= new TitleValue(
912 $this->getNamespace(),
914 $this->getFragment() );
915 } catch ( InvalidArgumentException
$ex ) {
916 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
917 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
921 return $this->mTitleValue
;
925 * Get the text form (spaces not underscores) of the main part
927 * @return string Main part of the title
929 public function getText() {
930 return $this->mTextform
;
934 * Get the URL-encoded form of the main part
936 * @return string Main part of the title, URL-encoded
938 public function getPartialURL() {
939 return $this->mUrlform
;
943 * Get the main part with underscores
945 * @return string Main part of the title, with underscores
947 public function getDBkey() {
948 return $this->mDbkeyform
;
952 * Get the DB key with the initial letter case as specified by the user
954 * @return string DB key
956 function getUserCaseDBKey() {
957 if ( !is_null( $this->mUserCaseDBKey
) ) {
958 return $this->mUserCaseDBKey
;
960 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
961 return $this->mDbkeyform
;
966 * Get the namespace index, i.e. one of the NS_xxxx constants.
968 * @return int Namespace index
970 public function getNamespace() {
971 return $this->mNamespace
;
975 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
977 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
978 * @return string Content model id
980 public function getContentModel( $flags = 0 ) {
981 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
982 $linkCache = LinkCache
::singleton();
983 $linkCache->addLinkObj( $this ); # in case we already had an article ID
984 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
987 if ( !$this->mContentModel
) {
988 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
991 return $this->mContentModel
;
995 * Convenience method for checking a title's content model name
997 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
998 * @return bool True if $this->getContentModel() == $id
1000 public function hasContentModel( $id ) {
1001 return $this->getContentModel() == $id;
1005 * Get the namespace text
1007 * @return string Namespace text
1009 public function getNsText() {
1010 if ( $this->isExternal() ) {
1011 // This probably shouldn't even happen,
1012 // but for interwiki transclusion it sometimes does.
1013 // Use the canonical namespaces if possible to try to
1014 // resolve a foreign namespace.
1015 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1016 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1021 $formatter = self
::getTitleFormatter();
1022 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1023 } catch ( InvalidArgumentException
$ex ) {
1024 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1030 * Get the namespace text of the subject (rather than talk) page
1032 * @return string Namespace text
1034 public function getSubjectNsText() {
1036 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1040 * Get the namespace text of the talk page
1042 * @return string Namespace text
1044 public function getTalkNsText() {
1046 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1050 * Could this title have a corresponding talk page?
1054 public function canTalk() {
1055 return MWNamespace
::canTalk( $this->mNamespace
);
1059 * Is this in a namespace that allows actual pages?
1063 public function canExist() {
1064 return $this->mNamespace
>= NS_MAIN
;
1068 * Can this title be added to a user's watchlist?
1072 public function isWatchable() {
1073 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1077 * Returns true if this is a special page.
1081 public function isSpecialPage() {
1082 return $this->getNamespace() == NS_SPECIAL
;
1086 * Returns true if this title resolves to the named special page
1088 * @param string $name The special page name
1091 public function isSpecial( $name ) {
1092 if ( $this->isSpecialPage() ) {
1093 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1094 if ( $name == $thisName ) {
1102 * If the Title refers to a special page alias which is not the local default, resolve
1103 * the alias, and localise the name as necessary. Otherwise, return $this
1107 public function fixSpecialName() {
1108 if ( $this->isSpecialPage() ) {
1109 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1110 if ( $canonicalName ) {
1111 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1112 if ( $localName != $this->mDbkeyform
) {
1113 return Title
::makeTitle( NS_SPECIAL
, $localName );
1121 * Returns true if the title is inside the specified namespace.
1123 * Please make use of this instead of comparing to getNamespace()
1124 * This function is much more resistant to changes we may make
1125 * to namespaces than code that makes direct comparisons.
1126 * @param int $ns The namespace
1130 public function inNamespace( $ns ) {
1131 return MWNamespace
::equals( $this->getNamespace(), $ns );
1135 * Returns true if the title is inside one of the specified namespaces.
1137 * @param int $namespaces,... The namespaces to check for
1141 public function inNamespaces( /* ... */ ) {
1142 $namespaces = func_get_args();
1143 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1144 $namespaces = $namespaces[0];
1147 foreach ( $namespaces as $ns ) {
1148 if ( $this->inNamespace( $ns ) ) {
1157 * Returns true if the title has the same subject namespace as the
1158 * namespace specified.
1159 * For example this method will take NS_USER and return true if namespace
1160 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1161 * as their subject namespace.
1163 * This is MUCH simpler than individually testing for equivalence
1164 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1169 public function hasSubjectNamespace( $ns ) {
1170 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1174 * Is this Title in a namespace which contains content?
1175 * In other words, is this a content page, for the purposes of calculating
1180 public function isContentPage() {
1181 return MWNamespace
::isContent( $this->getNamespace() );
1185 * Would anybody with sufficient privileges be able to move this page?
1186 * Some pages just aren't movable.
1190 public function isMovable() {
1191 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1192 // Interwiki title or immovable namespace. Hooks don't get to override here
1197 Hooks
::run( 'TitleIsMovable', array( $this, &$result ) );
1202 * Is this the mainpage?
1203 * @note Title::newFromText seems to be sufficiently optimized by the title
1204 * cache that we don't need to over-optimize by doing direct comparisons and
1205 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1206 * ends up reporting something differently than $title->isMainPage();
1211 public function isMainPage() {
1212 return $this->equals( Title
::newMainPage() );
1216 * Is this a subpage?
1220 public function isSubpage() {
1221 return MWNamespace
::hasSubpages( $this->mNamespace
)
1222 ?
strpos( $this->getText(), '/' ) !== false
1227 * Is this a conversion table for the LanguageConverter?
1231 public function isConversionTable() {
1232 // @todo ConversionTable should become a separate content model.
1234 return $this->getNamespace() == NS_MEDIAWIKI
&&
1235 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1239 * Does that page contain wikitext, or it is JS, CSS or whatever?
1243 public function isWikitextPage() {
1244 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1248 * Could this page contain custom CSS or JavaScript for the global UI.
1249 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1250 * or CONTENT_MODEL_JAVASCRIPT.
1252 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1255 * Note that this method should not return true for pages that contain and
1256 * show "inactive" CSS or JS.
1260 public function isCssOrJsPage() {
1261 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1262 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1263 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1265 # @note This hook is also called in ContentHandler::getDefaultModel.
1266 # It's called here again to make sure hook functions can force this
1267 # method to return true even outside the MediaWiki namespace.
1269 Hooks
::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1271 return $isCssOrJsPage;
1275 * Is this a .css or .js subpage of a user page?
1278 public function isCssJsSubpage() {
1279 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1280 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1281 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1285 * Trim down a .css or .js subpage title to get the corresponding skin name
1287 * @return string Containing skin name from .css or .js subpage title
1289 public function getSkinFromCssJsSubpage() {
1290 $subpage = explode( '/', $this->mTextform
);
1291 $subpage = $subpage[count( $subpage ) - 1];
1292 $lastdot = strrpos( $subpage, '.' );
1293 if ( $lastdot === false ) {
1294 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1296 return substr( $subpage, 0, $lastdot );
1300 * Is this a .css subpage of a user page?
1304 public function isCssSubpage() {
1305 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1306 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1310 * Is this a .js subpage of a user page?
1314 public function isJsSubpage() {
1315 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1316 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1320 * Is this a talk page of some sort?
1324 public function isTalkPage() {
1325 return MWNamespace
::isTalk( $this->getNamespace() );
1329 * Get a Title object associated with the talk page of this article
1331 * @return Title The object for the talk page
1333 public function getTalkPage() {
1334 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1338 * Get a title object associated with the subject page of this
1341 * @return Title The object for the subject page
1343 public function getSubjectPage() {
1344 // Is this the same title?
1345 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1346 if ( $this->getNamespace() == $subjectNS ) {
1349 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1353 * Get the other title for this page, if this is a subject page
1354 * get the talk page, if it is a subject page get the talk page
1357 * @throws MWException
1360 public function getOtherPage() {
1361 if ( $this->isSpecialPage() ) {
1362 throw new MWException( 'Special pages cannot have other pages' );
1364 if ( $this->isTalkPage() ) {
1365 return $this->getSubjectPage();
1367 return $this->getTalkPage();
1372 * Get the default namespace index, for when there is no namespace
1374 * @return int Default namespace index
1376 public function getDefaultNamespace() {
1377 return $this->mDefaultNamespace
;
1381 * Get the Title fragment (i.e.\ the bit after the #) in text form
1383 * Use Title::hasFragment to check for a fragment
1385 * @return string Title fragment
1387 public function getFragment() {
1388 return $this->mFragment
;
1392 * Check if a Title fragment is set
1397 public function hasFragment() {
1398 return $this->mFragment
!== '';
1402 * Get the fragment in URL form, including the "#" character if there is one
1403 * @return string Fragment in URL form
1405 public function getFragmentForURL() {
1406 if ( !$this->hasFragment() ) {
1409 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1414 * Set the fragment for this title. Removes the first character from the
1415 * specified fragment before setting, so it assumes you're passing it with
1418 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1419 * Still in active use privately.
1422 * @param string $fragment Text
1424 public function setFragment( $fragment ) {
1425 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1429 * Prefix some arbitrary text with the namespace or interwiki prefix
1432 * @param string $name The text
1433 * @return string The prefixed text
1435 private function prefix( $name ) {
1437 if ( $this->isExternal() ) {
1438 $p = $this->mInterwiki
. ':';
1441 if ( 0 != $this->mNamespace
) {
1442 $p .= $this->getNsText() . ':';
1448 * Get the prefixed database key form
1450 * @return string The prefixed title, with underscores and
1451 * any interwiki and namespace prefixes
1453 public function getPrefixedDBkey() {
1454 $s = $this->prefix( $this->mDbkeyform
);
1455 $s = strtr( $s, ' ', '_' );
1460 * Get the prefixed title with spaces.
1461 * This is the form usually used for display
1463 * @return string The prefixed title, with spaces
1465 public function getPrefixedText() {
1466 if ( $this->mPrefixedText
=== null ) {
1467 $s = $this->prefix( $this->mTextform
);
1468 $s = strtr( $s, '_', ' ' );
1469 $this->mPrefixedText
= $s;
1471 return $this->mPrefixedText
;
1475 * Return a string representation of this title
1477 * @return string Representation of this title
1479 public function __toString() {
1480 return $this->getPrefixedText();
1484 * Get the prefixed title with spaces, plus any fragment
1485 * (part beginning with '#')
1487 * @return string The prefixed title, with spaces and the fragment, including '#'
1489 public function getFullText() {
1490 $text = $this->getPrefixedText();
1491 if ( $this->hasFragment() ) {
1492 $text .= '#' . $this->getFragment();
1498 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1502 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1506 * @return string Root name
1509 public function getRootText() {
1510 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1511 return $this->getText();
1514 return strtok( $this->getText(), '/' );
1518 * Get the root page name title, i.e. the leftmost part before any slashes
1522 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1523 * # returns: Title{User:Foo}
1526 * @return Title Root title
1529 public function getRootTitle() {
1530 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1534 * Get the base page name without a namespace, i.e. the part before the subpage name
1538 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1539 * # returns: 'Foo/Bar'
1542 * @return string Base name
1544 public function getBaseText() {
1545 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1546 return $this->getText();
1549 $parts = explode( '/', $this->getText() );
1550 # Don't discard the real title if there's no subpage involved
1551 if ( count( $parts ) > 1 ) {
1552 unset( $parts[count( $parts ) - 1] );
1554 return implode( '/', $parts );
1558 * Get the base page name title, i.e. the part before the subpage name
1562 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1563 * # returns: Title{User:Foo/Bar}
1566 * @return Title Base title
1569 public function getBaseTitle() {
1570 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1574 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1578 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1582 * @return string Subpage name
1584 public function getSubpageText() {
1585 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1586 return $this->mTextform
;
1588 $parts = explode( '/', $this->mTextform
);
1589 return $parts[count( $parts ) - 1];
1593 * Get the title for a subpage of the current page
1597 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1598 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1601 * @param string $text The subpage name to add to the title
1602 * @return Title Subpage title
1605 public function getSubpage( $text ) {
1606 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1610 * Get a URL-encoded form of the subpage text
1612 * @return string URL-encoded subpage name
1614 public function getSubpageUrlForm() {
1615 $text = $this->getSubpageText();
1616 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1621 * Get a URL-encoded title (not an actual URL) including interwiki
1623 * @return string The URL-encoded form
1625 public function getPrefixedURL() {
1626 $s = $this->prefix( $this->mDbkeyform
);
1627 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1632 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1633 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1634 * second argument named variant. This was deprecated in favor
1635 * of passing an array of option with a "variant" key
1636 * Once $query2 is removed for good, this helper can be dropped
1637 * and the wfArrayToCgi moved to getLocalURL();
1639 * @since 1.19 (r105919)
1640 * @param array|string $query
1641 * @param bool $query2
1644 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1645 if ( $query2 !== false ) {
1646 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1647 "method called with a second parameter is deprecated. Add your " .
1648 "parameter to an array passed as the first parameter.", "1.19" );
1650 if ( is_array( $query ) ) {
1651 $query = wfArrayToCgi( $query );
1654 if ( is_string( $query2 ) ) {
1655 // $query2 is a string, we will consider this to be
1656 // a deprecated $variant argument and add it to the query
1657 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1659 $query2 = wfArrayToCgi( $query2 );
1661 // If we have $query content add a & to it first
1665 // Now append the queries together
1672 * Get a real URL referring to this title, with interwiki link and
1675 * @see self::getLocalURL for the arguments.
1677 * @param array|string $query
1678 * @param bool $query2
1679 * @param string $proto Protocol type to use in URL
1680 * @return string The URL
1682 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1683 $query = self
::fixUrlQueryArgs( $query, $query2 );
1685 # Hand off all the decisions on urls to getLocalURL
1686 $url = $this->getLocalURL( $query );
1688 # Expand the url to make it a full url. Note that getLocalURL has the
1689 # potential to output full urls for a variety of reasons, so we use
1690 # wfExpandUrl instead of simply prepending $wgServer
1691 $url = wfExpandUrl( $url, $proto );
1693 # Finally, add the fragment.
1694 $url .= $this->getFragmentForURL();
1696 Hooks
::run( 'GetFullURL', array( &$this, &$url, $query ) );
1701 * Get a URL with no fragment or server name (relative URL) from a Title object.
1702 * If this page is generated with action=render, however,
1703 * $wgServer is prepended to make an absolute URL.
1705 * @see self::getFullURL to always get an absolute URL.
1706 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1707 * valid to link, locally, to the current Title.
1708 * @see self::newFromText to produce a Title object.
1710 * @param string|array $query An optional query string,
1711 * not used for interwiki links. Can be specified as an associative array as well,
1712 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1713 * Some query patterns will trigger various shorturl path replacements.
1714 * @param array $query2 An optional secondary query array. This one MUST
1715 * be an array. If a string is passed it will be interpreted as a deprecated
1716 * variant argument and urlencoded into a variant= argument.
1717 * This second query argument will be added to the $query
1718 * The second parameter is deprecated since 1.19. Pass it as a key,value
1719 * pair in the first parameter array instead.
1721 * @return string String of the URL.
1723 public function getLocalURL( $query = '', $query2 = false ) {
1724 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1726 $query = self
::fixUrlQueryArgs( $query, $query2 );
1728 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1730 $namespace = $this->getNsText();
1731 if ( $namespace != '' ) {
1732 # Can this actually happen? Interwikis shouldn't be parsed.
1733 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1736 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1737 $url = wfAppendQuery( $url, $query );
1739 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1740 if ( $query == '' ) {
1741 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1742 Hooks
::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1744 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1748 if ( !empty( $wgActionPaths )
1749 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1751 $action = urldecode( $matches[2] );
1752 if ( isset( $wgActionPaths[$action] ) ) {
1753 $query = $matches[1];
1754 if ( isset( $matches[4] ) ) {
1755 $query .= $matches[4];
1757 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1758 if ( $query != '' ) {
1759 $url = wfAppendQuery( $url, $query );
1765 && $wgVariantArticlePath
1766 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1767 && $this->getPageLanguage()->hasVariants()
1768 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1770 $variant = urldecode( $matches[1] );
1771 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1772 // Only do the variant replacement if the given variant is a valid
1773 // variant for the page's language.
1774 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1775 $url = str_replace( '$1', $dbkey, $url );
1779 if ( $url === false ) {
1780 if ( $query == '-' ) {
1783 $url = "{$wgScript}?title={$dbkey}&{$query}";
1787 Hooks
::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1789 // @todo FIXME: This causes breakage in various places when we
1790 // actually expected a local URL and end up with dupe prefixes.
1791 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1792 $url = $wgServer . $url;
1795 Hooks
::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1800 * Get a URL that's the simplest URL that will be valid to link, locally,
1801 * to the current Title. It includes the fragment, but does not include
1802 * the server unless action=render is used (or the link is external). If
1803 * there's a fragment but the prefixed text is empty, we just return a link
1806 * The result obviously should not be URL-escaped, but does need to be
1807 * HTML-escaped if it's being output in HTML.
1809 * @param array $query
1810 * @param bool $query2
1811 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1812 * @see self::getLocalURL for the arguments.
1813 * @return string The URL
1815 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1816 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1817 $ret = $this->getFullURL( $query, $query2, $proto );
1818 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1819 $ret = $this->getFragmentForURL();
1821 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1827 * Get the URL form for an internal link.
1828 * - Used in various Squid-related code, in case we have a different
1829 * internal hostname for the server from the exposed one.
1831 * This uses $wgInternalServer to qualify the path, or $wgServer
1832 * if $wgInternalServer is not set. If the server variable used is
1833 * protocol-relative, the URL will be expanded to http://
1835 * @see self::getLocalURL for the arguments.
1836 * @return string The URL
1838 public function getInternalURL( $query = '', $query2 = false ) {
1839 global $wgInternalServer, $wgServer;
1840 $query = self
::fixUrlQueryArgs( $query, $query2 );
1841 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1842 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1843 Hooks
::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1848 * Get the URL for a canonical link, for use in things like IRC and
1849 * e-mail notifications. Uses $wgCanonicalServer and the
1850 * GetCanonicalURL hook.
1852 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1854 * @see self::getLocalURL for the arguments.
1855 * @return string The URL
1858 public function getCanonicalURL( $query = '', $query2 = false ) {
1859 $query = self
::fixUrlQueryArgs( $query, $query2 );
1860 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1861 Hooks
::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1866 * Get the edit URL for this Title
1868 * @return string The URL, or a null string if this is an interwiki link
1870 public function getEditURL() {
1871 if ( $this->isExternal() ) {
1874 $s = $this->getLocalURL( 'action=edit' );
1880 * Is $wgUser watching this page?
1882 * @deprecated since 1.20; use User::isWatched() instead.
1885 public function userIsWatching() {
1888 if ( is_null( $this->mWatched
) ) {
1889 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1890 $this->mWatched
= false;
1892 $this->mWatched
= $wgUser->isWatched( $this );
1895 return $this->mWatched
;
1899 * Can $user perform $action on this page?
1900 * This skips potentially expensive cascading permission checks
1901 * as well as avoids expensive error formatting
1903 * Suitable for use for nonessential UI controls in common cases, but
1904 * _not_ for functional access control.
1906 * May provide false positives, but should never provide a false negative.
1908 * @param string $action Action that permission needs to be checked for
1909 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1912 public function quickUserCan( $action, $user = null ) {
1913 return $this->userCan( $action, $user, false );
1917 * Can $user perform $action on this page?
1919 * @param string $action Action that permission needs to be checked for
1920 * @param User $user User to check (since 1.19); $wgUser will be used if not
1922 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1925 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1926 if ( !$user instanceof User
) {
1931 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1935 * Can $user perform $action on this page?
1937 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1939 * @param string $action Action that permission needs to be checked for
1940 * @param User $user User to check
1941 * @param string $rigor One of (quick,full,secure)
1942 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1943 * - full : does cheap and expensive checks possibly from a slave
1944 * - secure : does cheap and expensive checks, using the master as needed
1945 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1946 * whose corresponding errors may be ignored.
1947 * @return array Array of arguments to wfMessage to explain permissions problems.
1949 public function getUserPermissionsErrors(
1950 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1952 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1954 // Remove the errors being ignored.
1955 foreach ( $errors as $index => $error ) {
1956 $error_key = is_array( $error ) ?
$error[0] : $error;
1958 if ( in_array( $error_key, $ignoreErrors ) ) {
1959 unset( $errors[$index] );
1967 * Permissions checks that fail most often, and which are easiest to test.
1969 * @param string $action The action to check
1970 * @param User $user User to check
1971 * @param array $errors List of current errors
1972 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1973 * @param bool $short Short circuit on first error
1975 * @return array List of errors
1977 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1978 if ( !Hooks
::run( 'TitleQuickPermissions',
1979 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1984 if ( $action == 'create' ) {
1986 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1987 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1989 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1991 } elseif ( $action == 'move' ) {
1992 if ( !$user->isAllowed( 'move-rootuserpages' )
1993 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1994 // Show user page-specific message only if the user can move other pages
1995 $errors[] = array( 'cant-move-user-page' );
1998 // Check if user is allowed to move files if it's a file
1999 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2000 $errors[] = array( 'movenotallowedfile' );
2003 // Check if user is allowed to move category pages if it's a category page
2004 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2005 $errors[] = array( 'cant-move-category-page' );
2008 if ( !$user->isAllowed( 'move' ) ) {
2009 // User can't move anything
2010 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2011 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2012 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2013 // custom message if logged-in users without any special rights can move
2014 $errors[] = array( 'movenologintext' );
2016 $errors[] = array( 'movenotallowed' );
2019 } elseif ( $action == 'move-target' ) {
2020 if ( !$user->isAllowed( 'move' ) ) {
2021 // User can't move anything
2022 $errors[] = array( 'movenotallowed' );
2023 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2024 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2025 // Show user page-specific message only if the user can move other pages
2026 $errors[] = array( 'cant-move-to-user-page' );
2027 } elseif ( !$user->isAllowed( 'move-categorypages' )
2028 && $this->mNamespace
== NS_CATEGORY
) {
2029 // Show category page-specific message only if the user can move other pages
2030 $errors[] = array( 'cant-move-to-category-page' );
2032 } elseif ( !$user->isAllowed( $action ) ) {
2033 $errors[] = $this->missingPermissionError( $action, $short );
2040 * Add the resulting error code to the errors array
2042 * @param array $errors List of current errors
2043 * @param array $result Result of errors
2045 * @return array List of errors
2047 private function resultToError( $errors, $result ) {
2048 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2049 // A single array representing an error
2050 $errors[] = $result;
2051 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2052 // A nested array representing multiple errors
2053 $errors = array_merge( $errors, $result );
2054 } elseif ( $result !== '' && is_string( $result ) ) {
2055 // A string representing a message-id
2056 $errors[] = array( $result );
2057 } elseif ( $result === false ) {
2058 // a generic "We don't want them to do that"
2059 $errors[] = array( 'badaccess-group0' );
2065 * Check various permission hooks
2067 * @param string $action The action to check
2068 * @param User $user User to check
2069 * @param array $errors List of current errors
2070 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2071 * @param bool $short Short circuit on first error
2073 * @return array List of errors
2075 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2076 // Use getUserPermissionsErrors instead
2078 if ( !Hooks
::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2079 return $result ?
array() : array( array( 'badaccess-group0' ) );
2081 // Check getUserPermissionsErrors hook
2082 if ( !Hooks
::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2083 $errors = $this->resultToError( $errors, $result );
2085 // Check getUserPermissionsErrorsExpensive hook
2088 && !( $short && count( $errors ) > 0 )
2089 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2091 $errors = $this->resultToError( $errors, $result );
2098 * Check permissions on special pages & namespaces
2100 * @param string $action The action to check
2101 * @param User $user User to check
2102 * @param array $errors List of current errors
2103 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2104 * @param bool $short Short circuit on first error
2106 * @return array List of errors
2108 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2109 # Only 'createaccount' can be performed on special pages,
2110 # which don't actually exist in the DB.
2111 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2112 $errors[] = array( 'ns-specialprotected' );
2115 # Check $wgNamespaceProtection for restricted namespaces
2116 if ( $this->isNamespaceProtected( $user ) ) {
2117 $ns = $this->mNamespace
== NS_MAIN ?
2118 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2119 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2120 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2127 * Check CSS/JS sub-page permissions
2129 * @param string $action The action to check
2130 * @param User $user User to check
2131 * @param array $errors List of current errors
2132 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2133 * @param bool $short Short circuit on first error
2135 * @return array List of errors
2137 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2138 # Protect css/js subpages of user pages
2139 # XXX: this might be better using restrictions
2140 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2141 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2142 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2143 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2144 $errors[] = array( 'mycustomcssprotected', $action );
2145 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2146 $errors[] = array( 'mycustomjsprotected', $action );
2149 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2150 $errors[] = array( 'customcssprotected', $action );
2151 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2152 $errors[] = array( 'customjsprotected', $action );
2161 * Check against page_restrictions table requirements on this
2162 * page. The user must possess all required rights for this
2165 * @param string $action The action to check
2166 * @param User $user User to check
2167 * @param array $errors List of current errors
2168 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2169 * @param bool $short Short circuit on first error
2171 * @return array List of errors
2173 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2174 foreach ( $this->getRestrictions( $action ) as $right ) {
2175 // Backwards compatibility, rewrite sysop -> editprotected
2176 if ( $right == 'sysop' ) {
2177 $right = 'editprotected';
2179 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2180 if ( $right == 'autoconfirmed' ) {
2181 $right = 'editsemiprotected';
2183 if ( $right == '' ) {
2186 if ( !$user->isAllowed( $right ) ) {
2187 $errors[] = array( 'protectedpagetext', $right, $action );
2188 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2189 $errors[] = array( 'protectedpagetext', 'protect', $action );
2197 * Check restrictions on cascading pages.
2199 * @param string $action The action to check
2200 * @param User $user User to check
2201 * @param array $errors List of current errors
2202 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2203 * @param bool $short Short circuit on first error
2205 * @return array List of errors
2207 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2208 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2209 # We /could/ use the protection level on the source page, but it's
2210 # fairly ugly as we have to establish a precedence hierarchy for pages
2211 # included by multiple cascade-protected pages. So just restrict
2212 # it to people with 'protect' permission, as they could remove the
2213 # protection anyway.
2214 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2215 # Cascading protection depends on more than this page...
2216 # Several cascading protected pages may include this page...
2217 # Check each cascading level
2218 # This is only for protection restrictions, not for all actions
2219 if ( isset( $restrictions[$action] ) ) {
2220 foreach ( $restrictions[$action] as $right ) {
2221 // Backwards compatibility, rewrite sysop -> editprotected
2222 if ( $right == 'sysop' ) {
2223 $right = 'editprotected';
2225 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2226 if ( $right == 'autoconfirmed' ) {
2227 $right = 'editsemiprotected';
2229 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2231 foreach ( $cascadingSources as $page ) {
2232 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2234 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2244 * Check action permissions not already checked in checkQuickPermissions
2246 * @param string $action The action to check
2247 * @param User $user User to check
2248 * @param array $errors List of current errors
2249 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2250 * @param bool $short Short circuit on first error
2252 * @return array List of errors
2254 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2255 global $wgDeleteRevisionsLimit, $wgLang;
2257 if ( $action == 'protect' ) {
2258 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2259 // If they can't edit, they shouldn't protect.
2260 $errors[] = array( 'protect-cantedit' );
2262 } elseif ( $action == 'create' ) {
2263 $title_protection = $this->getTitleProtection();
2264 if ( $title_protection ) {
2265 if ( $title_protection['permission'] == ''
2266 ||
!$user->isAllowed( $title_protection['permission'] )
2270 User
::whoIs( $title_protection['user'] ),
2271 $title_protection['reason']
2275 } elseif ( $action == 'move' ) {
2276 // Check for immobile pages
2277 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2278 // Specific message for this case
2279 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2280 } elseif ( !$this->isMovable() ) {
2281 // Less specific message for rarer cases
2282 $errors[] = array( 'immobile-source-page' );
2284 } elseif ( $action == 'move-target' ) {
2285 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2286 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2287 } elseif ( !$this->isMovable() ) {
2288 $errors[] = array( 'immobile-target-page' );
2290 } elseif ( $action == 'delete' ) {
2291 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2292 if ( !$tempErrors ) {
2293 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2294 $user, $tempErrors, $rigor, true );
2296 if ( $tempErrors ) {
2297 // If protection keeps them from editing, they shouldn't be able to delete.
2298 $errors[] = array( 'deleteprotected' );
2300 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2301 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2303 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2310 * Check that the user isn't blocked from editing.
2312 * @param string $action The action to check
2313 * @param User $user User to check
2314 * @param array $errors List of current errors
2315 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2316 * @param bool $short Short circuit on first error
2318 * @return array List of errors
2320 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2321 // Account creation blocks handled at userlogin.
2322 // Unblocking handled in SpecialUnblock
2323 if ( $rigor === 'quick' ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2327 global $wgEmailConfirmToEdit;
2329 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2330 $errors[] = array( 'confirmedittext' );
2333 $useSlave = ( $rigor !== 'secure' );
2334 if ( ( $action == 'edit' ||
$action == 'create' )
2335 && !$user->isBlockedFrom( $this, $useSlave )
2337 // Don't block the user from editing their own talk page unless they've been
2338 // explicitly blocked from that too.
2339 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2340 // @todo FIXME: Pass the relevant context into this function.
2341 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2348 * Check that the user is allowed to read this page.
2350 * @param string $action The action to check
2351 * @param User $user User to check
2352 * @param array $errors List of current errors
2353 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2354 * @param bool $short Short circuit on first error
2356 * @return array List of errors
2358 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2359 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2361 $whitelisted = false;
2362 if ( User
::isEveryoneAllowed( 'read' ) ) {
2363 # Shortcut for public wikis, allows skipping quite a bit of code
2364 $whitelisted = true;
2365 } elseif ( $user->isAllowed( 'read' ) ) {
2366 # If the user is allowed to read pages, he is allowed to read all pages
2367 $whitelisted = true;
2368 } elseif ( $this->isSpecial( 'Userlogin' )
2369 ||
$this->isSpecial( 'ChangePassword' )
2370 ||
$this->isSpecial( 'PasswordReset' )
2372 # Always grant access to the login page.
2373 # Even anons need to be able to log in.
2374 $whitelisted = true;
2375 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2376 # Time to check the whitelist
2377 # Only do these checks is there's something to check against
2378 $name = $this->getPrefixedText();
2379 $dbName = $this->getPrefixedDBkey();
2381 // Check for explicit whitelisting with and without underscores
2382 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2383 $whitelisted = true;
2384 } elseif ( $this->getNamespace() == NS_MAIN
) {
2385 # Old settings might have the title prefixed with
2386 # a colon for main-namespace pages
2387 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2388 $whitelisted = true;
2390 } elseif ( $this->isSpecialPage() ) {
2391 # If it's a special page, ditch the subpage bit and check again
2392 $name = $this->getDBkey();
2393 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2395 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2396 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2397 $whitelisted = true;
2403 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2404 $name = $this->getPrefixedText();
2405 // Check for regex whitelisting
2406 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2407 if ( preg_match( $listItem, $name ) ) {
2408 $whitelisted = true;
2414 if ( !$whitelisted ) {
2415 # If the title is not whitelisted, give extensions a chance to do so...
2416 Hooks
::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2417 if ( !$whitelisted ) {
2418 $errors[] = $this->missingPermissionError( $action, $short );
2426 * Get a description array when the user doesn't have the right to perform
2427 * $action (i.e. when User::isAllowed() returns false)
2429 * @param string $action The action to check
2430 * @param bool $short Short circuit on first error
2431 * @return array List of errors
2433 private function missingPermissionError( $action, $short ) {
2434 // We avoid expensive display logic for quickUserCan's and such
2436 return array( 'badaccess-group0' );
2439 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2440 User
::getGroupsWithPermission( $action ) );
2442 if ( count( $groups ) ) {
2446 $wgLang->commaList( $groups ),
2450 return array( 'badaccess-group0' );
2455 * Can $user perform $action on this page? This is an internal function,
2456 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2457 * checks on wfReadOnly() and blocks)
2459 * @param string $action Action that permission needs to be checked for
2460 * @param User $user User to check
2461 * @param string $rigor One of (quick,full,secure)
2462 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2463 * - full : does cheap and expensive checks possibly from a slave
2464 * - secure : does cheap and expensive checks, using the master as needed
2465 * @param bool $short Set this to true to stop after the first permission error.
2466 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2468 protected function getUserPermissionsErrorsInternal(
2469 $action, $user, $rigor = 'secure', $short = false
2471 if ( $rigor === true ) {
2472 $rigor = 'secure'; // b/c
2473 } elseif ( $rigor === false ) {
2474 $rigor = 'quick'; // b/c
2475 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2476 throw new Exception( "Invalid rigor parameter '$rigor'." );
2479 # Read has special handling
2480 if ( $action == 'read' ) {
2482 'checkPermissionHooks',
2483 'checkReadPermissions',
2485 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2486 # here as it will lead to duplicate error messages. This is okay to do
2487 # since anywhere that checks for create will also check for edit, and
2488 # those checks are called for edit.
2489 } elseif ( $action == 'create' ) {
2491 'checkQuickPermissions',
2492 'checkPermissionHooks',
2493 'checkPageRestrictions',
2494 'checkCascadingSourcesRestrictions',
2495 'checkActionPermissions',
2500 'checkQuickPermissions',
2501 'checkPermissionHooks',
2502 'checkSpecialsAndNSPermissions',
2503 'checkCSSandJSPermissions',
2504 'checkPageRestrictions',
2505 'checkCascadingSourcesRestrictions',
2506 'checkActionPermissions',
2512 while ( count( $checks ) > 0 &&
2513 !( $short && count( $errors ) > 0 ) ) {
2514 $method = array_shift( $checks );
2515 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2522 * Get a filtered list of all restriction types supported by this wiki.
2523 * @param bool $exists True to get all restriction types that apply to
2524 * titles that do exist, False for all restriction types that apply to
2525 * titles that do not exist
2528 public static function getFilteredRestrictionTypes( $exists = true ) {
2529 global $wgRestrictionTypes;
2530 $types = $wgRestrictionTypes;
2532 # Remove the create restriction for existing titles
2533 $types = array_diff( $types, array( 'create' ) );
2535 # Only the create and upload restrictions apply to non-existing titles
2536 $types = array_intersect( $types, array( 'create', 'upload' ) );
2542 * Returns restriction types for the current Title
2544 * @return array Applicable restriction types
2546 public function getRestrictionTypes() {
2547 if ( $this->isSpecialPage() ) {
2551 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2553 if ( $this->getNamespace() != NS_FILE
) {
2554 # Remove the upload restriction for non-file titles
2555 $types = array_diff( $types, array( 'upload' ) );
2558 Hooks
::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2560 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2561 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2567 * Is this title subject to title protection?
2568 * Title protection is the one applied against creation of such title.
2570 * @return array|bool An associative array representing any existent title
2571 * protection, or false if there's none.
2573 public function getTitleProtection() {
2574 // Can't protect pages in special namespaces
2575 if ( $this->getNamespace() < 0 ) {
2579 // Can't protect pages that exist.
2580 if ( $this->exists() ) {
2584 if ( $this->mTitleProtection
=== null ) {
2585 $dbr = wfGetDB( DB_SLAVE
);
2586 $res = $dbr->select(
2589 'user' => 'pt_user',
2590 'reason' => 'pt_reason',
2591 'expiry' => 'pt_expiry',
2592 'permission' => 'pt_create_perm'
2594 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2598 // fetchRow returns false if there are no rows.
2599 $row = $dbr->fetchRow( $res );
2601 if ( $row['permission'] == 'sysop' ) {
2602 $row['permission'] = 'editprotected'; // B/C
2604 if ( $row['permission'] == 'autoconfirmed' ) {
2605 $row['permission'] = 'editsemiprotected'; // B/C
2607 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2609 $this->mTitleProtection
= $row;
2611 return $this->mTitleProtection
;
2615 * Remove any title protection due to page existing
2617 public function deleteTitleProtection() {
2618 $dbw = wfGetDB( DB_MASTER
);
2622 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2625 $this->mTitleProtection
= false;
2629 * Is this page "semi-protected" - the *only* protection levels are listed
2630 * in $wgSemiprotectedRestrictionLevels?
2632 * @param string $action Action to check (default: edit)
2635 public function isSemiProtected( $action = 'edit' ) {
2636 global $wgSemiprotectedRestrictionLevels;
2638 $restrictions = $this->getRestrictions( $action );
2639 $semi = $wgSemiprotectedRestrictionLevels;
2640 if ( !$restrictions ||
!$semi ) {
2641 // Not protected, or all protection is full protection
2645 // Remap autoconfirmed to editsemiprotected for BC
2646 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2647 $semi[$key] = 'editsemiprotected';
2649 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2650 $restrictions[$key] = 'editsemiprotected';
2653 return !array_diff( $restrictions, $semi );
2657 * Does the title correspond to a protected article?
2659 * @param string $action The action the page is protected from,
2660 * by default checks all actions.
2663 public function isProtected( $action = '' ) {
2664 global $wgRestrictionLevels;
2666 $restrictionTypes = $this->getRestrictionTypes();
2668 # Special pages have inherent protection
2669 if ( $this->isSpecialPage() ) {
2673 # Check regular protection levels
2674 foreach ( $restrictionTypes as $type ) {
2675 if ( $action == $type ||
$action == '' ) {
2676 $r = $this->getRestrictions( $type );
2677 foreach ( $wgRestrictionLevels as $level ) {
2678 if ( in_array( $level, $r ) && $level != '' ) {
2689 * Determines if $user is unable to edit this page because it has been protected
2690 * by $wgNamespaceProtection.
2692 * @param User $user User object to check permissions
2695 public function isNamespaceProtected( User
$user ) {
2696 global $wgNamespaceProtection;
2698 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2699 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2700 if ( $right != '' && !$user->isAllowed( $right ) ) {
2709 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2711 * @return bool If the page is subject to cascading restrictions.
2713 public function isCascadeProtected() {
2714 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2715 return ( $sources > 0 );
2719 * Determines whether cascading protection sources have already been loaded from
2722 * @param bool $getPages True to check if the pages are loaded, or false to check
2723 * if the status is loaded.
2724 * @return bool Whether or not the specified information has been loaded
2727 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2728 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2732 * Cascading protection: Get the source of any cascading restrictions on this page.
2734 * @param bool $getPages Whether or not to retrieve the actual pages
2735 * that the restrictions have come from and the actual restrictions
2737 * @return array Two elements: First is an array of Title objects of the
2738 * pages from which cascading restrictions have come, false for
2739 * none, or true if such restrictions exist but $getPages was not
2740 * set. Second is an array like that returned by
2741 * Title::getAllRestrictions(), or an empty array if $getPages is
2744 public function getCascadeProtectionSources( $getPages = true ) {
2745 $pagerestrictions = array();
2747 if ( $this->mCascadeSources
!== null && $getPages ) {
2748 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2749 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2750 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2753 $dbr = wfGetDB( DB_SLAVE
);
2755 if ( $this->getNamespace() == NS_FILE
) {
2756 $tables = array( 'imagelinks', 'page_restrictions' );
2757 $where_clauses = array(
2758 'il_to' => $this->getDBkey(),
2763 $tables = array( 'templatelinks', 'page_restrictions' );
2764 $where_clauses = array(
2765 'tl_namespace' => $this->getNamespace(),
2766 'tl_title' => $this->getDBkey(),
2773 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2774 'pr_expiry', 'pr_type', 'pr_level' );
2775 $where_clauses[] = 'page_id=pr_page';
2778 $cols = array( 'pr_expiry' );
2781 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2783 $sources = $getPages ?
array() : false;
2784 $now = wfTimestampNow();
2786 foreach ( $res as $row ) {
2787 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2788 if ( $expiry > $now ) {
2790 $page_id = $row->pr_page
;
2791 $page_ns = $row->page_namespace
;
2792 $page_title = $row->page_title
;
2793 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2794 # Add groups needed for each restriction type if its not already there
2795 # Make sure this restriction type still exists
2797 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2798 $pagerestrictions[$row->pr_type
] = array();
2802 isset( $pagerestrictions[$row->pr_type
] )
2803 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2805 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2814 $this->mCascadeSources
= $sources;
2815 $this->mCascadingRestrictions
= $pagerestrictions;
2817 $this->mHasCascadingRestrictions
= $sources;
2820 return array( $sources, $pagerestrictions );
2824 * Accessor for mRestrictionsLoaded
2826 * @return bool Whether or not the page's restrictions have already been
2827 * loaded from the database
2830 public function areRestrictionsLoaded() {
2831 return $this->mRestrictionsLoaded
;
2835 * Accessor/initialisation for mRestrictions
2837 * @param string $action Action that permission needs to be checked for
2838 * @return array Restriction levels needed to take the action. All levels are
2839 * required. Note that restriction levels are normally user rights, but 'sysop'
2840 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2841 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2843 public function getRestrictions( $action ) {
2844 if ( !$this->mRestrictionsLoaded
) {
2845 $this->loadRestrictions();
2847 return isset( $this->mRestrictions
[$action] )
2848 ?
$this->mRestrictions
[$action]
2853 * Accessor/initialisation for mRestrictions
2855 * @return array Keys are actions, values are arrays as returned by
2856 * Title::getRestrictions()
2859 public function getAllRestrictions() {
2860 if ( !$this->mRestrictionsLoaded
) {
2861 $this->loadRestrictions();
2863 return $this->mRestrictions
;
2867 * Get the expiry time for the restriction against a given action
2869 * @param string $action
2870 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2871 * or not protected at all, or false if the action is not recognised.
2873 public function getRestrictionExpiry( $action ) {
2874 if ( !$this->mRestrictionsLoaded
) {
2875 $this->loadRestrictions();
2877 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2881 * Returns cascading restrictions for the current article
2885 function areRestrictionsCascading() {
2886 if ( !$this->mRestrictionsLoaded
) {
2887 $this->loadRestrictions();
2890 return $this->mCascadeRestriction
;
2894 * Loads a string into mRestrictions array
2896 * @param ResultWrapper $res Resource restrictions as an SQL result.
2897 * @param string $oldFashionedRestrictions Comma-separated list of page
2898 * restrictions from page table (pre 1.10)
2900 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2903 foreach ( $res as $row ) {
2907 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2911 * Compiles list of active page restrictions from both page table (pre 1.10)
2912 * and page_restrictions table for this existing page.
2913 * Public for usage by LiquidThreads.
2915 * @param array $rows Array of db result objects
2916 * @param string $oldFashionedRestrictions Comma-separated list of page
2917 * restrictions from page table (pre 1.10)
2919 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2920 $dbr = wfGetDB( DB_SLAVE
);
2922 $restrictionTypes = $this->getRestrictionTypes();
2924 foreach ( $restrictionTypes as $type ) {
2925 $this->mRestrictions
[$type] = array();
2926 $this->mRestrictionsExpiry
[$type] = 'infinity';
2929 $this->mCascadeRestriction
= false;
2931 # Backwards-compatibility: also load the restrictions from the page record (old format).
2932 if ( $oldFashionedRestrictions !== null ) {
2933 $this->mOldRestrictions
= $oldFashionedRestrictions;
2936 if ( $this->mOldRestrictions
=== false ) {
2937 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2938 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2941 if ( $this->mOldRestrictions
!= '' ) {
2942 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2943 $temp = explode( '=', trim( $restrict ) );
2944 if ( count( $temp ) == 1 ) {
2945 // old old format should be treated as edit/move restriction
2946 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2947 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2949 $restriction = trim( $temp[1] );
2950 if ( $restriction != '' ) { // some old entries are empty
2951 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2957 if ( count( $rows ) ) {
2958 # Current system - load second to make them override.
2959 $now = wfTimestampNow();
2961 # Cycle through all the restrictions.
2962 foreach ( $rows as $row ) {
2964 // Don't take care of restrictions types that aren't allowed
2965 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2969 // This code should be refactored, now that it's being used more generally,
2970 // But I don't really see any harm in leaving it in Block for now -werdna
2971 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2973 // Only apply the restrictions if they haven't expired!
2974 if ( !$expiry ||
$expiry > $now ) {
2975 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2976 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2978 $this->mCascadeRestriction |
= $row->pr_cascade
;
2983 $this->mRestrictionsLoaded
= true;
2987 * Load restrictions from the page_restrictions table
2989 * @param string $oldFashionedRestrictions Comma-separated list of page
2990 * restrictions from page table (pre 1.10)
2992 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2993 if ( !$this->mRestrictionsLoaded
) {
2994 $dbr = wfGetDB( DB_SLAVE
);
2995 if ( $this->exists() ) {
2996 $res = $dbr->select(
2997 'page_restrictions',
2998 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2999 array( 'pr_page' => $this->getArticleID() ),
3003 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
3005 $title_protection = $this->getTitleProtection();
3007 if ( $title_protection ) {
3008 $now = wfTimestampNow();
3009 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
3011 if ( !$expiry ||
$expiry > $now ) {
3012 // Apply the restrictions
3013 $this->mRestrictionsExpiry
['create'] = $expiry;
3014 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
3015 } else { // Get rid of the old restrictions
3016 $this->mTitleProtection
= false;
3019 $this->mRestrictionsExpiry
['create'] = 'infinity';
3021 $this->mRestrictionsLoaded
= true;
3027 * Flush the protection cache in this object and force reload from the database.
3028 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3030 public function flushRestrictions() {
3031 $this->mRestrictionsLoaded
= false;
3032 $this->mTitleProtection
= null;
3036 * Purge expired restrictions from the page_restrictions table
3038 static function purgeExpiredRestrictions() {
3039 if ( wfReadOnly() ) {
3043 $method = __METHOD__
;
3044 $dbw = wfGetDB( DB_MASTER
);
3045 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3047 'page_restrictions',
3048 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3053 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3060 * Does this have subpages? (Warning, usually requires an extra DB query.)
3064 public function hasSubpages() {
3065 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3070 # We dynamically add a member variable for the purpose of this method
3071 # alone to cache the result. There's no point in having it hanging
3072 # around uninitialized in every Title object; therefore we only add it
3073 # if needed and don't declare it statically.
3074 if ( $this->mHasSubpages
=== null ) {
3075 $this->mHasSubpages
= false;
3076 $subpages = $this->getSubpages( 1 );
3077 if ( $subpages instanceof TitleArray
) {
3078 $this->mHasSubpages
= (bool)$subpages->count();
3082 return $this->mHasSubpages
;
3086 * Get all subpages of this page.
3088 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3089 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3090 * doesn't allow subpages
3092 public function getSubpages( $limit = -1 ) {
3093 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3097 $dbr = wfGetDB( DB_SLAVE
);
3098 $conds['page_namespace'] = $this->getNamespace();
3099 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3101 if ( $limit > -1 ) {
3102 $options['LIMIT'] = $limit;
3104 $this->mSubpages
= TitleArray
::newFromResult(
3105 $dbr->select( 'page',
3106 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3112 return $this->mSubpages
;
3116 * Is there a version of this page in the deletion archive?
3118 * @return int The number of archived revisions
3120 public function isDeleted() {
3121 if ( $this->getNamespace() < 0 ) {
3124 $dbr = wfGetDB( DB_SLAVE
);
3126 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3127 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3130 if ( $this->getNamespace() == NS_FILE
) {
3131 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3132 array( 'fa_name' => $this->getDBkey() ),
3141 * Is there a version of this page in the deletion archive?
3145 public function isDeletedQuick() {
3146 if ( $this->getNamespace() < 0 ) {
3149 $dbr = wfGetDB( DB_SLAVE
);
3150 $deleted = (bool)$dbr->selectField( 'archive', '1',
3151 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3154 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3155 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3156 array( 'fa_name' => $this->getDBkey() ),
3164 * Get the article ID for this Title from the link cache,
3165 * adding it if necessary
3167 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3169 * @return int The ID
3171 public function getArticleID( $flags = 0 ) {
3172 if ( $this->getNamespace() < 0 ) {
3173 $this->mArticleID
= 0;
3174 return $this->mArticleID
;
3176 $linkCache = LinkCache
::singleton();
3177 if ( $flags & self
::GAID_FOR_UPDATE
) {
3178 $oldUpdate = $linkCache->forUpdate( true );
3179 $linkCache->clearLink( $this );
3180 $this->mArticleID
= $linkCache->addLinkObj( $this );
3181 $linkCache->forUpdate( $oldUpdate );
3183 if ( -1 == $this->mArticleID
) {
3184 $this->mArticleID
= $linkCache->addLinkObj( $this );
3187 return $this->mArticleID
;
3191 * Is this an article that is a redirect page?
3192 * Uses link cache, adding it if necessary
3194 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3197 public function isRedirect( $flags = 0 ) {
3198 if ( !is_null( $this->mRedirect
) ) {
3199 return $this->mRedirect
;
3201 if ( !$this->getArticleID( $flags ) ) {
3202 $this->mRedirect
= false;
3203 return $this->mRedirect
;
3206 $linkCache = LinkCache
::singleton();
3207 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3208 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3209 if ( $cached === null ) {
3210 # Trust LinkCache's state over our own
3211 # LinkCache is telling us that the page doesn't exist, despite there being cached
3212 # data relating to an existing page in $this->mArticleID. Updaters should clear
3213 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3214 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3215 # LinkCache to refresh its data from the master.
3216 $this->mRedirect
= false;
3217 return $this->mRedirect
;
3220 $this->mRedirect
= (bool)$cached;
3222 return $this->mRedirect
;
3226 * What is the length of this page?
3227 * Uses link cache, adding it if necessary
3229 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3232 public function getLength( $flags = 0 ) {
3233 if ( $this->mLength
!= -1 ) {
3234 return $this->mLength
;
3236 if ( !$this->getArticleID( $flags ) ) {
3238 return $this->mLength
;
3240 $linkCache = LinkCache
::singleton();
3241 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3242 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3243 if ( $cached === null ) {
3244 # Trust LinkCache's state over our own, as for isRedirect()
3246 return $this->mLength
;
3249 $this->mLength
= intval( $cached );
3251 return $this->mLength
;
3255 * What is the page_latest field for this page?
3257 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3258 * @return int Int or 0 if the page doesn't exist
3260 public function getLatestRevID( $flags = 0 ) {
3261 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3262 return intval( $this->mLatestID
);
3264 if ( !$this->getArticleID( $flags ) ) {
3265 $this->mLatestID
= 0;
3266 return $this->mLatestID
;
3268 $linkCache = LinkCache
::singleton();
3269 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3270 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3271 if ( $cached === null ) {
3272 # Trust LinkCache's state over our own, as for isRedirect()
3273 $this->mLatestID
= 0;
3274 return $this->mLatestID
;
3277 $this->mLatestID
= intval( $cached );
3279 return $this->mLatestID
;
3283 * This clears some fields in this object, and clears any associated
3284 * keys in the "bad links" section of the link cache.
3286 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3287 * loading of the new page_id. It's also called from
3288 * WikiPage::doDeleteArticleReal()
3290 * @param int $newid The new Article ID
3292 public function resetArticleID( $newid ) {
3293 $linkCache = LinkCache
::singleton();
3294 $linkCache->clearLink( $this );
3296 if ( $newid === false ) {
3297 $this->mArticleID
= -1;
3299 $this->mArticleID
= intval( $newid );
3301 $this->mRestrictionsLoaded
= false;
3302 $this->mRestrictions
= array();
3303 $this->mOldRestrictions
= false;
3304 $this->mRedirect
= null;
3305 $this->mLength
= -1;
3306 $this->mLatestID
= false;
3307 $this->mContentModel
= false;
3308 $this->mEstimateRevisions
= null;
3309 $this->mPageLanguage
= false;
3310 $this->mDbPageLanguage
= null;
3311 $this->mIsBigDeletion
= null;
3314 public static function clearCaches() {
3315 $linkCache = LinkCache
::singleton();
3316 $linkCache->clear();
3318 $titleCache = self
::getTitleCache();
3319 $titleCache->clear();
3323 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3325 * @param string $text Containing title to capitalize
3326 * @param int $ns Namespace index, defaults to NS_MAIN
3327 * @return string Containing capitalized title
3329 public static function capitalize( $text, $ns = NS_MAIN
) {
3332 if ( MWNamespace
::isCapitalized( $ns ) ) {
3333 return $wgContLang->ucfirst( $text );
3340 * Secure and split - main initialisation function for this object
3342 * Assumes that mDbkeyform has been set, and is urldecoded
3343 * and uses underscores, but not otherwise munged. This function
3344 * removes illegal characters, splits off the interwiki and
3345 * namespace prefixes, sets the other forms, and canonicalizes
3348 * @throws MalformedTitleException On invalid titles
3349 * @return bool True on success
3351 private function secureAndSplit() {
3353 $this->mInterwiki
= '';
3354 $this->mFragment
= '';
3355 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3357 $dbkey = $this->mDbkeyform
;
3359 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3360 // the parsing code with Title, while avoiding massive refactoring.
3361 // @todo: get rid of secureAndSplit, refactor parsing code.
3362 $titleParser = self
::getTitleParser();
3363 // MalformedTitleException can be thrown here
3364 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3367 $this->setFragment( '#' . $parts['fragment'] );
3368 $this->mInterwiki
= $parts['interwiki'];
3369 $this->mLocalInterwiki
= $parts['local_interwiki'];
3370 $this->mNamespace
= $parts['namespace'];
3371 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3373 $this->mDbkeyform
= $parts['dbkey'];
3374 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3375 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3377 # We already know that some pages won't be in the database!
3378 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3379 $this->mArticleID
= 0;
3386 * Get an array of Title objects linking to this Title
3387 * Also stores the IDs in the link cache.
3389 * WARNING: do not use this function on arbitrary user-supplied titles!
3390 * On heavily-used templates it will max out the memory.
3392 * @param array $options May be FOR UPDATE
3393 * @param string $table Table name
3394 * @param string $prefix Fields prefix
3395 * @return Title[] Array of Title objects linking here
3397 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3398 if ( count( $options ) > 0 ) {
3399 $db = wfGetDB( DB_MASTER
);
3401 $db = wfGetDB( DB_SLAVE
);
3405 array( 'page', $table ),
3406 self
::getSelectFields(),
3408 "{$prefix}_from=page_id",
3409 "{$prefix}_namespace" => $this->getNamespace(),
3410 "{$prefix}_title" => $this->getDBkey() ),
3416 if ( $res->numRows() ) {
3417 $linkCache = LinkCache
::singleton();
3418 foreach ( $res as $row ) {
3419 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3421 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3422 $retVal[] = $titleObj;
3430 * Get an array of Title objects using this Title as a template
3431 * Also stores the IDs in the link cache.
3433 * WARNING: do not use this function on arbitrary user-supplied titles!
3434 * On heavily-used templates it will max out the memory.
3436 * @param array $options May be FOR UPDATE
3437 * @return Title[] Array of Title the Title objects linking here
3439 public function getTemplateLinksTo( $options = array() ) {
3440 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3444 * Get an array of Title objects linked from this Title
3445 * Also stores the IDs in the link cache.
3447 * WARNING: do not use this function on arbitrary user-supplied titles!
3448 * On heavily-used templates it will max out the memory.
3450 * @param array $options May be FOR UPDATE
3451 * @param string $table Table name
3452 * @param string $prefix Fields prefix
3453 * @return array Array of Title objects linking here
3455 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3456 $id = $this->getArticleID();
3458 # If the page doesn't exist; there can't be any link from this page
3463 if ( count( $options ) > 0 ) {
3464 $db = wfGetDB( DB_MASTER
);
3466 $db = wfGetDB( DB_SLAVE
);
3469 $blNamespace = "{$prefix}_namespace";
3470 $blTitle = "{$prefix}_title";
3473 array( $table, 'page' ),
3475 array( $blNamespace, $blTitle ),
3476 WikiPage
::selectFields()
3478 array( "{$prefix}_from" => $id ),
3481 array( 'page' => array(
3483 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3488 $linkCache = LinkCache
::singleton();
3489 foreach ( $res as $row ) {
3490 if ( $row->page_id
) {
3491 $titleObj = Title
::newFromRow( $row );
3493 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3494 $linkCache->addBadLinkObj( $titleObj );
3496 $retVal[] = $titleObj;
3503 * Get an array of Title objects used on this Title as a template
3504 * Also stores the IDs in the link cache.
3506 * WARNING: do not use this function on arbitrary user-supplied titles!
3507 * On heavily-used templates it will max out the memory.
3509 * @param array $options May be FOR UPDATE
3510 * @return Title[] Array of Title the Title objects used here
3512 public function getTemplateLinksFrom( $options = array() ) {
3513 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3517 * Get an array of Title objects referring to non-existent articles linked
3520 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3521 * should use redirect table in this case).
3522 * @return Title[] Array of Title the Title objects
3524 public function getBrokenLinksFrom() {
3525 if ( $this->getArticleID() == 0 ) {
3526 # All links from article ID 0 are false positives
3530 $dbr = wfGetDB( DB_SLAVE
);
3531 $res = $dbr->select(
3532 array( 'page', 'pagelinks' ),
3533 array( 'pl_namespace', 'pl_title' ),
3535 'pl_from' => $this->getArticleID(),
3536 'page_namespace IS NULL'
3538 __METHOD__
, array(),
3542 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3548 foreach ( $res as $row ) {
3549 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3555 * Get a list of URLs to purge from the Squid cache when this
3558 * @return string[] Array of String the URLs
3560 public function getSquidURLs() {
3562 $this->getInternalURL(),
3563 $this->getInternalURL( 'action=history' )
3566 $pageLang = $this->getPageLanguage();
3567 if ( $pageLang->hasVariants() ) {
3568 $variants = $pageLang->getVariants();
3569 foreach ( $variants as $vCode ) {
3570 $urls[] = $this->getInternalURL( '', $vCode );
3574 // If we are looking at a css/js user subpage, purge the action=raw.
3575 if ( $this->isJsSubpage() ) {
3576 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3577 } elseif ( $this->isCssSubpage() ) {
3578 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3581 Hooks
::run( 'TitleSquidURLs', array( $this, &$urls ) );
3586 * Purge all applicable Squid URLs
3588 public function purgeSquid() {
3590 if ( $wgUseSquid ) {
3591 $urls = $this->getSquidURLs();
3592 $u = new SquidUpdate( $urls );
3598 * Move this page without authentication
3600 * @deprecated since 1.25 use MovePage class instead
3601 * @param Title $nt The new page Title
3602 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3604 public function moveNoAuth( &$nt ) {
3605 wfDeprecated( __METHOD__
, '1.25' );
3606 return $this->moveTo( $nt, false );
3610 * Check whether a given move operation would be valid.
3611 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3613 * @deprecated since 1.25, use MovePage's methods instead
3614 * @param Title $nt The new title
3615 * @param bool $auth Whether to check user permissions (uses $wgUser)
3616 * @param string $reason Is the log summary of the move, used for spam checking
3617 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3619 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3622 if ( !( $nt instanceof Title
) ) {
3623 // Normally we'd add this to $errors, but we'll get
3624 // lots of syntax errors if $nt is not an object
3625 return array( array( 'badtitletext' ) );
3628 $mp = new MovePage( $this, $nt );
3629 $errors = $mp->isValidMove()->getErrorsArray();
3631 $errors = wfMergeErrorArrays(
3633 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3637 return $errors ?
: true;
3641 * Check if the requested move target is a valid file move target
3642 * @todo move this to MovePage
3643 * @param Title $nt Target title
3644 * @return array List of errors
3646 protected function validateFileMoveOperation( $nt ) {
3651 $destFile = wfLocalFile( $nt );
3652 $destFile->load( File
::READ_LATEST
);
3653 if ( !$wgUser->isAllowed( 'reupload-shared' )
3654 && !$destFile->exists() && wfFindFile( $nt )
3656 $errors[] = array( 'file-exists-sharedrepo' );
3663 * Move a title to a new location
3665 * @deprecated since 1.25, use the MovePage class instead
3666 * @param Title $nt The new title
3667 * @param bool $auth Indicates whether $wgUser's permissions
3669 * @param string $reason The reason for the move
3670 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3671 * Ignored if the user doesn't have the suppressredirect right.
3672 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3674 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3676 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3677 if ( is_array( $err ) ) {
3678 // Auto-block user's IP if the account was "hard" blocked
3679 $wgUser->spreadAnyEditBlock();
3682 // Check suppressredirect permission
3683 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3684 $createRedirect = true;
3687 $mp = new MovePage( $this, $nt );
3688 $status = $mp->move( $wgUser, $reason, $createRedirect );
3689 if ( $status->isOK() ) {
3692 return $status->getErrorsArray();
3697 * Move this page's subpages to be subpages of $nt
3699 * @param Title $nt Move target
3700 * @param bool $auth Whether $wgUser's permissions should be checked
3701 * @param string $reason The reason for the move
3702 * @param bool $createRedirect Whether to create redirects from the old subpages to
3703 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3704 * @return array Array with old page titles as keys, and strings (new page titles) or
3705 * arrays (errors) as values, or an error array with numeric indices if no pages
3708 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3709 global $wgMaximumMovedPages;
3710 // Check permissions
3711 if ( !$this->userCan( 'move-subpages' ) ) {
3712 return array( 'cant-move-subpages' );
3714 // Do the source and target namespaces support subpages?
3715 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3716 return array( 'namespace-nosubpages',
3717 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3719 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3720 return array( 'namespace-nosubpages',
3721 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3724 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3727 foreach ( $subpages as $oldSubpage ) {
3729 if ( $count > $wgMaximumMovedPages ) {
3730 $retval[$oldSubpage->getPrefixedText()] =
3731 array( 'movepage-max-pages',
3732 $wgMaximumMovedPages );
3736 // We don't know whether this function was called before
3737 // or after moving the root page, so check both
3739 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3740 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3742 // When moving a page to a subpage of itself,
3743 // don't move it twice
3746 $newPageName = preg_replace(
3747 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3748 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3749 $oldSubpage->getDBkey() );
3750 if ( $oldSubpage->isTalkPage() ) {
3751 $newNs = $nt->getTalkPage()->getNamespace();
3753 $newNs = $nt->getSubjectPage()->getNamespace();
3755 # Bug 14385: we need makeTitleSafe because the new page names may
3756 # be longer than 255 characters.
3757 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3759 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3760 if ( $success === true ) {
3761 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3763 $retval[$oldSubpage->getPrefixedText()] = $success;
3770 * Checks if this page is just a one-rev redirect.
3771 * Adds lock, so don't use just for light purposes.
3775 public function isSingleRevRedirect() {
3776 global $wgContentHandlerUseDB;
3778 $dbw = wfGetDB( DB_MASTER
);
3781 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3782 if ( $wgContentHandlerUseDB ) {
3783 $fields[] = 'page_content_model';
3786 $row = $dbw->selectRow( 'page',
3790 array( 'FOR UPDATE' )
3792 # Cache some fields we may want
3793 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3794 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3795 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3796 $this->mContentModel
= $row && isset( $row->page_content_model
)
3797 ?
strval( $row->page_content_model
)
3800 if ( !$this->mRedirect
) {
3803 # Does the article have a history?
3804 $row = $dbw->selectField( array( 'page', 'revision' ),
3806 array( 'page_namespace' => $this->getNamespace(),
3807 'page_title' => $this->getDBkey(),
3809 'page_latest != rev_id'
3812 array( 'FOR UPDATE' )
3814 # Return true if there was no history
3815 return ( $row === false );
3819 * Checks if $this can be moved to a given Title
3820 * - Selects for update, so don't call it unless you mean business
3822 * @deprecated since 1.25, use MovePage's methods instead
3823 * @param Title $nt The new title to check
3826 public function isValidMoveTarget( $nt ) {
3827 # Is it an existing file?
3828 if ( $nt->getNamespace() == NS_FILE
) {
3829 $file = wfLocalFile( $nt );
3830 $file->load( File
::READ_LATEST
);
3831 if ( $file->exists() ) {
3832 wfDebug( __METHOD__
. ": file exists\n" );
3836 # Is it a redirect with no history?
3837 if ( !$nt->isSingleRevRedirect() ) {
3838 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3841 # Get the article text
3842 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3843 if ( !is_object( $rev ) ) {
3846 $content = $rev->getContent();
3847 # Does the redirect point to the source?
3848 # Or is it a broken self-redirect, usually caused by namespace collisions?
3849 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3851 if ( $redirTitle ) {
3852 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3853 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3854 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3860 # Fail safe (not a redirect after all. strange.)
3861 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3862 " is a redirect, but it doesn't contain a valid redirect.\n" );
3868 * Get categories to which this Title belongs and return an array of
3869 * categories' names.
3871 * @return array Array of parents in the form:
3872 * $parent => $currentarticle
3874 public function getParentCategories() {
3879 $titleKey = $this->getArticleID();
3881 if ( $titleKey === 0 ) {
3885 $dbr = wfGetDB( DB_SLAVE
);
3887 $res = $dbr->select(
3890 array( 'cl_from' => $titleKey ),
3894 if ( $res->numRows() > 0 ) {
3895 foreach ( $res as $row ) {
3896 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3897 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3904 * Get a tree of parent categories
3906 * @param array $children Array with the children in the keys, to check for circular refs
3907 * @return array Tree of parent categories
3909 public function getParentCategoryTree( $children = array() ) {
3911 $parents = $this->getParentCategories();
3914 foreach ( $parents as $parent => $current ) {
3915 if ( array_key_exists( $parent, $children ) ) {
3916 # Circular reference
3917 $stack[$parent] = array();
3919 $nt = Title
::newFromText( $parent );
3921 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3931 * Get an associative array for selecting this title from
3934 * @return array Array suitable for the $where parameter of DB::select()
3936 public function pageCond() {
3937 if ( $this->mArticleID
> 0 ) {
3938 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3939 return array( 'page_id' => $this->mArticleID
);
3941 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3946 * Get the revision ID of the previous revision
3948 * @param int $revId Revision ID. Get the revision that was before this one.
3949 * @param int $flags Title::GAID_FOR_UPDATE
3950 * @return int|bool Old revision ID, or false if none exists
3952 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3953 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3954 $revId = $db->selectField( 'revision', 'rev_id',
3956 'rev_page' => $this->getArticleID( $flags ),
3957 'rev_id < ' . intval( $revId )
3960 array( 'ORDER BY' => 'rev_id DESC' )
3963 if ( $revId === false ) {
3966 return intval( $revId );
3971 * Get the revision ID of the next revision
3973 * @param int $revId Revision ID. Get the revision that was after this one.
3974 * @param int $flags Title::GAID_FOR_UPDATE
3975 * @return int|bool Next revision ID, or false if none exists
3977 public function getNextRevisionID( $revId, $flags = 0 ) {
3978 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3979 $revId = $db->selectField( 'revision', 'rev_id',
3981 'rev_page' => $this->getArticleID( $flags ),
3982 'rev_id > ' . intval( $revId )
3985 array( 'ORDER BY' => 'rev_id' )
3988 if ( $revId === false ) {
3991 return intval( $revId );
3996 * Get the first revision of the page
3998 * @param int $flags Title::GAID_FOR_UPDATE
3999 * @return Revision|null If page doesn't exist
4001 public function getFirstRevision( $flags = 0 ) {
4002 $pageId = $this->getArticleID( $flags );
4004 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4005 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4006 array( 'rev_page' => $pageId ),
4008 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4011 return new Revision( $row );
4018 * Get the oldest revision timestamp of this page
4020 * @param int $flags Title::GAID_FOR_UPDATE
4021 * @return string MW timestamp
4023 public function getEarliestRevTime( $flags = 0 ) {
4024 $rev = $this->getFirstRevision( $flags );
4025 return $rev ?
$rev->getTimestamp() : null;
4029 * Check if this is a new page
4033 public function isNewPage() {
4034 $dbr = wfGetDB( DB_SLAVE
);
4035 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4039 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4043 public function isBigDeletion() {
4044 global $wgDeleteRevisionsLimit;
4046 if ( !$wgDeleteRevisionsLimit ) {
4050 if ( $this->mIsBigDeletion
=== null ) {
4051 $dbr = wfGetDB( DB_SLAVE
);
4053 $revCount = $dbr->selectRowCount(
4056 array( 'rev_page' => $this->getArticleID() ),
4058 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4061 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4064 return $this->mIsBigDeletion
;
4068 * Get the approximate revision count of this page.
4072 public function estimateRevisionCount() {
4073 if ( !$this->exists() ) {
4077 if ( $this->mEstimateRevisions
=== null ) {
4078 $dbr = wfGetDB( DB_SLAVE
);
4079 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4080 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4083 return $this->mEstimateRevisions
;
4087 * Get the number of revisions between the given revision.
4088 * Used for diffs and other things that really need it.
4090 * @param int|Revision $old Old revision or rev ID (first before range)
4091 * @param int|Revision $new New revision or rev ID (first after range)
4092 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4093 * @return int Number of revisions between these revisions.
4095 public function countRevisionsBetween( $old, $new, $max = null ) {
4096 if ( !( $old instanceof Revision
) ) {
4097 $old = Revision
::newFromTitle( $this, (int)$old );
4099 if ( !( $new instanceof Revision
) ) {
4100 $new = Revision
::newFromTitle( $this, (int)$new );
4102 if ( !$old ||
!$new ) {
4103 return 0; // nothing to compare
4105 $dbr = wfGetDB( DB_SLAVE
);
4107 'rev_page' => $this->getArticleID(),
4108 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4109 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4111 if ( $max !== null ) {
4112 return $dbr->selectRowCount( 'revision', '1',
4115 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4118 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4123 * Get the authors between the given revisions or revision IDs.
4124 * Used for diffs and other things that really need it.
4128 * @param int|Revision $old Old revision or rev ID (first before range by default)
4129 * @param int|Revision $new New revision or rev ID (first after range by default)
4130 * @param int $limit Maximum number of authors
4131 * @param string|array $options (Optional): Single option, or an array of options:
4132 * 'include_old' Include $old in the range; $new is excluded.
4133 * 'include_new' Include $new in the range; $old is excluded.
4134 * 'include_both' Include both $old and $new in the range.
4135 * Unknown option values are ignored.
4136 * @return array|null Names of revision authors in the range; null if not both revisions exist
4138 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4139 if ( !( $old instanceof Revision
) ) {
4140 $old = Revision
::newFromTitle( $this, (int)$old );
4142 if ( !( $new instanceof Revision
) ) {
4143 $new = Revision
::newFromTitle( $this, (int)$new );
4145 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4146 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4147 // in the sanity check below?
4148 if ( !$old ||
!$new ) {
4149 return null; // nothing to compare
4154 $options = (array)$options;
4155 if ( in_array( 'include_old', $options ) ) {
4158 if ( in_array( 'include_new', $options ) ) {
4161 if ( in_array( 'include_both', $options ) ) {
4165 // No DB query needed if $old and $new are the same or successive revisions:
4166 if ( $old->getId() === $new->getId() ) {
4167 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4169 array( $old->getUserText( Revision
::RAW
) );
4170 } elseif ( $old->getId() === $new->getParentId() ) {
4171 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4172 $authors[] = $old->getUserText( Revision
::RAW
);
4173 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4174 $authors[] = $new->getUserText( Revision
::RAW
);
4176 } elseif ( $old_cmp === '>=' ) {
4177 $authors[] = $old->getUserText( Revision
::RAW
);
4178 } elseif ( $new_cmp === '<=' ) {
4179 $authors[] = $new->getUserText( Revision
::RAW
);
4183 $dbr = wfGetDB( DB_SLAVE
);
4184 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4186 'rev_page' => $this->getArticleID(),
4187 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4188 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4190 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4192 foreach ( $res as $row ) {
4193 $authors[] = $row->rev_user_text
;
4199 * Get the number of authors between the given revisions or revision IDs.
4200 * Used for diffs and other things that really need it.
4202 * @param int|Revision $old Old revision or rev ID (first before range by default)
4203 * @param int|Revision $new New revision or rev ID (first after range by default)
4204 * @param int $limit Maximum number of authors
4205 * @param string|array $options (Optional): Single option, or an array of options:
4206 * 'include_old' Include $old in the range; $new is excluded.
4207 * 'include_new' Include $new in the range; $old is excluded.
4208 * 'include_both' Include both $old and $new in the range.
4209 * Unknown option values are ignored.
4210 * @return int Number of revision authors in the range; zero if not both revisions exist
4212 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4213 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4214 return $authors ?
count( $authors ) : 0;
4218 * Compare with another title.
4220 * @param Title $title
4223 public function equals( Title
$title ) {
4224 // Note: === is necessary for proper matching of number-like titles.
4225 return $this->getInterwiki() === $title->getInterwiki()
4226 && $this->getNamespace() == $title->getNamespace()
4227 && $this->getDBkey() === $title->getDBkey();
4231 * Check if this title is a subpage of another title
4233 * @param Title $title
4236 public function isSubpageOf( Title
$title ) {
4237 return $this->getInterwiki() === $title->getInterwiki()
4238 && $this->getNamespace() == $title->getNamespace()
4239 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4243 * Check if page exists. For historical reasons, this function simply
4244 * checks for the existence of the title in the page table, and will
4245 * thus return false for interwiki links, special pages and the like.
4246 * If you want to know if a title can be meaningfully viewed, you should
4247 * probably call the isKnown() method instead.
4249 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4250 * from master/for update
4253 public function exists( $flags = 0 ) {
4254 $exists = $this->getArticleID( $flags ) != 0;
4255 Hooks
::run( 'TitleExists', array( $this, &$exists ) );
4260 * Should links to this title be shown as potentially viewable (i.e. as
4261 * "bluelinks"), even if there's no record by this title in the page
4264 * This function is semi-deprecated for public use, as well as somewhat
4265 * misleadingly named. You probably just want to call isKnown(), which
4266 * calls this function internally.
4268 * (ISSUE: Most of these checks are cheap, but the file existence check
4269 * can potentially be quite expensive. Including it here fixes a lot of
4270 * existing code, but we might want to add an optional parameter to skip
4271 * it and any other expensive checks.)
4275 public function isAlwaysKnown() {
4279 * Allows overriding default behavior for determining if a page exists.
4280 * If $isKnown is kept as null, regular checks happen. If it's
4281 * a boolean, this value is returned by the isKnown method.
4285 * @param Title $title
4286 * @param bool|null $isKnown
4288 Hooks
::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4290 if ( !is_null( $isKnown ) ) {
4294 if ( $this->isExternal() ) {
4295 return true; // any interwiki link might be viewable, for all we know
4298 switch ( $this->mNamespace
) {
4301 // file exists, possibly in a foreign repo
4302 return (bool)wfFindFile( $this );
4304 // valid special page
4305 return SpecialPageFactory
::exists( $this->getDBkey() );
4307 // selflink, possibly with fragment
4308 return $this->mDbkeyform
== '';
4310 // known system message
4311 return $this->hasSourceText() !== false;
4318 * Does this title refer to a page that can (or might) be meaningfully
4319 * viewed? In particular, this function may be used to determine if
4320 * links to the title should be rendered as "bluelinks" (as opposed to
4321 * "redlinks" to non-existent pages).
4322 * Adding something else to this function will cause inconsistency
4323 * since LinkHolderArray calls isAlwaysKnown() and does its own
4324 * page existence check.
4328 public function isKnown() {
4329 return $this->isAlwaysKnown() ||
$this->exists();
4333 * Does this page have source text?
4337 public function hasSourceText() {
4338 if ( $this->exists() ) {
4342 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4343 // If the page doesn't exist but is a known system message, default
4344 // message content will be displayed, same for language subpages-
4345 // Use always content language to avoid loading hundreds of languages
4346 // to get the link color.
4348 list( $name, ) = MessageCache
::singleton()->figureMessage(
4349 $wgContLang->lcfirst( $this->getText() )
4351 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4352 return $message->exists();
4359 * Get the default message text or false if the message doesn't exist
4361 * @return string|bool
4363 public function getDefaultMessageText() {
4366 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4370 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4371 $wgContLang->lcfirst( $this->getText() )
4373 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4375 if ( $message->exists() ) {
4376 return $message->plain();
4383 * Updates page_touched for this page; called from LinksUpdate.php
4385 * @param string $purgeTime [optional] TS_MW timestamp
4386 * @return bool True if the update succeeded
4388 public function invalidateCache( $purgeTime = null ) {
4389 if ( wfReadOnly() ) {
4393 if ( $this->mArticleID
=== 0 ) {
4394 return true; // avoid gap locking if we know it's not there
4397 $method = __METHOD__
;
4398 $dbw = wfGetDB( DB_MASTER
);
4399 $conds = $this->pageCond();
4400 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4401 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4405 array( 'page_touched' => $dbTimestamp ),
4406 $conds +
array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4415 * Update page_touched timestamps and send squid purge messages for
4416 * pages linking to this title. May be sent to the job queue depending
4417 * on the number of links. Typically called on create and delete.
4419 public function touchLinks() {
4420 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4421 if ( $this->getNamespace() == NS_CATEGORY
) {
4422 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4427 * Get the last touched timestamp
4429 * @param IDatabase $db Optional db
4430 * @return string Last-touched timestamp
4432 public function getTouched( $db = null ) {
4433 if ( $db === null ) {
4434 $db = wfGetDB( DB_SLAVE
);
4436 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4441 * Get the timestamp when this page was updated since the user last saw it.
4444 * @return string|null
4446 public function getNotificationTimestamp( $user = null ) {
4449 // Assume current user if none given
4453 // Check cache first
4454 $uid = $user->getId();
4458 // avoid isset here, as it'll return false for null entries
4459 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4460 return $this->mNotificationTimestamp
[$uid];
4462 // Don't cache too much!
4463 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4464 $this->mNotificationTimestamp
= array();
4467 $watchedItem = WatchedItem
::fromUserTitle( $user, $this );
4468 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4470 return $this->mNotificationTimestamp
[$uid];
4474 * Generate strings used for xml 'id' names in monobook tabs
4476 * @param string $prepend Defaults to 'nstab-'
4477 * @return string XML 'id' name
4479 public function getNamespaceKey( $prepend = 'nstab-' ) {
4481 // Gets the subject namespace if this title
4482 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4483 // Checks if canonical namespace name exists for namespace
4484 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4485 // Uses canonical namespace name
4486 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4488 // Uses text of namespace
4489 $namespaceKey = $this->getSubjectNsText();
4491 // Makes namespace key lowercase
4492 $namespaceKey = $wgContLang->lc( $namespaceKey );
4494 if ( $namespaceKey == '' ) {
4495 $namespaceKey = 'main';
4497 // Changes file to image for backwards compatibility
4498 if ( $namespaceKey == 'file' ) {
4499 $namespaceKey = 'image';
4501 return $prepend . $namespaceKey;
4505 * Get all extant redirects to this Title
4507 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4508 * @return Title[] Array of Title redirects to this title
4510 public function getRedirectsHere( $ns = null ) {
4513 $dbr = wfGetDB( DB_SLAVE
);
4515 'rd_namespace' => $this->getNamespace(),
4516 'rd_title' => $this->getDBkey(),
4519 if ( $this->isExternal() ) {
4520 $where['rd_interwiki'] = $this->getInterwiki();
4522 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4524 if ( !is_null( $ns ) ) {
4525 $where['page_namespace'] = $ns;
4528 $res = $dbr->select(
4529 array( 'redirect', 'page' ),
4530 array( 'page_namespace', 'page_title' ),
4535 foreach ( $res as $row ) {
4536 $redirs[] = self
::newFromRow( $row );
4542 * Check if this Title is a valid redirect target
4546 public function isValidRedirectTarget() {
4547 global $wgInvalidRedirectTargets;
4549 if ( $this->isSpecialPage() ) {
4550 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4551 if ( $this->isSpecial( 'Userlogout' ) ) {
4555 foreach ( $wgInvalidRedirectTargets as $target ) {
4556 if ( $this->isSpecial( $target ) ) {
4566 * Get a backlink cache object
4568 * @return BacklinkCache
4570 public function getBacklinkCache() {
4571 return BacklinkCache
::get( $this );
4575 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4579 public function canUseNoindex() {
4580 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4582 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4583 ?
$wgContentNamespaces
4584 : $wgExemptFromUserRobotsControl;
4586 return !in_array( $this->mNamespace
, $bannedNamespaces );
4591 * Returns the raw sort key to be used for categories, with the specified
4592 * prefix. This will be fed to Collation::getSortKey() to get a
4593 * binary sortkey that can be used for actual sorting.
4595 * @param string $prefix The prefix to be used, specified using
4596 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4600 public function getCategorySortkey( $prefix = '' ) {
4601 $unprefixed = $this->getText();
4603 // Anything that uses this hook should only depend
4604 // on the Title object passed in, and should probably
4605 // tell the users to run updateCollations.php --force
4606 // in order to re-sort existing category relations.
4607 Hooks
::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4608 if ( $prefix !== '' ) {
4609 # Separate with a line feed, so the unprefixed part is only used as
4610 # a tiebreaker when two pages have the exact same prefix.
4611 # In UCA, tab is the only character that can sort above LF
4612 # so we strip both of them from the original prefix.
4613 $prefix = strtr( $prefix, "\n\t", ' ' );
4614 return "$prefix\n$unprefixed";
4620 * Get the language in which the content of this page is written in
4621 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4622 * e.g. $wgLang (such as special pages, which are in the user language).
4627 public function getPageLanguage() {
4628 global $wgLang, $wgLanguageCode;
4629 if ( $this->isSpecialPage() ) {
4630 // special pages are in the user language
4634 // Checking if DB language is set
4635 if ( $this->mDbPageLanguage
) {
4636 return wfGetLangObj( $this->mDbPageLanguage
);
4639 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4640 // Note that this may depend on user settings, so the cache should
4641 // be only per-request.
4642 // NOTE: ContentHandler::getPageLanguage() may need to load the
4643 // content to determine the page language!
4644 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4646 $contentHandler = ContentHandler
::getForTitle( $this );
4647 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4648 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4650 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4657 * Get the language in which the content of this page is written when
4658 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4659 * e.g. $wgLang (such as special pages, which are in the user language).
4664 public function getPageViewLanguage() {
4667 if ( $this->isSpecialPage() ) {
4668 // If the user chooses a variant, the content is actually
4669 // in a language whose code is the variant code.
4670 $variant = $wgLang->getPreferredVariant();
4671 if ( $wgLang->getCode() !== $variant ) {
4672 return Language
::factory( $variant );
4678 // @note Can't be cached persistently, depends on user settings.
4679 // @note ContentHandler::getPageViewLanguage() may need to load the
4680 // content to determine the page language!
4681 $contentHandler = ContentHandler
::getForTitle( $this );
4682 $pageLang = $contentHandler->getPageViewLanguage( $this );
4687 * Get a list of rendered edit notices for this page.
4689 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4690 * they will already be wrapped in paragraphs.
4693 * @param int $oldid Revision ID that's being edited
4696 public function getEditNotices( $oldid = 0 ) {
4699 // Optional notice for the entire namespace
4700 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4701 $msg = wfMessage( $editnotice_ns );
4702 if ( $msg->exists() ) {
4703 $html = $msg->parseAsBlock();
4704 // Edit notices may have complex logic, but output nothing (T91715)
4705 if ( trim( $html ) !== '' ) {
4706 $notices[$editnotice_ns] = Html
::rawElement(
4708 array( 'class' => array(
4710 'mw-editnotice-namespace',
4711 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4718 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4719 // Optional notice for page itself and any parent page
4720 $parts = explode( '/', $this->getDBkey() );
4721 $editnotice_base = $editnotice_ns;
4722 while ( count( $parts ) > 0 ) {
4723 $editnotice_base .= '-' . array_shift( $parts );
4724 $msg = wfMessage( $editnotice_base );
4725 if ( $msg->exists() ) {
4726 $html = $msg->parseAsBlock();
4727 if ( trim( $html ) !== '' ) {
4728 $notices[$editnotice_base] = Html
::rawElement(
4730 array( 'class' => array(
4732 'mw-editnotice-base',
4733 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4741 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4742 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4743 $msg = wfMessage( $editnoticeText );
4744 if ( $msg->exists() ) {
4745 $html = $msg->parseAsBlock();
4746 if ( trim( $html ) !== '' ) {
4747 $notices[$editnoticeText] = Html
::rawElement(
4749 array( 'class' => array(
4751 'mw-editnotice-page',
4752 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4760 Hooks
::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4767 public function __sleep() {
4775 'mDefaultNamespace',
4779 public function __wakeup() {
4780 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4781 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4782 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );