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 HashBagOStuff */
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
;
133 /** @var int The page length, 0 for special pages */
134 protected $mLength = -1;
136 /** @var null Is the article at this title a redirect? */
137 public $mRedirect = null;
139 /** @var array Associative array of user ID -> timestamp/false */
140 private $mNotificationTimestamp = array();
142 /** @var bool Whether a page has any subpages */
143 private $mHasSubpages;
145 /** @var bool The (string) language code of the page's language and content code. */
146 private $mPageLanguage = false;
148 /** @var string The page language code from the database */
149 private $mDbPageLanguage = null;
151 /** @var TitleValue A corresponding TitleValue object */
152 private $mTitleValue = null;
154 /** @var bool Would deleting this page be a big deletion? */
155 private $mIsBigDeletion = null;
159 * B/C kludge: provide a TitleParser for use by Title.
160 * Ideally, Title would have no methods that need this.
161 * Avoid usage of this singleton by using TitleValue
162 * and the associated services when possible.
164 * @return TitleParser
166 private static function getTitleParser() {
167 global $wgContLang, $wgLocalInterwikis;
169 static $titleCodec = null;
170 static $titleCodecFingerprint = null;
172 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
173 // make sure we are using the right one. To detect changes over the course
174 // of a request, we remember a fingerprint of the config used to create the
175 // codec singleton, and re-create it if the fingerprint doesn't match.
176 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
178 if ( $fingerprint !== $titleCodecFingerprint ) {
182 if ( !$titleCodec ) {
183 $titleCodec = new MediaWikiTitleCodec(
185 GenderCache
::singleton(),
188 $titleCodecFingerprint = $fingerprint;
195 * B/C kludge: provide a TitleParser for use by Title.
196 * Ideally, Title would have no methods that need this.
197 * Avoid usage of this singleton by using TitleValue
198 * and the associated services when possible.
200 * @return TitleFormatter
202 private static function getTitleFormatter() {
203 // NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
204 // which implements TitleFormatter.
205 return self
::getTitleParser();
208 function __construct() {
212 * Create a new Title from a prefixed DB key
214 * @param string $key The database key, which has underscores
215 * instead of spaces, possibly including namespace and
217 * @return Title|null Title, or null on an error
219 public static function newFromDBkey( $key ) {
221 $t->mDbkeyform
= $key;
224 $t->secureAndSplit();
226 } catch ( MalformedTitleException
$ex ) {
232 * Create a new Title from a TitleValue
234 * @param TitleValue $titleValue Assumed to be safe.
238 public static function newFromTitleValue( TitleValue
$titleValue ) {
239 return self
::makeTitle(
240 $titleValue->getNamespace(),
241 $titleValue->getText(),
242 $titleValue->getFragment() );
246 * Create a new Title from text, such as what one would find in a link. De-
247 * codes any HTML entities in the text.
249 * @param string|int|null $text The link text; spaces, prefixes, and an
250 * initial ':' indicating the main namespace are accepted.
251 * @param int $defaultNamespace The namespace to use if none is specified
252 * by a prefix. If you want to force a specific namespace even if
253 * $text might begin with a namespace prefix, use makeTitle() or
255 * @throws InvalidArgumentException
256 * @return Title|null Title or null on an error.
258 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
259 if ( is_object( $text ) ) {
260 throw new InvalidArgumentException( '$text must be a string.' );
262 // DWIM: Integers can be passed in here when page titles are used as array keys.
263 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
264 wfDebugLog( 'T76305', wfGetAllCallers( 5 ) );
267 if ( $text === null ) {
272 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
273 } catch ( MalformedTitleException
$ex ) {
279 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
280 * rather than returning null.
282 * The exception subclasses encode detailed information about why the title is invalid.
284 * @see Title::newFromText
287 * @param string $text Title text to check
288 * @param int $defaultNamespace
289 * @throws MalformedTitleException If the title is invalid
292 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
293 if ( is_object( $text ) ) {
294 throw new MWException( '$text must be a string, given an object' );
297 $titleCache = self
::getTitleCache();
299 // Wiki pages often contain multiple links to the same page.
300 // Title normalization and parsing can become expensive on pages with many
301 // links, so we can save a little time by caching them.
302 // In theory these are value objects and won't get changed...
303 if ( $defaultNamespace == NS_MAIN
) {
304 $t = $titleCache->get( $text );
310 // Convert things like é ā or 〗 into normalized (bug 14952) text
311 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
314 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
315 $t->mDefaultNamespace
= intval( $defaultNamespace );
317 $t->secureAndSplit();
318 if ( $defaultNamespace == NS_MAIN
) {
319 $titleCache->set( $text, $t );
325 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
327 * Example of wrong and broken code:
328 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
330 * Example of right code:
331 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
333 * Create a new Title from URL-encoded text. Ensures that
334 * the given title's length does not exceed the maximum.
336 * @param string $url The title, as might be taken from a URL
337 * @return Title|null The new object, or null on an error
339 public static function newFromURL( $url ) {
342 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
343 # but some URLs used it as a space replacement and they still come
344 # from some external search tools.
345 if ( strpos( self
::legalChars(), '+' ) === false ) {
346 $url = strtr( $url, '+', ' ' );
349 $t->mDbkeyform
= strtr( $url, ' ', '_' );
352 $t->secureAndSplit();
354 } catch ( MalformedTitleException
$ex ) {
360 * @return HashBagOStuff
362 private static function getTitleCache() {
363 if ( self
::$titleCache == null ) {
364 self
::$titleCache = new HashBagOStuff( array( 'maxKeys' => self
::CACHE_MAX
) );
366 return self
::$titleCache;
370 * Returns a list of fields that are to be selected for initializing Title
371 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
372 * whether to include page_content_model.
376 protected static function getSelectFields() {
377 global $wgContentHandlerUseDB;
380 'page_namespace', 'page_title', 'page_id',
381 'page_len', 'page_is_redirect', 'page_latest',
384 if ( $wgContentHandlerUseDB ) {
385 $fields[] = 'page_content_model';
392 * Create a new Title from an article ID
394 * @param int $id The page_id corresponding to the Title to create
395 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
396 * @return Title|null The new object, or null on an error
398 public static function newFromID( $id, $flags = 0 ) {
399 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
400 $row = $db->selectRow(
402 self
::getSelectFields(),
403 array( 'page_id' => $id ),
406 if ( $row !== false ) {
407 $title = Title
::newFromRow( $row );
415 * Make an array of titles from an array of IDs
417 * @param int[] $ids Array of IDs
418 * @return Title[] Array of Titles
420 public static function newFromIDs( $ids ) {
421 if ( !count( $ids ) ) {
424 $dbr = wfGetDB( DB_SLAVE
);
428 self
::getSelectFields(),
429 array( 'page_id' => $ids ),
434 foreach ( $res as $row ) {
435 $titles[] = Title
::newFromRow( $row );
441 * Make a Title object from a DB row
443 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
444 * @return Title Corresponding Title
446 public static function newFromRow( $row ) {
447 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
448 $t->loadFromRow( $row );
453 * Load Title object fields from a DB row.
454 * If false is given, the title will be treated as non-existing.
456 * @param stdClass|bool $row Database row
458 public function loadFromRow( $row ) {
459 if ( $row ) { // page found
460 if ( isset( $row->page_id
) ) {
461 $this->mArticleID
= (int)$row->page_id
;
463 if ( isset( $row->page_len
) ) {
464 $this->mLength
= (int)$row->page_len
;
466 if ( isset( $row->page_is_redirect
) ) {
467 $this->mRedirect
= (bool)$row->page_is_redirect
;
469 if ( isset( $row->page_latest
) ) {
470 $this->mLatestID
= (int)$row->page_latest
;
472 if ( isset( $row->page_content_model
) ) {
473 $this->mContentModel
= strval( $row->page_content_model
);
475 $this->mContentModel
= false; # initialized lazily in getContentModel()
477 if ( isset( $row->page_lang
) ) {
478 $this->mDbPageLanguage
= (string)$row->page_lang
;
480 if ( isset( $row->page_restrictions
) ) {
481 $this->mOldRestrictions
= $row->page_restrictions
;
483 } else { // page not found
484 $this->mArticleID
= 0;
486 $this->mRedirect
= false;
487 $this->mLatestID
= 0;
488 $this->mContentModel
= false; # initialized lazily in getContentModel()
493 * Create a new Title from a namespace index and a DB key.
494 * It's assumed that $ns and $title are *valid*, for instance when
495 * they came directly from the database or a special page name.
496 * For convenience, spaces are converted to underscores so that
497 * eg user_text fields can be used directly.
499 * @param int $ns The namespace of the article
500 * @param string $title The unprefixed database key form
501 * @param string $fragment The link fragment (after the "#")
502 * @param string $interwiki The interwiki prefix
503 * @return Title The new object
505 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
507 $t->mInterwiki
= $interwiki;
508 $t->mFragment
= $fragment;
509 $t->mNamespace
= $ns = intval( $ns );
510 $t->mDbkeyform
= strtr( $title, ' ', '_' );
511 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
512 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
513 $t->mTextform
= strtr( $title, '_', ' ' );
514 $t->mContentModel
= false; # initialized lazily in getContentModel()
519 * Create a new Title from a namespace index and a DB key.
520 * The parameters will be checked for validity, which is a bit slower
521 * than makeTitle() but safer for user-provided data.
523 * @param int $ns The namespace of the article
524 * @param string $title Database key form
525 * @param string $fragment The link fragment (after the "#")
526 * @param string $interwiki Interwiki prefix
527 * @return Title|null The new object, or null on an error
529 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
530 if ( !MWNamespace
::exists( $ns ) ) {
535 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
538 $t->secureAndSplit();
540 } catch ( MalformedTitleException
$ex ) {
546 * Create a new Title for the Main Page
548 * @return Title The new object
550 public static function newMainPage() {
551 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
552 // Don't give fatal errors if the message is broken
554 $title = Title
::newFromText( 'Main Page' );
560 * Extract a redirect destination from a string and return the
561 * Title, or null if the text doesn't contain a valid redirect
562 * This will only return the very next target, useful for
563 * the redirect table and other checks that don't need full recursion
565 * @param string $text Text with possible redirect
566 * @return Title The corresponding Title
567 * @deprecated since 1.21, use Content::getRedirectTarget instead.
569 public static function newFromRedirect( $text ) {
570 ContentHandler
::deprecated( __METHOD__
, '1.21' );
572 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
573 return $content->getRedirectTarget();
577 * Extract a redirect destination from a string and return the
578 * Title, or null if the text doesn't contain a valid redirect
579 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
580 * in order to provide (hopefully) the Title of the final destination instead of another redirect
582 * @param string $text Text with possible redirect
584 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
586 public static function newFromRedirectRecurse( $text ) {
587 ContentHandler
::deprecated( __METHOD__
, '1.21' );
589 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
590 return $content->getUltimateRedirectTarget();
594 * Extract a redirect destination from a string and return an
595 * array of Titles, or null if the text doesn't contain a valid redirect
596 * The last element in the array is the final destination after all redirects
597 * have been resolved (up to $wgMaxRedirects times)
599 * @param string $text Text with possible redirect
600 * @return Title[] Array of Titles, with the destination last
601 * @deprecated since 1.21, use Content::getRedirectChain instead.
603 public static function newFromRedirectArray( $text ) {
604 ContentHandler
::deprecated( __METHOD__
, '1.21' );
606 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
607 return $content->getRedirectChain();
611 * Get the prefixed DB key associated with an ID
613 * @param int $id The page_id of the article
614 * @return Title|null An object representing the article, or null if no such article was found
616 public static function nameOf( $id ) {
617 $dbr = wfGetDB( DB_SLAVE
);
619 $s = $dbr->selectRow(
621 array( 'page_namespace', 'page_title' ),
622 array( 'page_id' => $id ),
625 if ( $s === false ) {
629 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
634 * Get a regex character class describing the legal characters in a link
636 * @return string The list of characters, not delimited
638 public static function legalChars() {
639 global $wgLegalTitleChars;
640 return $wgLegalTitleChars;
644 * Returns a simple regex that will match on characters and sequences invalid in titles.
645 * Note that this doesn't pick up many things that could be wrong with titles, but that
646 * replacing this regex with something valid will make many titles valid.
648 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
650 * @return string Regex string
652 static function getTitleInvalidRegex() {
653 wfDeprecated( __METHOD__
, '1.25' );
654 return MediaWikiTitleCodec
::getTitleInvalidRegex();
658 * Utility method for converting a character sequence from bytes to Unicode.
660 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
661 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
663 * @param string $byteClass
666 public static function convertByteClassToUnicodeClass( $byteClass ) {
667 $length = strlen( $byteClass );
669 $x0 = $x1 = $x2 = '';
671 $d0 = $d1 = $d2 = '';
672 // Decoded integer codepoints
673 $ord0 = $ord1 = $ord2 = 0;
675 $r0 = $r1 = $r2 = '';
679 $allowUnicode = false;
680 for ( $pos = 0; $pos < $length; $pos++
) {
681 // Shift the queues down
690 // Load the current input token and decoded values
691 $inChar = $byteClass[$pos];
692 if ( $inChar == '\\' ) {
693 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
694 $x0 = $inChar . $m[0];
695 $d0 = chr( hexdec( $m[1] ) );
696 $pos +
= strlen( $m[0] );
697 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
698 $x0 = $inChar . $m[0];
699 $d0 = chr( octdec( $m[0] ) );
700 $pos +
= strlen( $m[0] );
701 } elseif ( $pos +
1 >= $length ) {
704 $d0 = $byteClass[$pos +
1];
712 // Load the current re-encoded value
713 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
714 $r0 = sprintf( '\x%02x', $ord0 );
715 } elseif ( $ord0 >= 0x80 ) {
716 // Allow unicode if a single high-bit character appears
717 $r0 = sprintf( '\x%02x', $ord0 );
718 $allowUnicode = true;
719 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
725 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
727 if ( $ord2 > $ord0 ) {
729 } elseif ( $ord0 >= 0x80 ) {
731 $allowUnicode = true;
732 if ( $ord2 < 0x80 ) {
733 // Keep the non-unicode section of the range
740 // Reset state to the initial value
741 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
742 } elseif ( $ord2 < 0x80 ) {
747 if ( $ord1 < 0x80 ) {
750 if ( $ord0 < 0x80 ) {
753 if ( $allowUnicode ) {
754 $out .= '\u0080-\uFFFF';
760 * Make a prefixed DB key from a DB key and a namespace index
762 * @param int $ns Numerical representation of the namespace
763 * @param string $title The DB key form the title
764 * @param string $fragment The link fragment (after the "#")
765 * @param string $interwiki The interwiki prefix
766 * @param bool $canonicalNamespace If true, use the canonical name for
767 * $ns instead of the localized version.
768 * @return string The prefixed form of the title
770 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
771 $canonicalNamespace = false
775 if ( $canonicalNamespace ) {
776 $namespace = MWNamespace
::getCanonicalName( $ns );
778 $namespace = $wgContLang->getNsText( $ns );
780 $name = $namespace == '' ?
$title : "$namespace:$title";
781 if ( strval( $interwiki ) != '' ) {
782 $name = "$interwiki:$name";
784 if ( strval( $fragment ) != '' ) {
785 $name .= '#' . $fragment;
791 * Escape a text fragment, say from a link, for a URL
793 * @param string $fragment Containing a URL or link fragment (after the "#")
794 * @return string Escaped string
796 static function escapeFragmentForURL( $fragment ) {
797 # Note that we don't urlencode the fragment. urlencoded Unicode
798 # fragments appear not to work in IE (at least up to 7) or in at least
799 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
800 # to care if they aren't encoded.
801 return Sanitizer
::escapeId( $fragment, 'noninitial' );
805 * Callback for usort() to do title sorts by (namespace, title)
810 * @return int Result of string comparison, or namespace comparison
812 public static function compare( $a, $b ) {
813 if ( $a->getNamespace() == $b->getNamespace() ) {
814 return strcmp( $a->getText(), $b->getText() );
816 return $a->getNamespace() - $b->getNamespace();
821 * Determine whether the object refers to a page within
822 * this project (either this wiki or a wiki with a local
823 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
825 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
827 public function isLocal() {
828 if ( $this->isExternal() ) {
829 $iw = Interwiki
::fetch( $this->mInterwiki
);
831 return $iw->isLocal();
838 * Is this Title interwiki?
842 public function isExternal() {
843 return $this->mInterwiki
!== '';
847 * Get the interwiki prefix
849 * Use Title::isExternal to check if a interwiki is set
851 * @return string Interwiki prefix
853 public function getInterwiki() {
854 return $this->mInterwiki
;
858 * Was this a local interwiki link?
862 public function wasLocalInterwiki() {
863 return $this->mLocalInterwiki
;
867 * Determine whether the object refers to a page within
868 * this project and is transcludable.
870 * @return bool True if this is transcludable
872 public function isTrans() {
873 if ( !$this->isExternal() ) {
877 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
881 * Returns the DB name of the distant wiki which owns the object.
883 * @return string The DB name
885 public function getTransWikiID() {
886 if ( !$this->isExternal() ) {
890 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
894 * Get a TitleValue object representing this Title.
896 * @note Not all valid Titles have a corresponding valid TitleValue
897 * (e.g. TitleValues cannot represent page-local links that have a
898 * fragment but no title text).
900 * @return TitleValue|null
902 public function getTitleValue() {
903 if ( $this->mTitleValue
=== null ) {
905 $this->mTitleValue
= new TitleValue(
906 $this->getNamespace(),
908 $this->getFragment() );
909 } catch ( InvalidArgumentException
$ex ) {
910 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
911 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
915 return $this->mTitleValue
;
919 * Get the text form (spaces not underscores) of the main part
921 * @return string Main part of the title
923 public function getText() {
924 return $this->mTextform
;
928 * Get the URL-encoded form of the main part
930 * @return string Main part of the title, URL-encoded
932 public function getPartialURL() {
933 return $this->mUrlform
;
937 * Get the main part with underscores
939 * @return string Main part of the title, with underscores
941 public function getDBkey() {
942 return $this->mDbkeyform
;
946 * Get the DB key with the initial letter case as specified by the user
948 * @return string DB key
950 function getUserCaseDBKey() {
951 if ( !is_null( $this->mUserCaseDBKey
) ) {
952 return $this->mUserCaseDBKey
;
954 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
955 return $this->mDbkeyform
;
960 * Get the namespace index, i.e. one of the NS_xxxx constants.
962 * @return int Namespace index
964 public function getNamespace() {
965 return $this->mNamespace
;
969 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
971 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
972 * @return string Content model id
974 public function getContentModel( $flags = 0 ) {
975 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
976 $linkCache = LinkCache
::singleton();
977 $linkCache->addLinkObj( $this ); # in case we already had an article ID
978 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
981 if ( !$this->mContentModel
) {
982 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
985 return $this->mContentModel
;
989 * Convenience method for checking a title's content model name
991 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
992 * @return bool True if $this->getContentModel() == $id
994 public function hasContentModel( $id ) {
995 return $this->getContentModel() == $id;
999 * Get the namespace text
1001 * @return string Namespace text
1003 public function getNsText() {
1004 if ( $this->isExternal() ) {
1005 // This probably shouldn't even happen,
1006 // but for interwiki transclusion it sometimes does.
1007 // Use the canonical namespaces if possible to try to
1008 // resolve a foreign namespace.
1009 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1010 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1015 $formatter = self
::getTitleFormatter();
1016 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1017 } catch ( InvalidArgumentException
$ex ) {
1018 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1024 * Get the namespace text of the subject (rather than talk) page
1026 * @return string Namespace text
1028 public function getSubjectNsText() {
1030 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1034 * Get the namespace text of the talk page
1036 * @return string Namespace text
1038 public function getTalkNsText() {
1040 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1044 * Could this title have a corresponding talk page?
1048 public function canTalk() {
1049 return MWNamespace
::canTalk( $this->mNamespace
);
1053 * Is this in a namespace that allows actual pages?
1057 public function canExist() {
1058 return $this->mNamespace
>= NS_MAIN
;
1062 * Can this title be added to a user's watchlist?
1066 public function isWatchable() {
1067 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1071 * Returns true if this is a special page.
1075 public function isSpecialPage() {
1076 return $this->getNamespace() == NS_SPECIAL
;
1080 * Returns true if this title resolves to the named special page
1082 * @param string $name The special page name
1085 public function isSpecial( $name ) {
1086 if ( $this->isSpecialPage() ) {
1087 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1088 if ( $name == $thisName ) {
1096 * If the Title refers to a special page alias which is not the local default, resolve
1097 * the alias, and localise the name as necessary. Otherwise, return $this
1101 public function fixSpecialName() {
1102 if ( $this->isSpecialPage() ) {
1103 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1104 if ( $canonicalName ) {
1105 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1106 if ( $localName != $this->mDbkeyform
) {
1107 return Title
::makeTitle( NS_SPECIAL
, $localName );
1115 * Returns true if the title is inside the specified namespace.
1117 * Please make use of this instead of comparing to getNamespace()
1118 * This function is much more resistant to changes we may make
1119 * to namespaces than code that makes direct comparisons.
1120 * @param int $ns The namespace
1124 public function inNamespace( $ns ) {
1125 return MWNamespace
::equals( $this->getNamespace(), $ns );
1129 * Returns true if the title is inside one of the specified namespaces.
1131 * @param int $namespaces,... The namespaces to check for
1135 public function inNamespaces( /* ... */ ) {
1136 $namespaces = func_get_args();
1137 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1138 $namespaces = $namespaces[0];
1141 foreach ( $namespaces as $ns ) {
1142 if ( $this->inNamespace( $ns ) ) {
1151 * Returns true if the title has the same subject namespace as the
1152 * namespace specified.
1153 * For example this method will take NS_USER and return true if namespace
1154 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1155 * as their subject namespace.
1157 * This is MUCH simpler than individually testing for equivalence
1158 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1163 public function hasSubjectNamespace( $ns ) {
1164 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1168 * Is this Title in a namespace which contains content?
1169 * In other words, is this a content page, for the purposes of calculating
1174 public function isContentPage() {
1175 return MWNamespace
::isContent( $this->getNamespace() );
1179 * Would anybody with sufficient privileges be able to move this page?
1180 * Some pages just aren't movable.
1184 public function isMovable() {
1185 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1186 // Interwiki title or immovable namespace. Hooks don't get to override here
1191 Hooks
::run( 'TitleIsMovable', array( $this, &$result ) );
1196 * Is this the mainpage?
1197 * @note Title::newFromText seems to be sufficiently optimized by the title
1198 * cache that we don't need to over-optimize by doing direct comparisons and
1199 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1200 * ends up reporting something differently than $title->isMainPage();
1205 public function isMainPage() {
1206 return $this->equals( Title
::newMainPage() );
1210 * Is this a subpage?
1214 public function isSubpage() {
1215 return MWNamespace
::hasSubpages( $this->mNamespace
)
1216 ?
strpos( $this->getText(), '/' ) !== false
1221 * Is this a conversion table for the LanguageConverter?
1225 public function isConversionTable() {
1226 // @todo ConversionTable should become a separate content model.
1228 return $this->getNamespace() == NS_MEDIAWIKI
&&
1229 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1233 * Does that page contain wikitext, or it is JS, CSS or whatever?
1237 public function isWikitextPage() {
1238 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1242 * Could this page contain custom CSS or JavaScript for the global UI.
1243 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1244 * or CONTENT_MODEL_JAVASCRIPT.
1246 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1249 * Note that this method should not return true for pages that contain and
1250 * show "inactive" CSS or JS.
1254 public function isCssOrJsPage() {
1255 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1256 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1257 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1259 # @note This hook is also called in ContentHandler::getDefaultModel.
1260 # It's called here again to make sure hook functions can force this
1261 # method to return true even outside the MediaWiki namespace.
1263 Hooks
::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1265 return $isCssOrJsPage;
1269 * Is this a .css or .js subpage of a user page?
1272 public function isCssJsSubpage() {
1273 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1274 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1275 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1279 * Trim down a .css or .js subpage title to get the corresponding skin name
1281 * @return string Containing skin name from .css or .js subpage title
1283 public function getSkinFromCssJsSubpage() {
1284 $subpage = explode( '/', $this->mTextform
);
1285 $subpage = $subpage[count( $subpage ) - 1];
1286 $lastdot = strrpos( $subpage, '.' );
1287 if ( $lastdot === false ) {
1288 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1290 return substr( $subpage, 0, $lastdot );
1294 * Is this a .css subpage of a user page?
1298 public function isCssSubpage() {
1299 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1300 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1304 * Is this a .js subpage of a user page?
1308 public function isJsSubpage() {
1309 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1310 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1314 * Is this a talk page of some sort?
1318 public function isTalkPage() {
1319 return MWNamespace
::isTalk( $this->getNamespace() );
1323 * Get a Title object associated with the talk page of this article
1325 * @return Title The object for the talk page
1327 public function getTalkPage() {
1328 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1332 * Get a title object associated with the subject page of this
1335 * @return Title The object for the subject page
1337 public function getSubjectPage() {
1338 // Is this the same title?
1339 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1340 if ( $this->getNamespace() == $subjectNS ) {
1343 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1347 * Get the other title for this page, if this is a subject page
1348 * get the talk page, if it is a subject page get the talk page
1351 * @throws MWException
1354 public function getOtherPage() {
1355 if ( $this->isSpecialPage() ) {
1356 throw new MWException( 'Special pages cannot have other pages' );
1358 if ( $this->isTalkPage() ) {
1359 return $this->getSubjectPage();
1361 return $this->getTalkPage();
1366 * Get the default namespace index, for when there is no namespace
1368 * @return int Default namespace index
1370 public function getDefaultNamespace() {
1371 return $this->mDefaultNamespace
;
1375 * Get the Title fragment (i.e.\ the bit after the #) in text form
1377 * Use Title::hasFragment to check for a fragment
1379 * @return string Title fragment
1381 public function getFragment() {
1382 return $this->mFragment
;
1386 * Check if a Title fragment is set
1391 public function hasFragment() {
1392 return $this->mFragment
!== '';
1396 * Get the fragment in URL form, including the "#" character if there is one
1397 * @return string Fragment in URL form
1399 public function getFragmentForURL() {
1400 if ( !$this->hasFragment() ) {
1403 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1408 * Set the fragment for this title. Removes the first character from the
1409 * specified fragment before setting, so it assumes you're passing it with
1412 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1413 * Still in active use privately.
1416 * @param string $fragment Text
1418 public function setFragment( $fragment ) {
1419 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1423 * Prefix some arbitrary text with the namespace or interwiki prefix
1426 * @param string $name The text
1427 * @return string The prefixed text
1429 private function prefix( $name ) {
1431 if ( $this->isExternal() ) {
1432 $p = $this->mInterwiki
. ':';
1435 if ( 0 != $this->mNamespace
) {
1436 $p .= $this->getNsText() . ':';
1442 * Get the prefixed database key form
1444 * @return string The prefixed title, with underscores and
1445 * any interwiki and namespace prefixes
1447 public function getPrefixedDBkey() {
1448 $s = $this->prefix( $this->mDbkeyform
);
1449 $s = strtr( $s, ' ', '_' );
1454 * Get the prefixed title with spaces.
1455 * This is the form usually used for display
1457 * @return string The prefixed title, with spaces
1459 public function getPrefixedText() {
1460 if ( $this->mPrefixedText
=== null ) {
1461 $s = $this->prefix( $this->mTextform
);
1462 $s = strtr( $s, '_', ' ' );
1463 $this->mPrefixedText
= $s;
1465 return $this->mPrefixedText
;
1469 * Return a string representation of this title
1471 * @return string Representation of this title
1473 public function __toString() {
1474 return $this->getPrefixedText();
1478 * Get the prefixed title with spaces, plus any fragment
1479 * (part beginning with '#')
1481 * @return string The prefixed title, with spaces and the fragment, including '#'
1483 public function getFullText() {
1484 $text = $this->getPrefixedText();
1485 if ( $this->hasFragment() ) {
1486 $text .= '#' . $this->getFragment();
1492 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1496 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1500 * @return string Root name
1503 public function getRootText() {
1504 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1505 return $this->getText();
1508 return strtok( $this->getText(), '/' );
1512 * Get the root page name title, i.e. the leftmost part before any slashes
1516 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1517 * # returns: Title{User:Foo}
1520 * @return Title Root title
1523 public function getRootTitle() {
1524 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1528 * Get the base page name without a namespace, i.e. the part before the subpage name
1532 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1533 * # returns: 'Foo/Bar'
1536 * @return string Base name
1538 public function getBaseText() {
1539 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1540 return $this->getText();
1543 $parts = explode( '/', $this->getText() );
1544 # Don't discard the real title if there's no subpage involved
1545 if ( count( $parts ) > 1 ) {
1546 unset( $parts[count( $parts ) - 1] );
1548 return implode( '/', $parts );
1552 * Get the base page name title, i.e. the part before the subpage name
1556 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1557 * # returns: Title{User:Foo/Bar}
1560 * @return Title Base title
1563 public function getBaseTitle() {
1564 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1568 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1572 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1576 * @return string Subpage name
1578 public function getSubpageText() {
1579 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1580 return $this->mTextform
;
1582 $parts = explode( '/', $this->mTextform
);
1583 return $parts[count( $parts ) - 1];
1587 * Get the title for a subpage of the current page
1591 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1592 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1595 * @param string $text The subpage name to add to the title
1596 * @return Title Subpage title
1599 public function getSubpage( $text ) {
1600 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1604 * Get a URL-encoded form of the subpage text
1606 * @return string URL-encoded subpage name
1608 public function getSubpageUrlForm() {
1609 $text = $this->getSubpageText();
1610 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1615 * Get a URL-encoded title (not an actual URL) including interwiki
1617 * @return string The URL-encoded form
1619 public function getPrefixedURL() {
1620 $s = $this->prefix( $this->mDbkeyform
);
1621 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1626 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1627 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1628 * second argument named variant. This was deprecated in favor
1629 * of passing an array of option with a "variant" key
1630 * Once $query2 is removed for good, this helper can be dropped
1631 * and the wfArrayToCgi moved to getLocalURL();
1633 * @since 1.19 (r105919)
1634 * @param array|string $query
1635 * @param bool $query2
1638 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1639 if ( $query2 !== false ) {
1640 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1641 "method called with a second parameter is deprecated. Add your " .
1642 "parameter to an array passed as the first parameter.", "1.19" );
1644 if ( is_array( $query ) ) {
1645 $query = wfArrayToCgi( $query );
1648 if ( is_string( $query2 ) ) {
1649 // $query2 is a string, we will consider this to be
1650 // a deprecated $variant argument and add it to the query
1651 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1653 $query2 = wfArrayToCgi( $query2 );
1655 // If we have $query content add a & to it first
1659 // Now append the queries together
1666 * Get a real URL referring to this title, with interwiki link and
1669 * @see self::getLocalURL for the arguments.
1671 * @param array|string $query
1672 * @param bool $query2
1673 * @param string $proto Protocol type to use in URL
1674 * @return string The URL
1676 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1677 $query = self
::fixUrlQueryArgs( $query, $query2 );
1679 # Hand off all the decisions on urls to getLocalURL
1680 $url = $this->getLocalURL( $query );
1682 # Expand the url to make it a full url. Note that getLocalURL has the
1683 # potential to output full urls for a variety of reasons, so we use
1684 # wfExpandUrl instead of simply prepending $wgServer
1685 $url = wfExpandUrl( $url, $proto );
1687 # Finally, add the fragment.
1688 $url .= $this->getFragmentForURL();
1690 Hooks
::run( 'GetFullURL', array( &$this, &$url, $query ) );
1695 * Get a URL with no fragment or server name (relative URL) from a Title object.
1696 * If this page is generated with action=render, however,
1697 * $wgServer is prepended to make an absolute URL.
1699 * @see self::getFullURL to always get an absolute URL.
1700 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1701 * valid to link, locally, to the current Title.
1702 * @see self::newFromText to produce a Title object.
1704 * @param string|array $query An optional query string,
1705 * not used for interwiki links. Can be specified as an associative array as well,
1706 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1707 * Some query patterns will trigger various shorturl path replacements.
1708 * @param array $query2 An optional secondary query array. This one MUST
1709 * be an array. If a string is passed it will be interpreted as a deprecated
1710 * variant argument and urlencoded into a variant= argument.
1711 * This second query argument will be added to the $query
1712 * The second parameter is deprecated since 1.19. Pass it as a key,value
1713 * pair in the first parameter array instead.
1715 * @return string String of the URL.
1717 public function getLocalURL( $query = '', $query2 = false ) {
1718 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1720 $query = self
::fixUrlQueryArgs( $query, $query2 );
1722 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1724 $namespace = $this->getNsText();
1725 if ( $namespace != '' ) {
1726 # Can this actually happen? Interwikis shouldn't be parsed.
1727 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1730 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1731 $url = wfAppendQuery( $url, $query );
1733 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1734 if ( $query == '' ) {
1735 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1736 Hooks
::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1738 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1742 if ( !empty( $wgActionPaths )
1743 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1745 $action = urldecode( $matches[2] );
1746 if ( isset( $wgActionPaths[$action] ) ) {
1747 $query = $matches[1];
1748 if ( isset( $matches[4] ) ) {
1749 $query .= $matches[4];
1751 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1752 if ( $query != '' ) {
1753 $url = wfAppendQuery( $url, $query );
1759 && $wgVariantArticlePath
1760 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1761 && $this->getPageLanguage()->hasVariants()
1762 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1764 $variant = urldecode( $matches[1] );
1765 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1766 // Only do the variant replacement if the given variant is a valid
1767 // variant for the page's language.
1768 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1769 $url = str_replace( '$1', $dbkey, $url );
1773 if ( $url === false ) {
1774 if ( $query == '-' ) {
1777 $url = "{$wgScript}?title={$dbkey}&{$query}";
1781 Hooks
::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1783 // @todo FIXME: This causes breakage in various places when we
1784 // actually expected a local URL and end up with dupe prefixes.
1785 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1786 $url = $wgServer . $url;
1789 Hooks
::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1794 * Get a URL that's the simplest URL that will be valid to link, locally,
1795 * to the current Title. It includes the fragment, but does not include
1796 * the server unless action=render is used (or the link is external). If
1797 * there's a fragment but the prefixed text is empty, we just return a link
1800 * The result obviously should not be URL-escaped, but does need to be
1801 * HTML-escaped if it's being output in HTML.
1803 * @param array $query
1804 * @param bool $query2
1805 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1806 * @see self::getLocalURL for the arguments.
1807 * @return string The URL
1809 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1810 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1811 $ret = $this->getFullURL( $query, $query2, $proto );
1812 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1813 $ret = $this->getFragmentForURL();
1815 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1821 * Get the URL form for an internal link.
1822 * - Used in various CDN-related code, in case we have a different
1823 * internal hostname for the server from the exposed one.
1825 * This uses $wgInternalServer to qualify the path, or $wgServer
1826 * if $wgInternalServer is not set. If the server variable used is
1827 * protocol-relative, the URL will be expanded to http://
1829 * @see self::getLocalURL for the arguments.
1830 * @return string The URL
1832 public function getInternalURL( $query = '', $query2 = false ) {
1833 global $wgInternalServer, $wgServer;
1834 $query = self
::fixUrlQueryArgs( $query, $query2 );
1835 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1836 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1837 Hooks
::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1842 * Get the URL for a canonical link, for use in things like IRC and
1843 * e-mail notifications. Uses $wgCanonicalServer and the
1844 * GetCanonicalURL hook.
1846 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1848 * @see self::getLocalURL for the arguments.
1849 * @return string The URL
1852 public function getCanonicalURL( $query = '', $query2 = false ) {
1853 $query = self
::fixUrlQueryArgs( $query, $query2 );
1854 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1855 Hooks
::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1860 * Get the edit URL for this Title
1862 * @return string The URL, or a null string if this is an interwiki link
1864 public function getEditURL() {
1865 if ( $this->isExternal() ) {
1868 $s = $this->getLocalURL( 'action=edit' );
1874 * Can $user perform $action on this page?
1875 * This skips potentially expensive cascading permission checks
1876 * as well as avoids expensive error formatting
1878 * Suitable for use for nonessential UI controls in common cases, but
1879 * _not_ for functional access control.
1881 * May provide false positives, but should never provide a false negative.
1883 * @param string $action Action that permission needs to be checked for
1884 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1887 public function quickUserCan( $action, $user = null ) {
1888 return $this->userCan( $action, $user, false );
1892 * Can $user perform $action on this page?
1894 * @param string $action Action that permission needs to be checked for
1895 * @param User $user User to check (since 1.19); $wgUser will be used if not
1897 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1900 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1901 if ( !$user instanceof User
) {
1906 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1910 * Can $user perform $action on this page?
1912 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1914 * @param string $action Action that permission needs to be checked for
1915 * @param User $user User to check
1916 * @param string $rigor One of (quick,full,secure)
1917 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1918 * - full : does cheap and expensive checks possibly from a slave
1919 * - secure : does cheap and expensive checks, using the master as needed
1920 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1921 * whose corresponding errors may be ignored.
1922 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1924 public function getUserPermissionsErrors(
1925 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1927 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1929 // Remove the errors being ignored.
1930 foreach ( $errors as $index => $error ) {
1931 $errKey = is_array( $error ) ?
$error[0] : $error;
1933 if ( in_array( $errKey, $ignoreErrors ) ) {
1934 unset( $errors[$index] );
1936 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1937 unset( $errors[$index] );
1945 * Permissions checks that fail most often, and which are easiest to test.
1947 * @param string $action The action to check
1948 * @param User $user User to check
1949 * @param array $errors List of current errors
1950 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1951 * @param bool $short Short circuit on first error
1953 * @return array List of errors
1955 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1956 if ( !Hooks
::run( 'TitleQuickPermissions',
1957 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1962 if ( $action == 'create' ) {
1964 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1965 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1967 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1969 } elseif ( $action == 'move' ) {
1970 if ( !$user->isAllowed( 'move-rootuserpages' )
1971 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1972 // Show user page-specific message only if the user can move other pages
1973 $errors[] = array( 'cant-move-user-page' );
1976 // Check if user is allowed to move files if it's a file
1977 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1978 $errors[] = array( 'movenotallowedfile' );
1981 // Check if user is allowed to move category pages if it's a category page
1982 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1983 $errors[] = array( 'cant-move-category-page' );
1986 if ( !$user->isAllowed( 'move' ) ) {
1987 // User can't move anything
1988 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1989 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1990 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1991 // custom message if logged-in users without any special rights can move
1992 $errors[] = array( 'movenologintext' );
1994 $errors[] = array( 'movenotallowed' );
1997 } elseif ( $action == 'move-target' ) {
1998 if ( !$user->isAllowed( 'move' ) ) {
1999 // User can't move anything
2000 $errors[] = array( 'movenotallowed' );
2001 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2002 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2003 // Show user page-specific message only if the user can move other pages
2004 $errors[] = array( 'cant-move-to-user-page' );
2005 } elseif ( !$user->isAllowed( 'move-categorypages' )
2006 && $this->mNamespace
== NS_CATEGORY
) {
2007 // Show category page-specific message only if the user can move other pages
2008 $errors[] = array( 'cant-move-to-category-page' );
2010 } elseif ( !$user->isAllowed( $action ) ) {
2011 $errors[] = $this->missingPermissionError( $action, $short );
2018 * Add the resulting error code to the errors array
2020 * @param array $errors List of current errors
2021 * @param array $result Result of errors
2023 * @return array List of errors
2025 private function resultToError( $errors, $result ) {
2026 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2027 // A single array representing an error
2028 $errors[] = $result;
2029 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2030 // A nested array representing multiple errors
2031 $errors = array_merge( $errors, $result );
2032 } elseif ( $result !== '' && is_string( $result ) ) {
2033 // A string representing a message-id
2034 $errors[] = array( $result );
2035 } elseif ( $result instanceof MessageSpecifier
) {
2036 // A message specifier representing an error
2037 $errors[] = array( $result );
2038 } elseif ( $result === false ) {
2039 // a generic "We don't want them to do that"
2040 $errors[] = array( 'badaccess-group0' );
2046 * Check various permission hooks
2048 * @param string $action The action to check
2049 * @param User $user User to check
2050 * @param array $errors List of current errors
2051 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2052 * @param bool $short Short circuit on first error
2054 * @return array List of errors
2056 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2057 // Use getUserPermissionsErrors instead
2059 if ( !Hooks
::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2060 return $result ?
array() : array( array( 'badaccess-group0' ) );
2062 // Check getUserPermissionsErrors hook
2063 if ( !Hooks
::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2064 $errors = $this->resultToError( $errors, $result );
2066 // Check getUserPermissionsErrorsExpensive hook
2069 && !( $short && count( $errors ) > 0 )
2070 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2072 $errors = $this->resultToError( $errors, $result );
2079 * Check permissions on special pages & namespaces
2081 * @param string $action The action to check
2082 * @param User $user User to check
2083 * @param array $errors List of current errors
2084 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2085 * @param bool $short Short circuit on first error
2087 * @return array List of errors
2089 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2090 # Only 'createaccount' can be performed on special pages,
2091 # which don't actually exist in the DB.
2092 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2093 $errors[] = array( 'ns-specialprotected' );
2096 # Check $wgNamespaceProtection for restricted namespaces
2097 if ( $this->isNamespaceProtected( $user ) ) {
2098 $ns = $this->mNamespace
== NS_MAIN ?
2099 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2100 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2101 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2108 * Check CSS/JS sub-page permissions
2110 * @param string $action The action to check
2111 * @param User $user User to check
2112 * @param array $errors List of current errors
2113 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2114 * @param bool $short Short circuit on first error
2116 * @return array List of errors
2118 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2119 # Protect css/js subpages of user pages
2120 # XXX: this might be better using restrictions
2121 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2122 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2123 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2124 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2125 $errors[] = array( 'mycustomcssprotected', $action );
2126 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2127 $errors[] = array( 'mycustomjsprotected', $action );
2130 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2131 $errors[] = array( 'customcssprotected', $action );
2132 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2133 $errors[] = array( 'customjsprotected', $action );
2142 * Check against page_restrictions table requirements on this
2143 * page. The user must possess all required rights for this
2146 * @param string $action The action to check
2147 * @param User $user User to check
2148 * @param array $errors List of current errors
2149 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2150 * @param bool $short Short circuit on first error
2152 * @return array List of errors
2154 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2155 foreach ( $this->getRestrictions( $action ) as $right ) {
2156 // Backwards compatibility, rewrite sysop -> editprotected
2157 if ( $right == 'sysop' ) {
2158 $right = 'editprotected';
2160 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2161 if ( $right == 'autoconfirmed' ) {
2162 $right = 'editsemiprotected';
2164 if ( $right == '' ) {
2167 if ( !$user->isAllowed( $right ) ) {
2168 $errors[] = array( 'protectedpagetext', $right, $action );
2169 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2170 $errors[] = array( 'protectedpagetext', 'protect', $action );
2178 * Check restrictions on cascading pages.
2180 * @param string $action The action to check
2181 * @param User $user User to check
2182 * @param array $errors List of current errors
2183 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2184 * @param bool $short Short circuit on first error
2186 * @return array List of errors
2188 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2189 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2190 # We /could/ use the protection level on the source page, but it's
2191 # fairly ugly as we have to establish a precedence hierarchy for pages
2192 # included by multiple cascade-protected pages. So just restrict
2193 # it to people with 'protect' permission, as they could remove the
2194 # protection anyway.
2195 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2196 # Cascading protection depends on more than this page...
2197 # Several cascading protected pages may include this page...
2198 # Check each cascading level
2199 # This is only for protection restrictions, not for all actions
2200 if ( isset( $restrictions[$action] ) ) {
2201 foreach ( $restrictions[$action] as $right ) {
2202 // Backwards compatibility, rewrite sysop -> editprotected
2203 if ( $right == 'sysop' ) {
2204 $right = 'editprotected';
2206 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2207 if ( $right == 'autoconfirmed' ) {
2208 $right = 'editsemiprotected';
2210 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2212 foreach ( $cascadingSources as $page ) {
2213 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2215 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2225 * Check action permissions not already checked in checkQuickPermissions
2227 * @param string $action The action to check
2228 * @param User $user User to check
2229 * @param array $errors List of current errors
2230 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2231 * @param bool $short Short circuit on first error
2233 * @return array List of errors
2235 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2236 global $wgDeleteRevisionsLimit, $wgLang;
2238 if ( $action == 'protect' ) {
2239 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2240 // If they can't edit, they shouldn't protect.
2241 $errors[] = array( 'protect-cantedit' );
2243 } elseif ( $action == 'create' ) {
2244 $title_protection = $this->getTitleProtection();
2245 if ( $title_protection ) {
2246 if ( $title_protection['permission'] == ''
2247 ||
!$user->isAllowed( $title_protection['permission'] )
2251 User
::whoIs( $title_protection['user'] ),
2252 $title_protection['reason']
2256 } elseif ( $action == 'move' ) {
2257 // Check for immobile pages
2258 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2259 // Specific message for this case
2260 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2261 } elseif ( !$this->isMovable() ) {
2262 // Less specific message for rarer cases
2263 $errors[] = array( 'immobile-source-page' );
2265 } elseif ( $action == 'move-target' ) {
2266 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2267 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2268 } elseif ( !$this->isMovable() ) {
2269 $errors[] = array( 'immobile-target-page' );
2271 } elseif ( $action == 'delete' ) {
2272 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2273 if ( !$tempErrors ) {
2274 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2275 $user, $tempErrors, $rigor, true );
2277 if ( $tempErrors ) {
2278 // If protection keeps them from editing, they shouldn't be able to delete.
2279 $errors[] = array( 'deleteprotected' );
2281 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2282 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2284 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2291 * Check that the user isn't blocked from editing.
2293 * @param string $action The action to check
2294 * @param User $user User to check
2295 * @param array $errors List of current errors
2296 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2297 * @param bool $short Short circuit on first error
2299 * @return array List of errors
2301 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2302 // Account creation blocks handled at userlogin.
2303 // Unblocking handled in SpecialUnblock
2304 if ( $rigor === 'quick' ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2308 global $wgEmailConfirmToEdit;
2310 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2311 $errors[] = array( 'confirmedittext' );
2314 $useSlave = ( $rigor !== 'secure' );
2315 if ( ( $action == 'edit' ||
$action == 'create' )
2316 && !$user->isBlockedFrom( $this, $useSlave )
2318 // Don't block the user from editing their own talk page unless they've been
2319 // explicitly blocked from that too.
2320 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2321 // @todo FIXME: Pass the relevant context into this function.
2322 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2329 * Check that the user is allowed to read this page.
2331 * @param string $action The action to check
2332 * @param User $user User to check
2333 * @param array $errors List of current errors
2334 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2335 * @param bool $short Short circuit on first error
2337 * @return array List of errors
2339 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2340 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2342 $whitelisted = false;
2343 if ( User
::isEveryoneAllowed( 'read' ) ) {
2344 # Shortcut for public wikis, allows skipping quite a bit of code
2345 $whitelisted = true;
2346 } elseif ( $user->isAllowed( 'read' ) ) {
2347 # If the user is allowed to read pages, he is allowed to read all pages
2348 $whitelisted = true;
2349 } elseif ( $this->isSpecial( 'Userlogin' )
2350 ||
$this->isSpecial( 'ChangePassword' )
2351 ||
$this->isSpecial( 'PasswordReset' )
2353 # Always grant access to the login page.
2354 # Even anons need to be able to log in.
2355 $whitelisted = true;
2356 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2357 # Time to check the whitelist
2358 # Only do these checks is there's something to check against
2359 $name = $this->getPrefixedText();
2360 $dbName = $this->getPrefixedDBkey();
2362 // Check for explicit whitelisting with and without underscores
2363 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2364 $whitelisted = true;
2365 } elseif ( $this->getNamespace() == NS_MAIN
) {
2366 # Old settings might have the title prefixed with
2367 # a colon for main-namespace pages
2368 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2369 $whitelisted = true;
2371 } elseif ( $this->isSpecialPage() ) {
2372 # If it's a special page, ditch the subpage bit and check again
2373 $name = $this->getDBkey();
2374 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2376 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2377 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2378 $whitelisted = true;
2384 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2385 $name = $this->getPrefixedText();
2386 // Check for regex whitelisting
2387 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2388 if ( preg_match( $listItem, $name ) ) {
2389 $whitelisted = true;
2395 if ( !$whitelisted ) {
2396 # If the title is not whitelisted, give extensions a chance to do so...
2397 Hooks
::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2398 if ( !$whitelisted ) {
2399 $errors[] = $this->missingPermissionError( $action, $short );
2407 * Get a description array when the user doesn't have the right to perform
2408 * $action (i.e. when User::isAllowed() returns false)
2410 * @param string $action The action to check
2411 * @param bool $short Short circuit on first error
2412 * @return array List of errors
2414 private function missingPermissionError( $action, $short ) {
2415 // We avoid expensive display logic for quickUserCan's and such
2417 return array( 'badaccess-group0' );
2420 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2421 User
::getGroupsWithPermission( $action ) );
2423 if ( count( $groups ) ) {
2427 $wgLang->commaList( $groups ),
2431 return array( 'badaccess-group0' );
2436 * Can $user perform $action on this page? This is an internal function,
2437 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2438 * checks on wfReadOnly() and blocks)
2440 * @param string $action Action that permission needs to be checked for
2441 * @param User $user User to check
2442 * @param string $rigor One of (quick,full,secure)
2443 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2444 * - full : does cheap and expensive checks possibly from a slave
2445 * - secure : does cheap and expensive checks, using the master as needed
2446 * @param bool $short Set this to true to stop after the first permission error.
2447 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2449 protected function getUserPermissionsErrorsInternal(
2450 $action, $user, $rigor = 'secure', $short = false
2452 if ( $rigor === true ) {
2453 $rigor = 'secure'; // b/c
2454 } elseif ( $rigor === false ) {
2455 $rigor = 'quick'; // b/c
2456 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2457 throw new Exception( "Invalid rigor parameter '$rigor'." );
2460 # Read has special handling
2461 if ( $action == 'read' ) {
2463 'checkPermissionHooks',
2464 'checkReadPermissions',
2466 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2467 # here as it will lead to duplicate error messages. This is okay to do
2468 # since anywhere that checks for create will also check for edit, and
2469 # those checks are called for edit.
2470 } elseif ( $action == 'create' ) {
2472 'checkQuickPermissions',
2473 'checkPermissionHooks',
2474 'checkPageRestrictions',
2475 'checkCascadingSourcesRestrictions',
2476 'checkActionPermissions',
2481 'checkQuickPermissions',
2482 'checkPermissionHooks',
2483 'checkSpecialsAndNSPermissions',
2484 'checkCSSandJSPermissions',
2485 'checkPageRestrictions',
2486 'checkCascadingSourcesRestrictions',
2487 'checkActionPermissions',
2493 while ( count( $checks ) > 0 &&
2494 !( $short && count( $errors ) > 0 ) ) {
2495 $method = array_shift( $checks );
2496 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2503 * Get a filtered list of all restriction types supported by this wiki.
2504 * @param bool $exists True to get all restriction types that apply to
2505 * titles that do exist, False for all restriction types that apply to
2506 * titles that do not exist
2509 public static function getFilteredRestrictionTypes( $exists = true ) {
2510 global $wgRestrictionTypes;
2511 $types = $wgRestrictionTypes;
2513 # Remove the create restriction for existing titles
2514 $types = array_diff( $types, array( 'create' ) );
2516 # Only the create and upload restrictions apply to non-existing titles
2517 $types = array_intersect( $types, array( 'create', 'upload' ) );
2523 * Returns restriction types for the current Title
2525 * @return array Applicable restriction types
2527 public function getRestrictionTypes() {
2528 if ( $this->isSpecialPage() ) {
2532 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2534 if ( $this->getNamespace() != NS_FILE
) {
2535 # Remove the upload restriction for non-file titles
2536 $types = array_diff( $types, array( 'upload' ) );
2539 Hooks
::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2541 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2542 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2548 * Is this title subject to title protection?
2549 * Title protection is the one applied against creation of such title.
2551 * @return array|bool An associative array representing any existent title
2552 * protection, or false if there's none.
2554 public function getTitleProtection() {
2555 // Can't protect pages in special namespaces
2556 if ( $this->getNamespace() < 0 ) {
2560 // Can't protect pages that exist.
2561 if ( $this->exists() ) {
2565 if ( $this->mTitleProtection
=== null ) {
2566 $dbr = wfGetDB( DB_SLAVE
);
2567 $res = $dbr->select(
2570 'user' => 'pt_user',
2571 'reason' => 'pt_reason',
2572 'expiry' => 'pt_expiry',
2573 'permission' => 'pt_create_perm'
2575 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2579 // fetchRow returns false if there are no rows.
2580 $row = $dbr->fetchRow( $res );
2582 if ( $row['permission'] == 'sysop' ) {
2583 $row['permission'] = 'editprotected'; // B/C
2585 if ( $row['permission'] == 'autoconfirmed' ) {
2586 $row['permission'] = 'editsemiprotected'; // B/C
2588 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2590 $this->mTitleProtection
= $row;
2592 return $this->mTitleProtection
;
2596 * Remove any title protection due to page existing
2598 public function deleteTitleProtection() {
2599 $dbw = wfGetDB( DB_MASTER
);
2603 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2606 $this->mTitleProtection
= false;
2610 * Is this page "semi-protected" - the *only* protection levels are listed
2611 * in $wgSemiprotectedRestrictionLevels?
2613 * @param string $action Action to check (default: edit)
2616 public function isSemiProtected( $action = 'edit' ) {
2617 global $wgSemiprotectedRestrictionLevels;
2619 $restrictions = $this->getRestrictions( $action );
2620 $semi = $wgSemiprotectedRestrictionLevels;
2621 if ( !$restrictions ||
!$semi ) {
2622 // Not protected, or all protection is full protection
2626 // Remap autoconfirmed to editsemiprotected for BC
2627 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2628 $semi[$key] = 'editsemiprotected';
2630 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2631 $restrictions[$key] = 'editsemiprotected';
2634 return !array_diff( $restrictions, $semi );
2638 * Does the title correspond to a protected article?
2640 * @param string $action The action the page is protected from,
2641 * by default checks all actions.
2644 public function isProtected( $action = '' ) {
2645 global $wgRestrictionLevels;
2647 $restrictionTypes = $this->getRestrictionTypes();
2649 # Special pages have inherent protection
2650 if ( $this->isSpecialPage() ) {
2654 # Check regular protection levels
2655 foreach ( $restrictionTypes as $type ) {
2656 if ( $action == $type ||
$action == '' ) {
2657 $r = $this->getRestrictions( $type );
2658 foreach ( $wgRestrictionLevels as $level ) {
2659 if ( in_array( $level, $r ) && $level != '' ) {
2670 * Determines if $user is unable to edit this page because it has been protected
2671 * by $wgNamespaceProtection.
2673 * @param User $user User object to check permissions
2676 public function isNamespaceProtected( User
$user ) {
2677 global $wgNamespaceProtection;
2679 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2680 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2681 if ( $right != '' && !$user->isAllowed( $right ) ) {
2690 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2692 * @return bool If the page is subject to cascading restrictions.
2694 public function isCascadeProtected() {
2695 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2696 return ( $sources > 0 );
2700 * Determines whether cascading protection sources have already been loaded from
2703 * @param bool $getPages True to check if the pages are loaded, or false to check
2704 * if the status is loaded.
2705 * @return bool Whether or not the specified information has been loaded
2708 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2709 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2713 * Cascading protection: Get the source of any cascading restrictions on this page.
2715 * @param bool $getPages Whether or not to retrieve the actual pages
2716 * that the restrictions have come from and the actual restrictions
2718 * @return array Two elements: First is an array of Title objects of the
2719 * pages from which cascading restrictions have come, false for
2720 * none, or true if such restrictions exist but $getPages was not
2721 * set. Second is an array like that returned by
2722 * Title::getAllRestrictions(), or an empty array if $getPages is
2725 public function getCascadeProtectionSources( $getPages = true ) {
2726 $pagerestrictions = array();
2728 if ( $this->mCascadeSources
!== null && $getPages ) {
2729 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2730 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2731 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2734 $dbr = wfGetDB( DB_SLAVE
);
2736 if ( $this->getNamespace() == NS_FILE
) {
2737 $tables = array( 'imagelinks', 'page_restrictions' );
2738 $where_clauses = array(
2739 'il_to' => $this->getDBkey(),
2744 $tables = array( 'templatelinks', 'page_restrictions' );
2745 $where_clauses = array(
2746 'tl_namespace' => $this->getNamespace(),
2747 'tl_title' => $this->getDBkey(),
2754 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2755 'pr_expiry', 'pr_type', 'pr_level' );
2756 $where_clauses[] = 'page_id=pr_page';
2759 $cols = array( 'pr_expiry' );
2762 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2764 $sources = $getPages ?
array() : false;
2765 $now = wfTimestampNow();
2767 foreach ( $res as $row ) {
2768 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2769 if ( $expiry > $now ) {
2771 $page_id = $row->pr_page
;
2772 $page_ns = $row->page_namespace
;
2773 $page_title = $row->page_title
;
2774 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2775 # Add groups needed for each restriction type if its not already there
2776 # Make sure this restriction type still exists
2778 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2779 $pagerestrictions[$row->pr_type
] = array();
2783 isset( $pagerestrictions[$row->pr_type
] )
2784 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2786 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2795 $this->mCascadeSources
= $sources;
2796 $this->mCascadingRestrictions
= $pagerestrictions;
2798 $this->mHasCascadingRestrictions
= $sources;
2801 return array( $sources, $pagerestrictions );
2805 * Accessor for mRestrictionsLoaded
2807 * @return bool Whether or not the page's restrictions have already been
2808 * loaded from the database
2811 public function areRestrictionsLoaded() {
2812 return $this->mRestrictionsLoaded
;
2816 * Accessor/initialisation for mRestrictions
2818 * @param string $action Action that permission needs to be checked for
2819 * @return array Restriction levels needed to take the action. All levels are
2820 * required. Note that restriction levels are normally user rights, but 'sysop'
2821 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2822 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2824 public function getRestrictions( $action ) {
2825 if ( !$this->mRestrictionsLoaded
) {
2826 $this->loadRestrictions();
2828 return isset( $this->mRestrictions
[$action] )
2829 ?
$this->mRestrictions
[$action]
2834 * Accessor/initialisation for mRestrictions
2836 * @return array Keys are actions, values are arrays as returned by
2837 * Title::getRestrictions()
2840 public function getAllRestrictions() {
2841 if ( !$this->mRestrictionsLoaded
) {
2842 $this->loadRestrictions();
2844 return $this->mRestrictions
;
2848 * Get the expiry time for the restriction against a given action
2850 * @param string $action
2851 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2852 * or not protected at all, or false if the action is not recognised.
2854 public function getRestrictionExpiry( $action ) {
2855 if ( !$this->mRestrictionsLoaded
) {
2856 $this->loadRestrictions();
2858 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2862 * Returns cascading restrictions for the current article
2866 function areRestrictionsCascading() {
2867 if ( !$this->mRestrictionsLoaded
) {
2868 $this->loadRestrictions();
2871 return $this->mCascadeRestriction
;
2875 * Loads a string into mRestrictions array
2877 * @param ResultWrapper $res Resource restrictions as an SQL result.
2878 * @param string $oldFashionedRestrictions Comma-separated list of page
2879 * restrictions from page table (pre 1.10)
2881 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2884 foreach ( $res as $row ) {
2888 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2892 * Compiles list of active page restrictions from both page table (pre 1.10)
2893 * and page_restrictions table for this existing page.
2894 * Public for usage by LiquidThreads.
2896 * @param array $rows Array of db result objects
2897 * @param string $oldFashionedRestrictions Comma-separated list of page
2898 * restrictions from page table (pre 1.10)
2900 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2901 $dbr = wfGetDB( DB_SLAVE
);
2903 $restrictionTypes = $this->getRestrictionTypes();
2905 foreach ( $restrictionTypes as $type ) {
2906 $this->mRestrictions
[$type] = array();
2907 $this->mRestrictionsExpiry
[$type] = 'infinity';
2910 $this->mCascadeRestriction
= false;
2912 # Backwards-compatibility: also load the restrictions from the page record (old format).
2913 if ( $oldFashionedRestrictions !== null ) {
2914 $this->mOldRestrictions
= $oldFashionedRestrictions;
2917 if ( $this->mOldRestrictions
=== false ) {
2918 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2919 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2922 if ( $this->mOldRestrictions
!= '' ) {
2923 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2924 $temp = explode( '=', trim( $restrict ) );
2925 if ( count( $temp ) == 1 ) {
2926 // old old format should be treated as edit/move restriction
2927 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2928 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2930 $restriction = trim( $temp[1] );
2931 if ( $restriction != '' ) { // some old entries are empty
2932 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2938 if ( count( $rows ) ) {
2939 # Current system - load second to make them override.
2940 $now = wfTimestampNow();
2942 # Cycle through all the restrictions.
2943 foreach ( $rows as $row ) {
2945 // Don't take care of restrictions types that aren't allowed
2946 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2950 // This code should be refactored, now that it's being used more generally,
2951 // But I don't really see any harm in leaving it in Block for now -werdna
2952 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2954 // Only apply the restrictions if they haven't expired!
2955 if ( !$expiry ||
$expiry > $now ) {
2956 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2957 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2959 $this->mCascadeRestriction |
= $row->pr_cascade
;
2964 $this->mRestrictionsLoaded
= true;
2968 * Load restrictions from the page_restrictions table
2970 * @param string $oldFashionedRestrictions Comma-separated list of page
2971 * restrictions from page table (pre 1.10)
2973 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2974 if ( !$this->mRestrictionsLoaded
) {
2975 $dbr = wfGetDB( DB_SLAVE
);
2976 if ( $this->exists() ) {
2977 $res = $dbr->select(
2978 'page_restrictions',
2979 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2980 array( 'pr_page' => $this->getArticleID() ),
2984 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2986 $title_protection = $this->getTitleProtection();
2988 if ( $title_protection ) {
2989 $now = wfTimestampNow();
2990 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2992 if ( !$expiry ||
$expiry > $now ) {
2993 // Apply the restrictions
2994 $this->mRestrictionsExpiry
['create'] = $expiry;
2995 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
2996 } else { // Get rid of the old restrictions
2997 $this->mTitleProtection
= false;
3000 $this->mRestrictionsExpiry
['create'] = 'infinity';
3002 $this->mRestrictionsLoaded
= true;
3008 * Flush the protection cache in this object and force reload from the database.
3009 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3011 public function flushRestrictions() {
3012 $this->mRestrictionsLoaded
= false;
3013 $this->mTitleProtection
= null;
3017 * Purge expired restrictions from the page_restrictions table
3019 static function purgeExpiredRestrictions() {
3020 if ( wfReadOnly() ) {
3024 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3025 wfGetDB( DB_MASTER
),
3027 function ( IDatabase
$dbw, $fname ) {
3029 'page_restrictions',
3030 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3035 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3043 * Does this have subpages? (Warning, usually requires an extra DB query.)
3047 public function hasSubpages() {
3048 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3053 # We dynamically add a member variable for the purpose of this method
3054 # alone to cache the result. There's no point in having it hanging
3055 # around uninitialized in every Title object; therefore we only add it
3056 # if needed and don't declare it statically.
3057 if ( $this->mHasSubpages
=== null ) {
3058 $this->mHasSubpages
= false;
3059 $subpages = $this->getSubpages( 1 );
3060 if ( $subpages instanceof TitleArray
) {
3061 $this->mHasSubpages
= (bool)$subpages->count();
3065 return $this->mHasSubpages
;
3069 * Get all subpages of this page.
3071 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3072 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3073 * doesn't allow subpages
3075 public function getSubpages( $limit = -1 ) {
3076 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3080 $dbr = wfGetDB( DB_SLAVE
);
3081 $conds['page_namespace'] = $this->getNamespace();
3082 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3084 if ( $limit > -1 ) {
3085 $options['LIMIT'] = $limit;
3087 $this->mSubpages
= TitleArray
::newFromResult(
3088 $dbr->select( 'page',
3089 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3095 return $this->mSubpages
;
3099 * Is there a version of this page in the deletion archive?
3101 * @return int The number of archived revisions
3103 public function isDeleted() {
3104 if ( $this->getNamespace() < 0 ) {
3107 $dbr = wfGetDB( DB_SLAVE
);
3109 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3110 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3113 if ( $this->getNamespace() == NS_FILE
) {
3114 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3115 array( 'fa_name' => $this->getDBkey() ),
3124 * Is there a version of this page in the deletion archive?
3128 public function isDeletedQuick() {
3129 if ( $this->getNamespace() < 0 ) {
3132 $dbr = wfGetDB( DB_SLAVE
);
3133 $deleted = (bool)$dbr->selectField( 'archive', '1',
3134 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3137 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3138 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3139 array( 'fa_name' => $this->getDBkey() ),
3147 * Get the article ID for this Title from the link cache,
3148 * adding it if necessary
3150 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3152 * @return int The ID
3154 public function getArticleID( $flags = 0 ) {
3155 if ( $this->getNamespace() < 0 ) {
3156 $this->mArticleID
= 0;
3157 return $this->mArticleID
;
3159 $linkCache = LinkCache
::singleton();
3160 if ( $flags & self
::GAID_FOR_UPDATE
) {
3161 $oldUpdate = $linkCache->forUpdate( true );
3162 $linkCache->clearLink( $this );
3163 $this->mArticleID
= $linkCache->addLinkObj( $this );
3164 $linkCache->forUpdate( $oldUpdate );
3166 if ( -1 == $this->mArticleID
) {
3167 $this->mArticleID
= $linkCache->addLinkObj( $this );
3170 return $this->mArticleID
;
3174 * Is this an article that is a redirect page?
3175 * Uses link cache, adding it if necessary
3177 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3180 public function isRedirect( $flags = 0 ) {
3181 if ( !is_null( $this->mRedirect
) ) {
3182 return $this->mRedirect
;
3184 if ( !$this->getArticleID( $flags ) ) {
3185 $this->mRedirect
= false;
3186 return $this->mRedirect
;
3189 $linkCache = LinkCache
::singleton();
3190 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3191 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3192 if ( $cached === null ) {
3193 # Trust LinkCache's state over our own
3194 # LinkCache is telling us that the page doesn't exist, despite there being cached
3195 # data relating to an existing page in $this->mArticleID. Updaters should clear
3196 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3197 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3198 # LinkCache to refresh its data from the master.
3199 $this->mRedirect
= false;
3200 return $this->mRedirect
;
3203 $this->mRedirect
= (bool)$cached;
3205 return $this->mRedirect
;
3209 * What is the length of this page?
3210 * Uses link cache, adding it if necessary
3212 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3215 public function getLength( $flags = 0 ) {
3216 if ( $this->mLength
!= -1 ) {
3217 return $this->mLength
;
3219 if ( !$this->getArticleID( $flags ) ) {
3221 return $this->mLength
;
3223 $linkCache = LinkCache
::singleton();
3224 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3225 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3226 if ( $cached === null ) {
3227 # Trust LinkCache's state over our own, as for isRedirect()
3229 return $this->mLength
;
3232 $this->mLength
= intval( $cached );
3234 return $this->mLength
;
3238 * What is the page_latest field for this page?
3240 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3241 * @return int Int or 0 if the page doesn't exist
3243 public function getLatestRevID( $flags = 0 ) {
3244 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3245 return intval( $this->mLatestID
);
3247 if ( !$this->getArticleID( $flags ) ) {
3248 $this->mLatestID
= 0;
3249 return $this->mLatestID
;
3251 $linkCache = LinkCache
::singleton();
3252 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3253 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3254 if ( $cached === null ) {
3255 # Trust LinkCache's state over our own, as for isRedirect()
3256 $this->mLatestID
= 0;
3257 return $this->mLatestID
;
3260 $this->mLatestID
= intval( $cached );
3262 return $this->mLatestID
;
3266 * This clears some fields in this object, and clears any associated
3267 * keys in the "bad links" section of the link cache.
3269 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3270 * loading of the new page_id. It's also called from
3271 * WikiPage::doDeleteArticleReal()
3273 * @param int $newid The new Article ID
3275 public function resetArticleID( $newid ) {
3276 $linkCache = LinkCache
::singleton();
3277 $linkCache->clearLink( $this );
3279 if ( $newid === false ) {
3280 $this->mArticleID
= -1;
3282 $this->mArticleID
= intval( $newid );
3284 $this->mRestrictionsLoaded
= false;
3285 $this->mRestrictions
= array();
3286 $this->mOldRestrictions
= false;
3287 $this->mRedirect
= null;
3288 $this->mLength
= -1;
3289 $this->mLatestID
= false;
3290 $this->mContentModel
= false;
3291 $this->mEstimateRevisions
= null;
3292 $this->mPageLanguage
= false;
3293 $this->mDbPageLanguage
= null;
3294 $this->mIsBigDeletion
= null;
3297 public static function clearCaches() {
3298 $linkCache = LinkCache
::singleton();
3299 $linkCache->clear();
3301 $titleCache = self
::getTitleCache();
3302 $titleCache->clear();
3306 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3308 * @param string $text Containing title to capitalize
3309 * @param int $ns Namespace index, defaults to NS_MAIN
3310 * @return string Containing capitalized title
3312 public static function capitalize( $text, $ns = NS_MAIN
) {
3315 if ( MWNamespace
::isCapitalized( $ns ) ) {
3316 return $wgContLang->ucfirst( $text );
3323 * Secure and split - main initialisation function for this object
3325 * Assumes that mDbkeyform has been set, and is urldecoded
3326 * and uses underscores, but not otherwise munged. This function
3327 * removes illegal characters, splits off the interwiki and
3328 * namespace prefixes, sets the other forms, and canonicalizes
3331 * @throws MalformedTitleException On invalid titles
3332 * @return bool True on success
3334 private function secureAndSplit() {
3336 $this->mInterwiki
= '';
3337 $this->mFragment
= '';
3338 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3340 $dbkey = $this->mDbkeyform
;
3342 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3343 // the parsing code with Title, while avoiding massive refactoring.
3344 // @todo: get rid of secureAndSplit, refactor parsing code.
3345 $titleParser = self
::getTitleParser();
3346 // MalformedTitleException can be thrown here
3347 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3350 $this->setFragment( '#' . $parts['fragment'] );
3351 $this->mInterwiki
= $parts['interwiki'];
3352 $this->mLocalInterwiki
= $parts['local_interwiki'];
3353 $this->mNamespace
= $parts['namespace'];
3354 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3356 $this->mDbkeyform
= $parts['dbkey'];
3357 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3358 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3360 # We already know that some pages won't be in the database!
3361 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3362 $this->mArticleID
= 0;
3369 * Get an array of Title objects linking to this Title
3370 * Also stores the IDs in the link cache.
3372 * WARNING: do not use this function on arbitrary user-supplied titles!
3373 * On heavily-used templates it will max out the memory.
3375 * @param array $options May be FOR UPDATE
3376 * @param string $table Table name
3377 * @param string $prefix Fields prefix
3378 * @return Title[] Array of Title objects linking here
3380 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3381 if ( count( $options ) > 0 ) {
3382 $db = wfGetDB( DB_MASTER
);
3384 $db = wfGetDB( DB_SLAVE
);
3388 array( 'page', $table ),
3389 self
::getSelectFields(),
3391 "{$prefix}_from=page_id",
3392 "{$prefix}_namespace" => $this->getNamespace(),
3393 "{$prefix}_title" => $this->getDBkey() ),
3399 if ( $res->numRows() ) {
3400 $linkCache = LinkCache
::singleton();
3401 foreach ( $res as $row ) {
3402 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3404 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3405 $retVal[] = $titleObj;
3413 * Get an array of Title objects using this Title as a template
3414 * Also stores the IDs in the link cache.
3416 * WARNING: do not use this function on arbitrary user-supplied titles!
3417 * On heavily-used templates it will max out the memory.
3419 * @param array $options May be FOR UPDATE
3420 * @return Title[] Array of Title the Title objects linking here
3422 public function getTemplateLinksTo( $options = array() ) {
3423 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3427 * Get an array of Title objects linked from this Title
3428 * Also stores the IDs in the link cache.
3430 * WARNING: do not use this function on arbitrary user-supplied titles!
3431 * On heavily-used templates it will max out the memory.
3433 * @param array $options May be FOR UPDATE
3434 * @param string $table Table name
3435 * @param string $prefix Fields prefix
3436 * @return array Array of Title objects linking here
3438 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3439 $id = $this->getArticleID();
3441 # If the page doesn't exist; there can't be any link from this page
3446 if ( count( $options ) > 0 ) {
3447 $db = wfGetDB( DB_MASTER
);
3449 $db = wfGetDB( DB_SLAVE
);
3452 $blNamespace = "{$prefix}_namespace";
3453 $blTitle = "{$prefix}_title";
3456 array( $table, 'page' ),
3458 array( $blNamespace, $blTitle ),
3459 WikiPage
::selectFields()
3461 array( "{$prefix}_from" => $id ),
3464 array( 'page' => array(
3466 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3471 $linkCache = LinkCache
::singleton();
3472 foreach ( $res as $row ) {
3473 if ( $row->page_id
) {
3474 $titleObj = Title
::newFromRow( $row );
3476 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3477 $linkCache->addBadLinkObj( $titleObj );
3479 $retVal[] = $titleObj;
3486 * Get an array of Title objects used on this Title as a template
3487 * Also stores the IDs in the link cache.
3489 * WARNING: do not use this function on arbitrary user-supplied titles!
3490 * On heavily-used templates it will max out the memory.
3492 * @param array $options May be FOR UPDATE
3493 * @return Title[] Array of Title the Title objects used here
3495 public function getTemplateLinksFrom( $options = array() ) {
3496 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3500 * Get an array of Title objects referring to non-existent articles linked
3503 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3504 * should use redirect table in this case).
3505 * @return Title[] Array of Title the Title objects
3507 public function getBrokenLinksFrom() {
3508 if ( $this->getArticleID() == 0 ) {
3509 # All links from article ID 0 are false positives
3513 $dbr = wfGetDB( DB_SLAVE
);
3514 $res = $dbr->select(
3515 array( 'page', 'pagelinks' ),
3516 array( 'pl_namespace', 'pl_title' ),
3518 'pl_from' => $this->getArticleID(),
3519 'page_namespace IS NULL'
3521 __METHOD__
, array(),
3525 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3531 foreach ( $res as $row ) {
3532 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3538 * Get a list of URLs to purge from the CDN cache when this
3541 * @return string[] Array of String the URLs
3543 public function getCdnUrls() {
3545 $this->getInternalURL(),
3546 $this->getInternalURL( 'action=history' )
3549 $pageLang = $this->getPageLanguage();
3550 if ( $pageLang->hasVariants() ) {
3551 $variants = $pageLang->getVariants();
3552 foreach ( $variants as $vCode ) {
3553 $urls[] = $this->getInternalURL( $vCode );
3557 // If we are looking at a css/js user subpage, purge the action=raw.
3558 if ( $this->isJsSubpage() ) {
3559 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3560 } elseif ( $this->isCssSubpage() ) {
3561 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3564 Hooks
::run( 'TitleSquidURLs', array( $this, &$urls ) );
3569 * @deprecated since 1.27 use getCdnUrls()
3571 public function getSquidURLs() {
3572 return $this->getCdnUrls();
3576 * Purge all applicable CDN URLs
3578 public function purgeSquid() {
3579 DeferredUpdates
::addUpdate(
3580 new CdnCacheUpdate( $this->getCdnUrls() ),
3581 DeferredUpdates
::PRESEND
3586 * Move this page without authentication
3588 * @deprecated since 1.25 use MovePage class instead
3589 * @param Title $nt The new page Title
3590 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3592 public function moveNoAuth( &$nt ) {
3593 wfDeprecated( __METHOD__
, '1.25' );
3594 return $this->moveTo( $nt, false );
3598 * Check whether a given move operation would be valid.
3599 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3601 * @deprecated since 1.25, use MovePage's methods instead
3602 * @param Title $nt The new title
3603 * @param bool $auth Whether to check user permissions (uses $wgUser)
3604 * @param string $reason Is the log summary of the move, used for spam checking
3605 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3607 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3610 if ( !( $nt instanceof Title
) ) {
3611 // Normally we'd add this to $errors, but we'll get
3612 // lots of syntax errors if $nt is not an object
3613 return array( array( 'badtitletext' ) );
3616 $mp = new MovePage( $this, $nt );
3617 $errors = $mp->isValidMove()->getErrorsArray();
3619 $errors = wfMergeErrorArrays(
3621 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3625 return $errors ?
: true;
3629 * Check if the requested move target is a valid file move target
3630 * @todo move this to MovePage
3631 * @param Title $nt Target title
3632 * @return array List of errors
3634 protected function validateFileMoveOperation( $nt ) {
3639 $destFile = wfLocalFile( $nt );
3640 $destFile->load( File
::READ_LATEST
);
3641 if ( !$wgUser->isAllowed( 'reupload-shared' )
3642 && !$destFile->exists() && wfFindFile( $nt )
3644 $errors[] = array( 'file-exists-sharedrepo' );
3651 * Move a title to a new location
3653 * @deprecated since 1.25, use the MovePage class instead
3654 * @param Title $nt The new title
3655 * @param bool $auth Indicates whether $wgUser's permissions
3657 * @param string $reason The reason for the move
3658 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3659 * Ignored if the user doesn't have the suppressredirect right.
3660 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3662 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3664 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3665 if ( is_array( $err ) ) {
3666 // Auto-block user's IP if the account was "hard" blocked
3667 $wgUser->spreadAnyEditBlock();
3670 // Check suppressredirect permission
3671 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3672 $createRedirect = true;
3675 $mp = new MovePage( $this, $nt );
3676 $status = $mp->move( $wgUser, $reason, $createRedirect );
3677 if ( $status->isOK() ) {
3680 return $status->getErrorsArray();
3685 * Move this page's subpages to be subpages of $nt
3687 * @param Title $nt Move target
3688 * @param bool $auth Whether $wgUser's permissions should be checked
3689 * @param string $reason The reason for the move
3690 * @param bool $createRedirect Whether to create redirects from the old subpages to
3691 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3692 * @return array Array with old page titles as keys, and strings (new page titles) or
3693 * arrays (errors) as values, or an error array with numeric indices if no pages
3696 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3697 global $wgMaximumMovedPages;
3698 // Check permissions
3699 if ( !$this->userCan( 'move-subpages' ) ) {
3700 return array( 'cant-move-subpages' );
3702 // Do the source and target namespaces support subpages?
3703 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3704 return array( 'namespace-nosubpages',
3705 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3707 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3708 return array( 'namespace-nosubpages',
3709 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3712 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3715 foreach ( $subpages as $oldSubpage ) {
3717 if ( $count > $wgMaximumMovedPages ) {
3718 $retval[$oldSubpage->getPrefixedText()] =
3719 array( 'movepage-max-pages',
3720 $wgMaximumMovedPages );
3724 // We don't know whether this function was called before
3725 // or after moving the root page, so check both
3727 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3728 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3730 // When moving a page to a subpage of itself,
3731 // don't move it twice
3734 $newPageName = preg_replace(
3735 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3736 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3737 $oldSubpage->getDBkey() );
3738 if ( $oldSubpage->isTalkPage() ) {
3739 $newNs = $nt->getTalkPage()->getNamespace();
3741 $newNs = $nt->getSubjectPage()->getNamespace();
3743 # Bug 14385: we need makeTitleSafe because the new page names may
3744 # be longer than 255 characters.
3745 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3747 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3748 if ( $success === true ) {
3749 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3751 $retval[$oldSubpage->getPrefixedText()] = $success;
3758 * Checks if this page is just a one-rev redirect.
3759 * Adds lock, so don't use just for light purposes.
3763 public function isSingleRevRedirect() {
3764 global $wgContentHandlerUseDB;
3766 $dbw = wfGetDB( DB_MASTER
);
3769 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3770 if ( $wgContentHandlerUseDB ) {
3771 $fields[] = 'page_content_model';
3774 $row = $dbw->selectRow( 'page',
3778 array( 'FOR UPDATE' )
3780 # Cache some fields we may want
3781 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3782 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3783 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3784 $this->mContentModel
= $row && isset( $row->page_content_model
)
3785 ?
strval( $row->page_content_model
)
3788 if ( !$this->mRedirect
) {
3791 # Does the article have a history?
3792 $row = $dbw->selectField( array( 'page', 'revision' ),
3794 array( 'page_namespace' => $this->getNamespace(),
3795 'page_title' => $this->getDBkey(),
3797 'page_latest != rev_id'
3800 array( 'FOR UPDATE' )
3802 # Return true if there was no history
3803 return ( $row === false );
3807 * Checks if $this can be moved to a given Title
3808 * - Selects for update, so don't call it unless you mean business
3810 * @deprecated since 1.25, use MovePage's methods instead
3811 * @param Title $nt The new title to check
3814 public function isValidMoveTarget( $nt ) {
3815 # Is it an existing file?
3816 if ( $nt->getNamespace() == NS_FILE
) {
3817 $file = wfLocalFile( $nt );
3818 $file->load( File
::READ_LATEST
);
3819 if ( $file->exists() ) {
3820 wfDebug( __METHOD__
. ": file exists\n" );
3824 # Is it a redirect with no history?
3825 if ( !$nt->isSingleRevRedirect() ) {
3826 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3829 # Get the article text
3830 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3831 if ( !is_object( $rev ) ) {
3834 $content = $rev->getContent();
3835 # Does the redirect point to the source?
3836 # Or is it a broken self-redirect, usually caused by namespace collisions?
3837 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3839 if ( $redirTitle ) {
3840 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3841 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3842 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3848 # Fail safe (not a redirect after all. strange.)
3849 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3850 " is a redirect, but it doesn't contain a valid redirect.\n" );
3856 * Get categories to which this Title belongs and return an array of
3857 * categories' names.
3859 * @return array Array of parents in the form:
3860 * $parent => $currentarticle
3862 public function getParentCategories() {
3867 $titleKey = $this->getArticleID();
3869 if ( $titleKey === 0 ) {
3873 $dbr = wfGetDB( DB_SLAVE
);
3875 $res = $dbr->select(
3878 array( 'cl_from' => $titleKey ),
3882 if ( $res->numRows() > 0 ) {
3883 foreach ( $res as $row ) {
3884 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3885 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3892 * Get a tree of parent categories
3894 * @param array $children Array with the children in the keys, to check for circular refs
3895 * @return array Tree of parent categories
3897 public function getParentCategoryTree( $children = array() ) {
3899 $parents = $this->getParentCategories();
3902 foreach ( $parents as $parent => $current ) {
3903 if ( array_key_exists( $parent, $children ) ) {
3904 # Circular reference
3905 $stack[$parent] = array();
3907 $nt = Title
::newFromText( $parent );
3909 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3919 * Get an associative array for selecting this title from
3922 * @return array Array suitable for the $where parameter of DB::select()
3924 public function pageCond() {
3925 if ( $this->mArticleID
> 0 ) {
3926 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3927 return array( 'page_id' => $this->mArticleID
);
3929 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3934 * Get the revision ID of the previous revision
3936 * @param int $revId Revision ID. Get the revision that was before this one.
3937 * @param int $flags Title::GAID_FOR_UPDATE
3938 * @return int|bool Old revision ID, or false if none exists
3940 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3941 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3942 $revId = $db->selectField( 'revision', 'rev_id',
3944 'rev_page' => $this->getArticleID( $flags ),
3945 'rev_id < ' . intval( $revId )
3948 array( 'ORDER BY' => 'rev_id DESC' )
3951 if ( $revId === false ) {
3954 return intval( $revId );
3959 * Get the revision ID of the next revision
3961 * @param int $revId Revision ID. Get the revision that was after this one.
3962 * @param int $flags Title::GAID_FOR_UPDATE
3963 * @return int|bool Next revision ID, or false if none exists
3965 public function getNextRevisionID( $revId, $flags = 0 ) {
3966 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3967 $revId = $db->selectField( 'revision', 'rev_id',
3969 'rev_page' => $this->getArticleID( $flags ),
3970 'rev_id > ' . intval( $revId )
3973 array( 'ORDER BY' => 'rev_id' )
3976 if ( $revId === false ) {
3979 return intval( $revId );
3984 * Get the first revision of the page
3986 * @param int $flags Title::GAID_FOR_UPDATE
3987 * @return Revision|null If page doesn't exist
3989 public function getFirstRevision( $flags = 0 ) {
3990 $pageId = $this->getArticleID( $flags );
3992 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3993 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3994 array( 'rev_page' => $pageId ),
3996 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3999 return new Revision( $row );
4006 * Get the oldest revision timestamp of this page
4008 * @param int $flags Title::GAID_FOR_UPDATE
4009 * @return string MW timestamp
4011 public function getEarliestRevTime( $flags = 0 ) {
4012 $rev = $this->getFirstRevision( $flags );
4013 return $rev ?
$rev->getTimestamp() : null;
4017 * Check if this is a new page
4021 public function isNewPage() {
4022 $dbr = wfGetDB( DB_SLAVE
);
4023 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4027 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4031 public function isBigDeletion() {
4032 global $wgDeleteRevisionsLimit;
4034 if ( !$wgDeleteRevisionsLimit ) {
4038 if ( $this->mIsBigDeletion
=== null ) {
4039 $dbr = wfGetDB( DB_SLAVE
);
4041 $revCount = $dbr->selectRowCount(
4044 array( 'rev_page' => $this->getArticleID() ),
4046 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4049 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4052 return $this->mIsBigDeletion
;
4056 * Get the approximate revision count of this page.
4060 public function estimateRevisionCount() {
4061 if ( !$this->exists() ) {
4065 if ( $this->mEstimateRevisions
=== null ) {
4066 $dbr = wfGetDB( DB_SLAVE
);
4067 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4068 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4071 return $this->mEstimateRevisions
;
4075 * Get the number of revisions between the given revision.
4076 * Used for diffs and other things that really need it.
4078 * @param int|Revision $old Old revision or rev ID (first before range)
4079 * @param int|Revision $new New revision or rev ID (first after range)
4080 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4081 * @return int Number of revisions between these revisions.
4083 public function countRevisionsBetween( $old, $new, $max = null ) {
4084 if ( !( $old instanceof Revision
) ) {
4085 $old = Revision
::newFromTitle( $this, (int)$old );
4087 if ( !( $new instanceof Revision
) ) {
4088 $new = Revision
::newFromTitle( $this, (int)$new );
4090 if ( !$old ||
!$new ) {
4091 return 0; // nothing to compare
4093 $dbr = wfGetDB( DB_SLAVE
);
4095 'rev_page' => $this->getArticleID(),
4096 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4097 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4099 if ( $max !== null ) {
4100 return $dbr->selectRowCount( 'revision', '1',
4103 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4106 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4111 * Get the authors between the given revisions or revision IDs.
4112 * Used for diffs and other things that really need it.
4116 * @param int|Revision $old Old revision or rev ID (first before range by default)
4117 * @param int|Revision $new New revision or rev ID (first after range by default)
4118 * @param int $limit Maximum number of authors
4119 * @param string|array $options (Optional): Single option, or an array of options:
4120 * 'include_old' Include $old in the range; $new is excluded.
4121 * 'include_new' Include $new in the range; $old is excluded.
4122 * 'include_both' Include both $old and $new in the range.
4123 * Unknown option values are ignored.
4124 * @return array|null Names of revision authors in the range; null if not both revisions exist
4126 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4127 if ( !( $old instanceof Revision
) ) {
4128 $old = Revision
::newFromTitle( $this, (int)$old );
4130 if ( !( $new instanceof Revision
) ) {
4131 $new = Revision
::newFromTitle( $this, (int)$new );
4133 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4134 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4135 // in the sanity check below?
4136 if ( !$old ||
!$new ) {
4137 return null; // nothing to compare
4142 $options = (array)$options;
4143 if ( in_array( 'include_old', $options ) ) {
4146 if ( in_array( 'include_new', $options ) ) {
4149 if ( in_array( 'include_both', $options ) ) {
4153 // No DB query needed if $old and $new are the same or successive revisions:
4154 if ( $old->getId() === $new->getId() ) {
4155 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4157 array( $old->getUserText( Revision
::RAW
) );
4158 } elseif ( $old->getId() === $new->getParentId() ) {
4159 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4160 $authors[] = $old->getUserText( Revision
::RAW
);
4161 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4162 $authors[] = $new->getUserText( Revision
::RAW
);
4164 } elseif ( $old_cmp === '>=' ) {
4165 $authors[] = $old->getUserText( Revision
::RAW
);
4166 } elseif ( $new_cmp === '<=' ) {
4167 $authors[] = $new->getUserText( Revision
::RAW
);
4171 $dbr = wfGetDB( DB_SLAVE
);
4172 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4174 'rev_page' => $this->getArticleID(),
4175 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4176 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4178 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4180 foreach ( $res as $row ) {
4181 $authors[] = $row->rev_user_text
;
4187 * Get the number of authors between the given revisions or revision IDs.
4188 * Used for diffs and other things that really need it.
4190 * @param int|Revision $old Old revision or rev ID (first before range by default)
4191 * @param int|Revision $new New revision or rev ID (first after range by default)
4192 * @param int $limit Maximum number of authors
4193 * @param string|array $options (Optional): Single option, or an array of options:
4194 * 'include_old' Include $old in the range; $new is excluded.
4195 * 'include_new' Include $new in the range; $old is excluded.
4196 * 'include_both' Include both $old and $new in the range.
4197 * Unknown option values are ignored.
4198 * @return int Number of revision authors in the range; zero if not both revisions exist
4200 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4201 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4202 return $authors ?
count( $authors ) : 0;
4206 * Compare with another title.
4208 * @param Title $title
4211 public function equals( Title
$title ) {
4212 // Note: === is necessary for proper matching of number-like titles.
4213 return $this->getInterwiki() === $title->getInterwiki()
4214 && $this->getNamespace() == $title->getNamespace()
4215 && $this->getDBkey() === $title->getDBkey();
4219 * Check if this title is a subpage of another title
4221 * @param Title $title
4224 public function isSubpageOf( Title
$title ) {
4225 return $this->getInterwiki() === $title->getInterwiki()
4226 && $this->getNamespace() == $title->getNamespace()
4227 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4231 * Check if page exists. For historical reasons, this function simply
4232 * checks for the existence of the title in the page table, and will
4233 * thus return false for interwiki links, special pages and the like.
4234 * If you want to know if a title can be meaningfully viewed, you should
4235 * probably call the isKnown() method instead.
4237 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4238 * from master/for update
4241 public function exists( $flags = 0 ) {
4242 $exists = $this->getArticleID( $flags ) != 0;
4243 Hooks
::run( 'TitleExists', array( $this, &$exists ) );
4248 * Should links to this title be shown as potentially viewable (i.e. as
4249 * "bluelinks"), even if there's no record by this title in the page
4252 * This function is semi-deprecated for public use, as well as somewhat
4253 * misleadingly named. You probably just want to call isKnown(), which
4254 * calls this function internally.
4256 * (ISSUE: Most of these checks are cheap, but the file existence check
4257 * can potentially be quite expensive. Including it here fixes a lot of
4258 * existing code, but we might want to add an optional parameter to skip
4259 * it and any other expensive checks.)
4263 public function isAlwaysKnown() {
4267 * Allows overriding default behavior for determining if a page exists.
4268 * If $isKnown is kept as null, regular checks happen. If it's
4269 * a boolean, this value is returned by the isKnown method.
4273 * @param Title $title
4274 * @param bool|null $isKnown
4276 Hooks
::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4278 if ( !is_null( $isKnown ) ) {
4282 if ( $this->isExternal() ) {
4283 return true; // any interwiki link might be viewable, for all we know
4286 switch ( $this->mNamespace
) {
4289 // file exists, possibly in a foreign repo
4290 return (bool)wfFindFile( $this );
4292 // valid special page
4293 return SpecialPageFactory
::exists( $this->getDBkey() );
4295 // selflink, possibly with fragment
4296 return $this->mDbkeyform
== '';
4298 // known system message
4299 return $this->hasSourceText() !== false;
4306 * Does this title refer to a page that can (or might) be meaningfully
4307 * viewed? In particular, this function may be used to determine if
4308 * links to the title should be rendered as "bluelinks" (as opposed to
4309 * "redlinks" to non-existent pages).
4310 * Adding something else to this function will cause inconsistency
4311 * since LinkHolderArray calls isAlwaysKnown() and does its own
4312 * page existence check.
4316 public function isKnown() {
4317 return $this->isAlwaysKnown() ||
$this->exists();
4321 * Does this page have source text?
4325 public function hasSourceText() {
4326 if ( $this->exists() ) {
4330 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4331 // If the page doesn't exist but is a known system message, default
4332 // message content will be displayed, same for language subpages-
4333 // Use always content language to avoid loading hundreds of languages
4334 // to get the link color.
4336 list( $name, ) = MessageCache
::singleton()->figureMessage(
4337 $wgContLang->lcfirst( $this->getText() )
4339 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4340 return $message->exists();
4347 * Get the default message text or false if the message doesn't exist
4349 * @return string|bool
4351 public function getDefaultMessageText() {
4354 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4358 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4359 $wgContLang->lcfirst( $this->getText() )
4361 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4363 if ( $message->exists() ) {
4364 return $message->plain();
4371 * Updates page_touched for this page; called from LinksUpdate.php
4373 * @param string $purgeTime [optional] TS_MW timestamp
4374 * @return bool True if the update succeeded
4376 public function invalidateCache( $purgeTime = null ) {
4377 if ( wfReadOnly() ) {
4381 if ( $this->mArticleID
=== 0 ) {
4382 return true; // avoid gap locking if we know it's not there
4385 $method = __METHOD__
;
4386 $dbw = wfGetDB( DB_MASTER
);
4387 $conds = $this->pageCond();
4388 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4389 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4393 array( 'page_touched' => $dbTimestamp ),
4394 $conds +
array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4403 * Update page_touched timestamps and send CDN purge messages for
4404 * pages linking to this title. May be sent to the job queue depending
4405 * on the number of links. Typically called on create and delete.
4407 public function touchLinks() {
4408 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4409 if ( $this->getNamespace() == NS_CATEGORY
) {
4410 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4415 * Get the last touched timestamp
4417 * @param IDatabase $db Optional db
4418 * @return string Last-touched timestamp
4420 public function getTouched( $db = null ) {
4421 if ( $db === null ) {
4422 $db = wfGetDB( DB_SLAVE
);
4424 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4429 * Get the timestamp when this page was updated since the user last saw it.
4432 * @return string|null
4434 public function getNotificationTimestamp( $user = null ) {
4437 // Assume current user if none given
4441 // Check cache first
4442 $uid = $user->getId();
4446 // avoid isset here, as it'll return false for null entries
4447 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4448 return $this->mNotificationTimestamp
[$uid];
4450 // Don't cache too much!
4451 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4452 $this->mNotificationTimestamp
= array();
4455 $watchedItem = WatchedItem
::fromUserTitle( $user, $this );
4456 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4458 return $this->mNotificationTimestamp
[$uid];
4462 * Generate strings used for xml 'id' names in monobook tabs
4464 * @param string $prepend Defaults to 'nstab-'
4465 * @return string XML 'id' name
4467 public function getNamespaceKey( $prepend = 'nstab-' ) {
4469 // Gets the subject namespace if this title
4470 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4471 // Checks if canonical namespace name exists for namespace
4472 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4473 // Uses canonical namespace name
4474 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4476 // Uses text of namespace
4477 $namespaceKey = $this->getSubjectNsText();
4479 // Makes namespace key lowercase
4480 $namespaceKey = $wgContLang->lc( $namespaceKey );
4482 if ( $namespaceKey == '' ) {
4483 $namespaceKey = 'main';
4485 // Changes file to image for backwards compatibility
4486 if ( $namespaceKey == 'file' ) {
4487 $namespaceKey = 'image';
4489 return $prepend . $namespaceKey;
4493 * Get all extant redirects to this Title
4495 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4496 * @return Title[] Array of Title redirects to this title
4498 public function getRedirectsHere( $ns = null ) {
4501 $dbr = wfGetDB( DB_SLAVE
);
4503 'rd_namespace' => $this->getNamespace(),
4504 'rd_title' => $this->getDBkey(),
4507 if ( $this->isExternal() ) {
4508 $where['rd_interwiki'] = $this->getInterwiki();
4510 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4512 if ( !is_null( $ns ) ) {
4513 $where['page_namespace'] = $ns;
4516 $res = $dbr->select(
4517 array( 'redirect', 'page' ),
4518 array( 'page_namespace', 'page_title' ),
4523 foreach ( $res as $row ) {
4524 $redirs[] = self
::newFromRow( $row );
4530 * Check if this Title is a valid redirect target
4534 public function isValidRedirectTarget() {
4535 global $wgInvalidRedirectTargets;
4537 if ( $this->isSpecialPage() ) {
4538 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4539 if ( $this->isSpecial( 'Userlogout' ) ) {
4543 foreach ( $wgInvalidRedirectTargets as $target ) {
4544 if ( $this->isSpecial( $target ) ) {
4554 * Get a backlink cache object
4556 * @return BacklinkCache
4558 public function getBacklinkCache() {
4559 return BacklinkCache
::get( $this );
4563 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4567 public function canUseNoindex() {
4568 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4570 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4571 ?
$wgContentNamespaces
4572 : $wgExemptFromUserRobotsControl;
4574 return !in_array( $this->mNamespace
, $bannedNamespaces );
4579 * Returns the raw sort key to be used for categories, with the specified
4580 * prefix. This will be fed to Collation::getSortKey() to get a
4581 * binary sortkey that can be used for actual sorting.
4583 * @param string $prefix The prefix to be used, specified using
4584 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4588 public function getCategorySortkey( $prefix = '' ) {
4589 $unprefixed = $this->getText();
4591 // Anything that uses this hook should only depend
4592 // on the Title object passed in, and should probably
4593 // tell the users to run updateCollations.php --force
4594 // in order to re-sort existing category relations.
4595 Hooks
::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4596 if ( $prefix !== '' ) {
4597 # Separate with a line feed, so the unprefixed part is only used as
4598 # a tiebreaker when two pages have the exact same prefix.
4599 # In UCA, tab is the only character that can sort above LF
4600 # so we strip both of them from the original prefix.
4601 $prefix = strtr( $prefix, "\n\t", ' ' );
4602 return "$prefix\n$unprefixed";
4608 * Get the language in which the content of this page is written in
4609 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4610 * e.g. $wgLang (such as special pages, which are in the user language).
4615 public function getPageLanguage() {
4616 global $wgLang, $wgLanguageCode;
4617 if ( $this->isSpecialPage() ) {
4618 // special pages are in the user language
4622 // Checking if DB language is set
4623 if ( $this->mDbPageLanguage
) {
4624 return wfGetLangObj( $this->mDbPageLanguage
);
4627 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4628 // Note that this may depend on user settings, so the cache should
4629 // be only per-request.
4630 // NOTE: ContentHandler::getPageLanguage() may need to load the
4631 // content to determine the page language!
4632 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4634 $contentHandler = ContentHandler
::getForTitle( $this );
4635 $langObj = $contentHandler->getPageLanguage( $this );
4636 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4638 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4645 * Get the language in which the content of this page is written when
4646 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4647 * e.g. $wgLang (such as special pages, which are in the user language).
4652 public function getPageViewLanguage() {
4655 if ( $this->isSpecialPage() ) {
4656 // If the user chooses a variant, the content is actually
4657 // in a language whose code is the variant code.
4658 $variant = $wgLang->getPreferredVariant();
4659 if ( $wgLang->getCode() !== $variant ) {
4660 return Language
::factory( $variant );
4666 // @note Can't be cached persistently, depends on user settings.
4667 // @note ContentHandler::getPageViewLanguage() may need to load the
4668 // content to determine the page language!
4669 $contentHandler = ContentHandler
::getForTitle( $this );
4670 $pageLang = $contentHandler->getPageViewLanguage( $this );
4675 * Get a list of rendered edit notices for this page.
4677 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4678 * they will already be wrapped in paragraphs.
4681 * @param int $oldid Revision ID that's being edited
4684 public function getEditNotices( $oldid = 0 ) {
4687 // Optional notice for the entire namespace
4688 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4689 $msg = wfMessage( $editnotice_ns );
4690 if ( $msg->exists() ) {
4691 $html = $msg->parseAsBlock();
4692 // Edit notices may have complex logic, but output nothing (T91715)
4693 if ( trim( $html ) !== '' ) {
4694 $notices[$editnotice_ns] = Html
::rawElement(
4696 array( 'class' => array(
4698 'mw-editnotice-namespace',
4699 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4706 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4707 // Optional notice for page itself and any parent page
4708 $parts = explode( '/', $this->getDBkey() );
4709 $editnotice_base = $editnotice_ns;
4710 while ( count( $parts ) > 0 ) {
4711 $editnotice_base .= '-' . array_shift( $parts );
4712 $msg = wfMessage( $editnotice_base );
4713 if ( $msg->exists() ) {
4714 $html = $msg->parseAsBlock();
4715 if ( trim( $html ) !== '' ) {
4716 $notices[$editnotice_base] = Html
::rawElement(
4718 array( 'class' => array(
4720 'mw-editnotice-base',
4721 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4729 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4730 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4731 $msg = wfMessage( $editnoticeText );
4732 if ( $msg->exists() ) {
4733 $html = $msg->parseAsBlock();
4734 if ( trim( $html ) !== '' ) {
4735 $notices[$editnoticeText] = Html
::rawElement(
4737 array( 'class' => array(
4739 'mw-editnotice-page',
4740 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4748 Hooks
::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4755 public function __sleep() {
4763 'mDefaultNamespace',
4767 public function __wakeup() {
4768 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4769 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4770 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );