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.
33 class Title
implements LinkTarget
{
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 MediaWikiTitleCodec
166 private static function getMediaWikiTitleCodec() {
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 getMediaWikiTitleCodec() returns a MediaWikiTitleCodec,
204 // which implements TitleFormatter.
205 return self
::getMediaWikiTitleCodec();
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
::newFromLinkTarget( $titleValue );
243 * Create a new Title from a LinkTarget
245 * @param LinkTarget $linkTarget Assumed to be safe.
249 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
250 return self
::makeTitle(
251 $linkTarget->getNamespace(),
252 $linkTarget->getText(),
253 $linkTarget->getFragment() );
257 * Create a new Title from text, such as what one would find in a link. De-
258 * codes any HTML entities in the text.
260 * @param string|int|null $text The link text; spaces, prefixes, and an
261 * initial ':' indicating the main namespace are accepted.
262 * @param int $defaultNamespace The namespace to use if none is specified
263 * by a prefix. If you want to force a specific namespace even if
264 * $text might begin with a namespace prefix, use makeTitle() or
266 * @throws InvalidArgumentException
267 * @return Title|null Title or null on an error.
269 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
270 if ( is_object( $text ) ) {
271 throw new InvalidArgumentException( '$text must be a string.' );
273 // DWIM: Integers can be passed in here when page titles are used as array keys.
274 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
275 wfDebugLog( 'T76305', wfGetAllCallers( 5 ) );
278 if ( $text === null ) {
283 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
284 } catch ( MalformedTitleException
$ex ) {
290 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
291 * rather than returning null.
293 * The exception subclasses encode detailed information about why the title is invalid.
295 * @see Title::newFromText
298 * @param string $text Title text to check
299 * @param int $defaultNamespace
300 * @throws MalformedTitleException If the title is invalid
303 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
304 if ( is_object( $text ) ) {
305 throw new MWException( '$text must be a string, given an object' );
308 $titleCache = self
::getTitleCache();
310 // Wiki pages often contain multiple links to the same page.
311 // Title normalization and parsing can become expensive on pages with many
312 // links, so we can save a little time by caching them.
313 // In theory these are value objects and won't get changed...
314 if ( $defaultNamespace == NS_MAIN
) {
315 $t = $titleCache->get( $text );
321 // Convert things like é ā or 〗 into normalized (bug 14952) text
322 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
325 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
326 $t->mDefaultNamespace
= intval( $defaultNamespace );
328 $t->secureAndSplit();
329 if ( $defaultNamespace == NS_MAIN
) {
330 $titleCache->set( $text, $t );
336 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
338 * Example of wrong and broken code:
339 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
341 * Example of right code:
342 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
344 * Create a new Title from URL-encoded text. Ensures that
345 * the given title's length does not exceed the maximum.
347 * @param string $url The title, as might be taken from a URL
348 * @return Title|null The new object, or null on an error
350 public static function newFromURL( $url ) {
353 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
354 # but some URLs used it as a space replacement and they still come
355 # from some external search tools.
356 if ( strpos( self
::legalChars(), '+' ) === false ) {
357 $url = strtr( $url, '+', ' ' );
360 $t->mDbkeyform
= strtr( $url, ' ', '_' );
363 $t->secureAndSplit();
365 } catch ( MalformedTitleException
$ex ) {
371 * @return HashBagOStuff
373 private static function getTitleCache() {
374 if ( self
::$titleCache == null ) {
375 self
::$titleCache = new HashBagOStuff( array( 'maxKeys' => self
::CACHE_MAX
) );
377 return self
::$titleCache;
381 * Returns a list of fields that are to be selected for initializing Title
382 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
383 * whether to include page_content_model.
387 protected static function getSelectFields() {
388 global $wgContentHandlerUseDB;
391 'page_namespace', 'page_title', 'page_id',
392 'page_len', 'page_is_redirect', 'page_latest',
395 if ( $wgContentHandlerUseDB ) {
396 $fields[] = 'page_content_model';
403 * Create a new Title from an article ID
405 * @param int $id The page_id corresponding to the Title to create
406 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
407 * @return Title|null The new object, or null on an error
409 public static function newFromID( $id, $flags = 0 ) {
410 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
411 $row = $db->selectRow(
413 self
::getSelectFields(),
414 array( 'page_id' => $id ),
417 if ( $row !== false ) {
418 $title = Title
::newFromRow( $row );
426 * Make an array of titles from an array of IDs
428 * @param int[] $ids Array of IDs
429 * @return Title[] Array of Titles
431 public static function newFromIDs( $ids ) {
432 if ( !count( $ids ) ) {
435 $dbr = wfGetDB( DB_SLAVE
);
439 self
::getSelectFields(),
440 array( 'page_id' => $ids ),
445 foreach ( $res as $row ) {
446 $titles[] = Title
::newFromRow( $row );
452 * Make a Title object from a DB row
454 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
455 * @return Title Corresponding Title
457 public static function newFromRow( $row ) {
458 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
459 $t->loadFromRow( $row );
464 * Load Title object fields from a DB row.
465 * If false is given, the title will be treated as non-existing.
467 * @param stdClass|bool $row Database row
469 public function loadFromRow( $row ) {
470 if ( $row ) { // page found
471 if ( isset( $row->page_id
) ) {
472 $this->mArticleID
= (int)$row->page_id
;
474 if ( isset( $row->page_len
) ) {
475 $this->mLength
= (int)$row->page_len
;
477 if ( isset( $row->page_is_redirect
) ) {
478 $this->mRedirect
= (bool)$row->page_is_redirect
;
480 if ( isset( $row->page_latest
) ) {
481 $this->mLatestID
= (int)$row->page_latest
;
483 if ( isset( $row->page_content_model
) ) {
484 $this->mContentModel
= strval( $row->page_content_model
);
486 $this->mContentModel
= false; # initialized lazily in getContentModel()
488 if ( isset( $row->page_lang
) ) {
489 $this->mDbPageLanguage
= (string)$row->page_lang
;
491 if ( isset( $row->page_restrictions
) ) {
492 $this->mOldRestrictions
= $row->page_restrictions
;
494 } else { // page not found
495 $this->mArticleID
= 0;
497 $this->mRedirect
= false;
498 $this->mLatestID
= 0;
499 $this->mContentModel
= false; # initialized lazily in getContentModel()
504 * Create a new Title from a namespace index and a DB key.
505 * It's assumed that $ns and $title are *valid*, for instance when
506 * they came directly from the database or a special page name.
507 * For convenience, spaces are converted to underscores so that
508 * eg user_text fields can be used directly.
510 * @param int $ns The namespace of the article
511 * @param string $title The unprefixed database key form
512 * @param string $fragment The link fragment (after the "#")
513 * @param string $interwiki The interwiki prefix
514 * @return Title The new object
516 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
518 $t->mInterwiki
= $interwiki;
519 $t->mFragment
= $fragment;
520 $t->mNamespace
= $ns = intval( $ns );
521 $t->mDbkeyform
= strtr( $title, ' ', '_' );
522 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
523 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
524 $t->mTextform
= strtr( $title, '_', ' ' );
525 $t->mContentModel
= false; # initialized lazily in getContentModel()
530 * Create a new Title from a namespace index and a DB key.
531 * The parameters will be checked for validity, which is a bit slower
532 * than makeTitle() but safer for user-provided data.
534 * @param int $ns The namespace of the article
535 * @param string $title Database key form
536 * @param string $fragment The link fragment (after the "#")
537 * @param string $interwiki Interwiki prefix
538 * @return Title|null The new object, or null on an error
540 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
541 if ( !MWNamespace
::exists( $ns ) ) {
546 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
549 $t->secureAndSplit();
551 } catch ( MalformedTitleException
$ex ) {
557 * Create a new Title for the Main Page
559 * @return Title The new object
561 public static function newMainPage() {
562 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
563 // Don't give fatal errors if the message is broken
565 $title = Title
::newFromText( 'Main Page' );
571 * Extract a redirect destination from a string and return the
572 * Title, or null if the text doesn't contain a valid redirect
573 * This will only return the very next target, useful for
574 * the redirect table and other checks that don't need full recursion
576 * @param string $text Text with possible redirect
577 * @return Title The corresponding Title
578 * @deprecated since 1.21, use Content::getRedirectTarget instead.
580 public static function newFromRedirect( $text ) {
581 ContentHandler
::deprecated( __METHOD__
, '1.21' );
583 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
584 return $content->getRedirectTarget();
588 * Extract a redirect destination from a string and return the
589 * Title, or null if the text doesn't contain a valid redirect
590 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
591 * in order to provide (hopefully) the Title of the final destination instead of another redirect
593 * @param string $text Text with possible redirect
595 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
597 public static function newFromRedirectRecurse( $text ) {
598 ContentHandler
::deprecated( __METHOD__
, '1.21' );
600 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
601 return $content->getUltimateRedirectTarget();
605 * Extract a redirect destination from a string and return an
606 * array of Titles, or null if the text doesn't contain a valid redirect
607 * The last element in the array is the final destination after all redirects
608 * have been resolved (up to $wgMaxRedirects times)
610 * @param string $text Text with possible redirect
611 * @return Title[] Array of Titles, with the destination last
612 * @deprecated since 1.21, use Content::getRedirectChain instead.
614 public static function newFromRedirectArray( $text ) {
615 ContentHandler
::deprecated( __METHOD__
, '1.21' );
617 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
618 return $content->getRedirectChain();
622 * Get the prefixed DB key associated with an ID
624 * @param int $id The page_id of the article
625 * @return Title|null An object representing the article, or null if no such article was found
627 public static function nameOf( $id ) {
628 $dbr = wfGetDB( DB_SLAVE
);
630 $s = $dbr->selectRow(
632 array( 'page_namespace', 'page_title' ),
633 array( 'page_id' => $id ),
636 if ( $s === false ) {
640 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
645 * Get a regex character class describing the legal characters in a link
647 * @return string The list of characters, not delimited
649 public static function legalChars() {
650 global $wgLegalTitleChars;
651 return $wgLegalTitleChars;
655 * Returns a simple regex that will match on characters and sequences invalid in titles.
656 * Note that this doesn't pick up many things that could be wrong with titles, but that
657 * replacing this regex with something valid will make many titles valid.
659 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
661 * @return string Regex string
663 static function getTitleInvalidRegex() {
664 wfDeprecated( __METHOD__
, '1.25' );
665 return MediaWikiTitleCodec
::getTitleInvalidRegex();
669 * Utility method for converting a character sequence from bytes to Unicode.
671 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
672 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
674 * @param string $byteClass
677 public static function convertByteClassToUnicodeClass( $byteClass ) {
678 $length = strlen( $byteClass );
680 $x0 = $x1 = $x2 = '';
682 $d0 = $d1 = $d2 = '';
683 // Decoded integer codepoints
684 $ord0 = $ord1 = $ord2 = 0;
686 $r0 = $r1 = $r2 = '';
690 $allowUnicode = false;
691 for ( $pos = 0; $pos < $length; $pos++
) {
692 // Shift the queues down
701 // Load the current input token and decoded values
702 $inChar = $byteClass[$pos];
703 if ( $inChar == '\\' ) {
704 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
705 $x0 = $inChar . $m[0];
706 $d0 = chr( hexdec( $m[1] ) );
707 $pos +
= strlen( $m[0] );
708 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
709 $x0 = $inChar . $m[0];
710 $d0 = chr( octdec( $m[0] ) );
711 $pos +
= strlen( $m[0] );
712 } elseif ( $pos +
1 >= $length ) {
715 $d0 = $byteClass[$pos +
1];
723 // Load the current re-encoded value
724 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
725 $r0 = sprintf( '\x%02x', $ord0 );
726 } elseif ( $ord0 >= 0x80 ) {
727 // Allow unicode if a single high-bit character appears
728 $r0 = sprintf( '\x%02x', $ord0 );
729 $allowUnicode = true;
730 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
736 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
738 if ( $ord2 > $ord0 ) {
740 } elseif ( $ord0 >= 0x80 ) {
742 $allowUnicode = true;
743 if ( $ord2 < 0x80 ) {
744 // Keep the non-unicode section of the range
751 // Reset state to the initial value
752 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
753 } elseif ( $ord2 < 0x80 ) {
758 if ( $ord1 < 0x80 ) {
761 if ( $ord0 < 0x80 ) {
764 if ( $allowUnicode ) {
765 $out .= '\u0080-\uFFFF';
771 * Make a prefixed DB key from a DB key and a namespace index
773 * @param int $ns Numerical representation of the namespace
774 * @param string $title The DB key form the title
775 * @param string $fragment The link fragment (after the "#")
776 * @param string $interwiki The interwiki prefix
777 * @param bool $canonicalNamespace If true, use the canonical name for
778 * $ns instead of the localized version.
779 * @return string The prefixed form of the title
781 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
782 $canonicalNamespace = false
786 if ( $canonicalNamespace ) {
787 $namespace = MWNamespace
::getCanonicalName( $ns );
789 $namespace = $wgContLang->getNsText( $ns );
791 $name = $namespace == '' ?
$title : "$namespace:$title";
792 if ( strval( $interwiki ) != '' ) {
793 $name = "$interwiki:$name";
795 if ( strval( $fragment ) != '' ) {
796 $name .= '#' . $fragment;
802 * Escape a text fragment, say from a link, for a URL
804 * @param string $fragment Containing a URL or link fragment (after the "#")
805 * @return string Escaped string
807 static function escapeFragmentForURL( $fragment ) {
808 # Note that we don't urlencode the fragment. urlencoded Unicode
809 # fragments appear not to work in IE (at least up to 7) or in at least
810 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
811 # to care if they aren't encoded.
812 return Sanitizer
::escapeId( $fragment, 'noninitial' );
816 * Callback for usort() to do title sorts by (namespace, title)
821 * @return int Result of string comparison, or namespace comparison
823 public static function compare( $a, $b ) {
824 if ( $a->getNamespace() == $b->getNamespace() ) {
825 return strcmp( $a->getText(), $b->getText() );
827 return $a->getNamespace() - $b->getNamespace();
832 * Determine whether the object refers to a page within
833 * this project (either this wiki or a wiki with a local
834 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
836 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
838 public function isLocal() {
839 if ( $this->isExternal() ) {
840 $iw = Interwiki
::fetch( $this->mInterwiki
);
842 return $iw->isLocal();
849 * Is this Title interwiki?
853 public function isExternal() {
854 return $this->mInterwiki
!== '';
858 * Get the interwiki prefix
860 * Use Title::isExternal to check if a interwiki is set
862 * @return string Interwiki prefix
864 public function getInterwiki() {
865 return $this->mInterwiki
;
869 * Was this a local interwiki link?
873 public function wasLocalInterwiki() {
874 return $this->mLocalInterwiki
;
878 * Determine whether the object refers to a page within
879 * this project and is transcludable.
881 * @return bool True if this is transcludable
883 public function isTrans() {
884 if ( !$this->isExternal() ) {
888 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
892 * Returns the DB name of the distant wiki which owns the object.
894 * @return string The DB name
896 public function getTransWikiID() {
897 if ( !$this->isExternal() ) {
901 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
905 * Get a TitleValue object representing this Title.
907 * @note Not all valid Titles have a corresponding valid TitleValue
908 * (e.g. TitleValues cannot represent page-local links that have a
909 * fragment but no title text).
911 * @return TitleValue|null
913 public function getTitleValue() {
914 if ( $this->mTitleValue
=== null ) {
916 $this->mTitleValue
= new TitleValue(
917 $this->getNamespace(),
919 $this->getFragment() );
920 } catch ( InvalidArgumentException
$ex ) {
921 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
922 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
926 return $this->mTitleValue
;
930 * Get the text form (spaces not underscores) of the main part
932 * @return string Main part of the title
934 public function getText() {
935 return $this->mTextform
;
939 * Get the URL-encoded form of the main part
941 * @return string Main part of the title, URL-encoded
943 public function getPartialURL() {
944 return $this->mUrlform
;
948 * Get the main part with underscores
950 * @return string Main part of the title, with underscores
952 public function getDBkey() {
953 return $this->mDbkeyform
;
957 * Get the DB key with the initial letter case as specified by the user
959 * @return string DB key
961 function getUserCaseDBKey() {
962 if ( !is_null( $this->mUserCaseDBKey
) ) {
963 return $this->mUserCaseDBKey
;
965 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
966 return $this->mDbkeyform
;
971 * Get the namespace index, i.e. one of the NS_xxxx constants.
973 * @return int Namespace index
975 public function getNamespace() {
976 return $this->mNamespace
;
980 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
982 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
983 * @return string Content model id
985 public function getContentModel( $flags = 0 ) {
986 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
987 $linkCache = LinkCache
::singleton();
988 $linkCache->addLinkObj( $this ); # in case we already had an article ID
989 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
992 if ( !$this->mContentModel
) {
993 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
996 return $this->mContentModel
;
1000 * Convenience method for checking a title's content model name
1002 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1003 * @return bool True if $this->getContentModel() == $id
1005 public function hasContentModel( $id ) {
1006 return $this->getContentModel() == $id;
1010 * Get the namespace text
1012 * @return string Namespace text
1014 public function getNsText() {
1015 if ( $this->isExternal() ) {
1016 // This probably shouldn't even happen,
1017 // but for interwiki transclusion it sometimes does.
1018 // Use the canonical namespaces if possible to try to
1019 // resolve a foreign namespace.
1020 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1021 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1026 $formatter = self
::getTitleFormatter();
1027 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1028 } catch ( InvalidArgumentException
$ex ) {
1029 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1035 * Get the namespace text of the subject (rather than talk) page
1037 * @return string Namespace text
1039 public function getSubjectNsText() {
1041 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1045 * Get the namespace text of the talk page
1047 * @return string Namespace text
1049 public function getTalkNsText() {
1051 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1055 * Could this title have a corresponding talk page?
1059 public function canTalk() {
1060 return MWNamespace
::canTalk( $this->mNamespace
);
1064 * Is this in a namespace that allows actual pages?
1068 public function canExist() {
1069 return $this->mNamespace
>= NS_MAIN
;
1073 * Can this title be added to a user's watchlist?
1077 public function isWatchable() {
1078 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1082 * Returns true if this is a special page.
1086 public function isSpecialPage() {
1087 return $this->getNamespace() == NS_SPECIAL
;
1091 * Returns true if this title resolves to the named special page
1093 * @param string $name The special page name
1096 public function isSpecial( $name ) {
1097 if ( $this->isSpecialPage() ) {
1098 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1099 if ( $name == $thisName ) {
1107 * If the Title refers to a special page alias which is not the local default, resolve
1108 * the alias, and localise the name as necessary. Otherwise, return $this
1112 public function fixSpecialName() {
1113 if ( $this->isSpecialPage() ) {
1114 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1115 if ( $canonicalName ) {
1116 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1117 if ( $localName != $this->mDbkeyform
) {
1118 return Title
::makeTitle( NS_SPECIAL
, $localName );
1126 * Returns true if the title is inside the specified namespace.
1128 * Please make use of this instead of comparing to getNamespace()
1129 * This function is much more resistant to changes we may make
1130 * to namespaces than code that makes direct comparisons.
1131 * @param int $ns The namespace
1135 public function inNamespace( $ns ) {
1136 return MWNamespace
::equals( $this->getNamespace(), $ns );
1140 * Returns true if the title is inside one of the specified namespaces.
1142 * @param int $namespaces,... The namespaces to check for
1146 public function inNamespaces( /* ... */ ) {
1147 $namespaces = func_get_args();
1148 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1149 $namespaces = $namespaces[0];
1152 foreach ( $namespaces as $ns ) {
1153 if ( $this->inNamespace( $ns ) ) {
1162 * Returns true if the title has the same subject namespace as the
1163 * namespace specified.
1164 * For example this method will take NS_USER and return true if namespace
1165 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1166 * as their subject namespace.
1168 * This is MUCH simpler than individually testing for equivalence
1169 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1174 public function hasSubjectNamespace( $ns ) {
1175 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1179 * Is this Title in a namespace which contains content?
1180 * In other words, is this a content page, for the purposes of calculating
1185 public function isContentPage() {
1186 return MWNamespace
::isContent( $this->getNamespace() );
1190 * Would anybody with sufficient privileges be able to move this page?
1191 * Some pages just aren't movable.
1195 public function isMovable() {
1196 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1197 // Interwiki title or immovable namespace. Hooks don't get to override here
1202 Hooks
::run( 'TitleIsMovable', array( $this, &$result ) );
1207 * Is this the mainpage?
1208 * @note Title::newFromText seems to be sufficiently optimized by the title
1209 * cache that we don't need to over-optimize by doing direct comparisons and
1210 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1211 * ends up reporting something differently than $title->isMainPage();
1216 public function isMainPage() {
1217 return $this->equals( Title
::newMainPage() );
1221 * Is this a subpage?
1225 public function isSubpage() {
1226 return MWNamespace
::hasSubpages( $this->mNamespace
)
1227 ?
strpos( $this->getText(), '/' ) !== false
1232 * Is this a conversion table for the LanguageConverter?
1236 public function isConversionTable() {
1237 // @todo ConversionTable should become a separate content model.
1239 return $this->getNamespace() == NS_MEDIAWIKI
&&
1240 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1244 * Does that page contain wikitext, or it is JS, CSS or whatever?
1248 public function isWikitextPage() {
1249 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1253 * Could this page contain custom CSS or JavaScript for the global UI.
1254 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1255 * or CONTENT_MODEL_JAVASCRIPT.
1257 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1260 * Note that this method should not return true for pages that contain and
1261 * show "inactive" CSS or JS.
1264 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1266 public function isCssOrJsPage() {
1267 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1268 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1269 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1271 # @note This hook is also called in ContentHandler::getDefaultModel.
1272 # It's called here again to make sure hook functions can force this
1273 # method to return true even outside the MediaWiki namespace.
1275 Hooks
::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1277 return $isCssOrJsPage;
1281 * Is this a .css or .js subpage of a user page?
1283 * @todo FIXME: Rename to isUserConfigPage()
1285 public function isCssJsSubpage() {
1286 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1287 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1288 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1292 * Trim down a .css or .js subpage title to get the corresponding skin name
1294 * @return string Containing skin name from .css or .js subpage title
1296 public function getSkinFromCssJsSubpage() {
1297 $subpage = explode( '/', $this->mTextform
);
1298 $subpage = $subpage[count( $subpage ) - 1];
1299 $lastdot = strrpos( $subpage, '.' );
1300 if ( $lastdot === false ) {
1301 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1303 return substr( $subpage, 0, $lastdot );
1307 * Is this a .css subpage of a user page?
1311 public function isCssSubpage() {
1312 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1313 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1317 * Is this a .js subpage of a user page?
1321 public function isJsSubpage() {
1322 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1323 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1327 * Is this a talk page of some sort?
1331 public function isTalkPage() {
1332 return MWNamespace
::isTalk( $this->getNamespace() );
1336 * Get a Title object associated with the talk page of this article
1338 * @return Title The object for the talk page
1340 public function getTalkPage() {
1341 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1345 * Get a title object associated with the subject page of this
1348 * @return Title The object for the subject page
1350 public function getSubjectPage() {
1351 // Is this the same title?
1352 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1353 if ( $this->getNamespace() == $subjectNS ) {
1356 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1360 * Get the other title for this page, if this is a subject page
1361 * get the talk page, if it is a subject page get the talk page
1364 * @throws MWException
1367 public function getOtherPage() {
1368 if ( $this->isSpecialPage() ) {
1369 throw new MWException( 'Special pages cannot have other pages' );
1371 if ( $this->isTalkPage() ) {
1372 return $this->getSubjectPage();
1374 return $this->getTalkPage();
1379 * Get the default namespace index, for when there is no namespace
1381 * @return int Default namespace index
1383 public function getDefaultNamespace() {
1384 return $this->mDefaultNamespace
;
1388 * Get the Title fragment (i.e.\ the bit after the #) in text form
1390 * Use Title::hasFragment to check for a fragment
1392 * @return string Title fragment
1394 public function getFragment() {
1395 return $this->mFragment
;
1399 * Check if a Title fragment is set
1404 public function hasFragment() {
1405 return $this->mFragment
!== '';
1409 * Get the fragment in URL form, including the "#" character if there is one
1410 * @return string Fragment in URL form
1412 public function getFragmentForURL() {
1413 if ( !$this->hasFragment() ) {
1416 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1421 * Set the fragment for this title. Removes the first character from the
1422 * specified fragment before setting, so it assumes you're passing it with
1425 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1426 * Still in active use privately.
1429 * @param string $fragment Text
1431 public function setFragment( $fragment ) {
1432 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1436 * Prefix some arbitrary text with the namespace or interwiki prefix
1439 * @param string $name The text
1440 * @return string The prefixed text
1442 private function prefix( $name ) {
1444 if ( $this->isExternal() ) {
1445 $p = $this->mInterwiki
. ':';
1448 if ( 0 != $this->mNamespace
) {
1449 $p .= $this->getNsText() . ':';
1455 * Get the prefixed database key form
1457 * @return string The prefixed title, with underscores and
1458 * any interwiki and namespace prefixes
1460 public function getPrefixedDBkey() {
1461 $s = $this->prefix( $this->mDbkeyform
);
1462 $s = strtr( $s, ' ', '_' );
1467 * Get the prefixed title with spaces.
1468 * This is the form usually used for display
1470 * @return string The prefixed title, with spaces
1472 public function getPrefixedText() {
1473 if ( $this->mPrefixedText
=== null ) {
1474 $s = $this->prefix( $this->mTextform
);
1475 $s = strtr( $s, '_', ' ' );
1476 $this->mPrefixedText
= $s;
1478 return $this->mPrefixedText
;
1482 * Return a string representation of this title
1484 * @return string Representation of this title
1486 public function __toString() {
1487 return $this->getPrefixedText();
1491 * Get the prefixed title with spaces, plus any fragment
1492 * (part beginning with '#')
1494 * @return string The prefixed title, with spaces and the fragment, including '#'
1496 public function getFullText() {
1497 $text = $this->getPrefixedText();
1498 if ( $this->hasFragment() ) {
1499 $text .= '#' . $this->getFragment();
1505 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1509 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1513 * @return string Root name
1516 public function getRootText() {
1517 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1518 return $this->getText();
1521 return strtok( $this->getText(), '/' );
1525 * Get the root page name title, i.e. the leftmost part before any slashes
1529 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1530 * # returns: Title{User:Foo}
1533 * @return Title Root title
1536 public function getRootTitle() {
1537 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1541 * Get the base page name without a namespace, i.e. the part before the subpage name
1545 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1546 * # returns: 'Foo/Bar'
1549 * @return string Base name
1551 public function getBaseText() {
1552 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1553 return $this->getText();
1556 $parts = explode( '/', $this->getText() );
1557 # Don't discard the real title if there's no subpage involved
1558 if ( count( $parts ) > 1 ) {
1559 unset( $parts[count( $parts ) - 1] );
1561 return implode( '/', $parts );
1565 * Get the base page name title, i.e. the part before the subpage name
1569 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1570 * # returns: Title{User:Foo/Bar}
1573 * @return Title Base title
1576 public function getBaseTitle() {
1577 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1581 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1585 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1589 * @return string Subpage name
1591 public function getSubpageText() {
1592 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1593 return $this->mTextform
;
1595 $parts = explode( '/', $this->mTextform
);
1596 return $parts[count( $parts ) - 1];
1600 * Get the title for a subpage of the current page
1604 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1605 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1608 * @param string $text The subpage name to add to the title
1609 * @return Title Subpage title
1612 public function getSubpage( $text ) {
1613 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1617 * Get a URL-encoded form of the subpage text
1619 * @return string URL-encoded subpage name
1621 public function getSubpageUrlForm() {
1622 $text = $this->getSubpageText();
1623 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1628 * Get a URL-encoded title (not an actual URL) including interwiki
1630 * @return string The URL-encoded form
1632 public function getPrefixedURL() {
1633 $s = $this->prefix( $this->mDbkeyform
);
1634 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1639 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1640 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1641 * second argument named variant. This was deprecated in favor
1642 * of passing an array of option with a "variant" key
1643 * Once $query2 is removed for good, this helper can be dropped
1644 * and the wfArrayToCgi moved to getLocalURL();
1646 * @since 1.19 (r105919)
1647 * @param array|string $query
1648 * @param bool $query2
1651 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1652 if ( $query2 !== false ) {
1653 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1654 "method called with a second parameter is deprecated. Add your " .
1655 "parameter to an array passed as the first parameter.", "1.19" );
1657 if ( is_array( $query ) ) {
1658 $query = wfArrayToCgi( $query );
1661 if ( is_string( $query2 ) ) {
1662 // $query2 is a string, we will consider this to be
1663 // a deprecated $variant argument and add it to the query
1664 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1666 $query2 = wfArrayToCgi( $query2 );
1668 // If we have $query content add a & to it first
1672 // Now append the queries together
1679 * Get a real URL referring to this title, with interwiki link and
1682 * @see self::getLocalURL for the arguments.
1684 * @param array|string $query
1685 * @param bool $query2
1686 * @param string $proto Protocol type to use in URL
1687 * @return string The URL
1689 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1690 $query = self
::fixUrlQueryArgs( $query, $query2 );
1692 # Hand off all the decisions on urls to getLocalURL
1693 $url = $this->getLocalURL( $query );
1695 # Expand the url to make it a full url. Note that getLocalURL has the
1696 # potential to output full urls for a variety of reasons, so we use
1697 # wfExpandUrl instead of simply prepending $wgServer
1698 $url = wfExpandUrl( $url, $proto );
1700 # Finally, add the fragment.
1701 $url .= $this->getFragmentForURL();
1703 Hooks
::run( 'GetFullURL', array( &$this, &$url, $query ) );
1708 * Get a URL with no fragment or server name (relative URL) from a Title object.
1709 * If this page is generated with action=render, however,
1710 * $wgServer is prepended to make an absolute URL.
1712 * @see self::getFullURL to always get an absolute URL.
1713 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1714 * valid to link, locally, to the current Title.
1715 * @see self::newFromText to produce a Title object.
1717 * @param string|array $query An optional query string,
1718 * not used for interwiki links. Can be specified as an associative array as well,
1719 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1720 * Some query patterns will trigger various shorturl path replacements.
1721 * @param array $query2 An optional secondary query array. This one MUST
1722 * be an array. If a string is passed it will be interpreted as a deprecated
1723 * variant argument and urlencoded into a variant= argument.
1724 * This second query argument will be added to the $query
1725 * The second parameter is deprecated since 1.19. Pass it as a key,value
1726 * pair in the first parameter array instead.
1728 * @return string String of the URL.
1730 public function getLocalURL( $query = '', $query2 = false ) {
1731 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1733 $query = self
::fixUrlQueryArgs( $query, $query2 );
1735 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1737 $namespace = $this->getNsText();
1738 if ( $namespace != '' ) {
1739 # Can this actually happen? Interwikis shouldn't be parsed.
1740 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1743 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1744 $url = wfAppendQuery( $url, $query );
1746 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1747 if ( $query == '' ) {
1748 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1749 Hooks
::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1751 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1755 if ( !empty( $wgActionPaths )
1756 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1758 $action = urldecode( $matches[2] );
1759 if ( isset( $wgActionPaths[$action] ) ) {
1760 $query = $matches[1];
1761 if ( isset( $matches[4] ) ) {
1762 $query .= $matches[4];
1764 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1765 if ( $query != '' ) {
1766 $url = wfAppendQuery( $url, $query );
1772 && $wgVariantArticlePath
1773 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1774 && $this->getPageLanguage()->hasVariants()
1775 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1777 $variant = urldecode( $matches[1] );
1778 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1779 // Only do the variant replacement if the given variant is a valid
1780 // variant for the page's language.
1781 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1782 $url = str_replace( '$1', $dbkey, $url );
1786 if ( $url === false ) {
1787 if ( $query == '-' ) {
1790 $url = "{$wgScript}?title={$dbkey}&{$query}";
1794 Hooks
::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1796 // @todo FIXME: This causes breakage in various places when we
1797 // actually expected a local URL and end up with dupe prefixes.
1798 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1799 $url = $wgServer . $url;
1802 Hooks
::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1807 * Get a URL that's the simplest URL that will be valid to link, locally,
1808 * to the current Title. It includes the fragment, but does not include
1809 * the server unless action=render is used (or the link is external). If
1810 * there's a fragment but the prefixed text is empty, we just return a link
1813 * The result obviously should not be URL-escaped, but does need to be
1814 * HTML-escaped if it's being output in HTML.
1816 * @param array $query
1817 * @param bool $query2
1818 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1819 * @see self::getLocalURL for the arguments.
1820 * @return string The URL
1822 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1823 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1824 $ret = $this->getFullURL( $query, $query2, $proto );
1825 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1826 $ret = $this->getFragmentForURL();
1828 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1834 * Get the URL form for an internal link.
1835 * - Used in various CDN-related code, in case we have a different
1836 * internal hostname for the server from the exposed one.
1838 * This uses $wgInternalServer to qualify the path, or $wgServer
1839 * if $wgInternalServer is not set. If the server variable used is
1840 * protocol-relative, the URL will be expanded to http://
1842 * @see self::getLocalURL for the arguments.
1843 * @return string The URL
1845 public function getInternalURL( $query = '', $query2 = false ) {
1846 global $wgInternalServer, $wgServer;
1847 $query = self
::fixUrlQueryArgs( $query, $query2 );
1848 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1849 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1850 Hooks
::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1855 * Get the URL for a canonical link, for use in things like IRC and
1856 * e-mail notifications. Uses $wgCanonicalServer and the
1857 * GetCanonicalURL hook.
1859 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1861 * @see self::getLocalURL for the arguments.
1862 * @return string The URL
1865 public function getCanonicalURL( $query = '', $query2 = false ) {
1866 $query = self
::fixUrlQueryArgs( $query, $query2 );
1867 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1868 Hooks
::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1873 * Get the edit URL for this Title
1875 * @return string The URL, or a null string if this is an interwiki link
1877 public function getEditURL() {
1878 if ( $this->isExternal() ) {
1881 $s = $this->getLocalURL( 'action=edit' );
1887 * Can $user perform $action on this page?
1888 * This skips potentially expensive cascading permission checks
1889 * as well as avoids expensive error formatting
1891 * Suitable for use for nonessential UI controls in common cases, but
1892 * _not_ for functional access control.
1894 * May provide false positives, but should never provide a false negative.
1896 * @param string $action Action that permission needs to be checked for
1897 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1900 public function quickUserCan( $action, $user = null ) {
1901 return $this->userCan( $action, $user, false );
1905 * Can $user perform $action on this page?
1907 * @param string $action Action that permission needs to be checked for
1908 * @param User $user User to check (since 1.19); $wgUser will be used if not
1910 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1913 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1914 if ( !$user instanceof User
) {
1919 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1923 * Can $user perform $action on this page?
1925 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1927 * @param string $action Action that permission needs to be checked for
1928 * @param User $user User to check
1929 * @param string $rigor One of (quick,full,secure)
1930 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1931 * - full : does cheap and expensive checks possibly from a slave
1932 * - secure : does cheap and expensive checks, using the master as needed
1933 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1934 * whose corresponding errors may be ignored.
1935 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1937 public function getUserPermissionsErrors(
1938 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1940 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1942 // Remove the errors being ignored.
1943 foreach ( $errors as $index => $error ) {
1944 $errKey = is_array( $error ) ?
$error[0] : $error;
1946 if ( in_array( $errKey, $ignoreErrors ) ) {
1947 unset( $errors[$index] );
1949 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1950 unset( $errors[$index] );
1958 * Permissions checks that fail most often, and which are easiest to test.
1960 * @param string $action The action to check
1961 * @param User $user User to check
1962 * @param array $errors List of current errors
1963 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1964 * @param bool $short Short circuit on first error
1966 * @return array List of errors
1968 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1969 if ( !Hooks
::run( 'TitleQuickPermissions',
1970 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1975 if ( $action == 'create' ) {
1977 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1978 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1980 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1982 } elseif ( $action == 'move' ) {
1983 if ( !$user->isAllowed( 'move-rootuserpages' )
1984 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1985 // Show user page-specific message only if the user can move other pages
1986 $errors[] = array( 'cant-move-user-page' );
1989 // Check if user is allowed to move files if it's a file
1990 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1991 $errors[] = array( 'movenotallowedfile' );
1994 // Check if user is allowed to move category pages if it's a category page
1995 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1996 $errors[] = array( 'cant-move-category-page' );
1999 if ( !$user->isAllowed( 'move' ) ) {
2000 // User can't move anything
2001 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2002 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2003 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2004 // custom message if logged-in users without any special rights can move
2005 $errors[] = array( 'movenologintext' );
2007 $errors[] = array( 'movenotallowed' );
2010 } elseif ( $action == 'move-target' ) {
2011 if ( !$user->isAllowed( 'move' ) ) {
2012 // User can't move anything
2013 $errors[] = array( 'movenotallowed' );
2014 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2015 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2016 // Show user page-specific message only if the user can move other pages
2017 $errors[] = array( 'cant-move-to-user-page' );
2018 } elseif ( !$user->isAllowed( 'move-categorypages' )
2019 && $this->mNamespace
== NS_CATEGORY
) {
2020 // Show category page-specific message only if the user can move other pages
2021 $errors[] = array( 'cant-move-to-category-page' );
2023 } elseif ( !$user->isAllowed( $action ) ) {
2024 $errors[] = $this->missingPermissionError( $action, $short );
2031 * Add the resulting error code to the errors array
2033 * @param array $errors List of current errors
2034 * @param array $result Result of errors
2036 * @return array List of errors
2038 private function resultToError( $errors, $result ) {
2039 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2040 // A single array representing an error
2041 $errors[] = $result;
2042 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2043 // A nested array representing multiple errors
2044 $errors = array_merge( $errors, $result );
2045 } elseif ( $result !== '' && is_string( $result ) ) {
2046 // A string representing a message-id
2047 $errors[] = array( $result );
2048 } elseif ( $result instanceof MessageSpecifier
) {
2049 // A message specifier representing an error
2050 $errors[] = array( $result );
2051 } elseif ( $result === false ) {
2052 // a generic "We don't want them to do that"
2053 $errors[] = array( 'badaccess-group0' );
2059 * Check various permission hooks
2061 * @param string $action The action to check
2062 * @param User $user User to check
2063 * @param array $errors List of current errors
2064 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2065 * @param bool $short Short circuit on first error
2067 * @return array List of errors
2069 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2070 // Use getUserPermissionsErrors instead
2072 if ( !Hooks
::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2073 return $result ?
array() : array( array( 'badaccess-group0' ) );
2075 // Check getUserPermissionsErrors hook
2076 if ( !Hooks
::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2077 $errors = $this->resultToError( $errors, $result );
2079 // Check getUserPermissionsErrorsExpensive hook
2082 && !( $short && count( $errors ) > 0 )
2083 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2085 $errors = $this->resultToError( $errors, $result );
2092 * Check permissions on special pages & namespaces
2094 * @param string $action The action to check
2095 * @param User $user User to check
2096 * @param array $errors List of current errors
2097 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2098 * @param bool $short Short circuit on first error
2100 * @return array List of errors
2102 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2103 # Only 'createaccount' can be performed on special pages,
2104 # which don't actually exist in the DB.
2105 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2106 $errors[] = array( 'ns-specialprotected' );
2109 # Check $wgNamespaceProtection for restricted namespaces
2110 if ( $this->isNamespaceProtected( $user ) ) {
2111 $ns = $this->mNamespace
== NS_MAIN ?
2112 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2113 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2114 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2121 * Check CSS/JS sub-page permissions
2123 * @param string $action The action to check
2124 * @param User $user User to check
2125 * @param array $errors List of current errors
2126 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2127 * @param bool $short Short circuit on first error
2129 * @return array List of errors
2131 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2132 # Protect css/js subpages of user pages
2133 # XXX: this might be better using restrictions
2134 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2135 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2136 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2137 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2138 $errors[] = array( 'mycustomcssprotected', $action );
2139 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2140 $errors[] = array( 'mycustomjsprotected', $action );
2143 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2144 $errors[] = array( 'customcssprotected', $action );
2145 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2146 $errors[] = array( 'customjsprotected', $action );
2155 * Check against page_restrictions table requirements on this
2156 * page. The user must possess all required rights for this
2159 * @param string $action The action to check
2160 * @param User $user User to check
2161 * @param array $errors List of current errors
2162 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2163 * @param bool $short Short circuit on first error
2165 * @return array List of errors
2167 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2168 foreach ( $this->getRestrictions( $action ) as $right ) {
2169 // Backwards compatibility, rewrite sysop -> editprotected
2170 if ( $right == 'sysop' ) {
2171 $right = 'editprotected';
2173 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2174 if ( $right == 'autoconfirmed' ) {
2175 $right = 'editsemiprotected';
2177 if ( $right == '' ) {
2180 if ( !$user->isAllowed( $right ) ) {
2181 $errors[] = array( 'protectedpagetext', $right, $action );
2182 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2183 $errors[] = array( 'protectedpagetext', 'protect', $action );
2191 * Check restrictions on cascading pages.
2193 * @param string $action The action to check
2194 * @param User $user User to check
2195 * @param array $errors List of current errors
2196 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2197 * @param bool $short Short circuit on first error
2199 * @return array List of errors
2201 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2202 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2203 # We /could/ use the protection level on the source page, but it's
2204 # fairly ugly as we have to establish a precedence hierarchy for pages
2205 # included by multiple cascade-protected pages. So just restrict
2206 # it to people with 'protect' permission, as they could remove the
2207 # protection anyway.
2208 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2209 # Cascading protection depends on more than this page...
2210 # Several cascading protected pages may include this page...
2211 # Check each cascading level
2212 # This is only for protection restrictions, not for all actions
2213 if ( isset( $restrictions[$action] ) ) {
2214 foreach ( $restrictions[$action] as $right ) {
2215 // Backwards compatibility, rewrite sysop -> editprotected
2216 if ( $right == 'sysop' ) {
2217 $right = 'editprotected';
2219 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2220 if ( $right == 'autoconfirmed' ) {
2221 $right = 'editsemiprotected';
2223 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2225 foreach ( $cascadingSources as $page ) {
2226 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2228 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2238 * Check action permissions not already checked in checkQuickPermissions
2240 * @param string $action The action to check
2241 * @param User $user User to check
2242 * @param array $errors List of current errors
2243 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2244 * @param bool $short Short circuit on first error
2246 * @return array List of errors
2248 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2249 global $wgDeleteRevisionsLimit, $wgLang;
2251 if ( $action == 'protect' ) {
2252 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2253 // If they can't edit, they shouldn't protect.
2254 $errors[] = array( 'protect-cantedit' );
2256 } elseif ( $action == 'create' ) {
2257 $title_protection = $this->getTitleProtection();
2258 if ( $title_protection ) {
2259 if ( $title_protection['permission'] == ''
2260 ||
!$user->isAllowed( $title_protection['permission'] )
2264 User
::whoIs( $title_protection['user'] ),
2265 $title_protection['reason']
2269 } elseif ( $action == 'move' ) {
2270 // Check for immobile pages
2271 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2272 // Specific message for this case
2273 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2274 } elseif ( !$this->isMovable() ) {
2275 // Less specific message for rarer cases
2276 $errors[] = array( 'immobile-source-page' );
2278 } elseif ( $action == 'move-target' ) {
2279 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2280 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2281 } elseif ( !$this->isMovable() ) {
2282 $errors[] = array( 'immobile-target-page' );
2284 } elseif ( $action == 'delete' ) {
2285 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2286 if ( !$tempErrors ) {
2287 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2288 $user, $tempErrors, $rigor, true );
2290 if ( $tempErrors ) {
2291 // If protection keeps them from editing, they shouldn't be able to delete.
2292 $errors[] = array( 'deleteprotected' );
2294 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2295 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2297 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2304 * Check that the user isn't blocked from editing.
2306 * @param string $action The action to check
2307 * @param User $user User to check
2308 * @param array $errors List of current errors
2309 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2310 * @param bool $short Short circuit on first error
2312 * @return array List of errors
2314 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2315 // Account creation blocks handled at userlogin.
2316 // Unblocking handled in SpecialUnblock
2317 if ( $rigor === 'quick' ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2321 global $wgEmailConfirmToEdit;
2323 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2324 $errors[] = array( 'confirmedittext' );
2327 $useSlave = ( $rigor !== 'secure' );
2328 if ( ( $action == 'edit' ||
$action == 'create' )
2329 && !$user->isBlockedFrom( $this, $useSlave )
2331 // Don't block the user from editing their own talk page unless they've been
2332 // explicitly blocked from that too.
2333 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2334 // @todo FIXME: Pass the relevant context into this function.
2335 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2342 * Check that the user is allowed to read this page.
2344 * @param string $action The action to check
2345 * @param User $user User to check
2346 * @param array $errors List of current errors
2347 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2348 * @param bool $short Short circuit on first error
2350 * @return array List of errors
2352 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2353 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2355 $whitelisted = false;
2356 if ( User
::isEveryoneAllowed( 'read' ) ) {
2357 # Shortcut for public wikis, allows skipping quite a bit of code
2358 $whitelisted = true;
2359 } elseif ( $user->isAllowed( 'read' ) ) {
2360 # If the user is allowed to read pages, he is allowed to read all pages
2361 $whitelisted = true;
2362 } elseif ( $this->isSpecial( 'Userlogin' )
2363 ||
$this->isSpecial( 'ChangePassword' )
2364 ||
$this->isSpecial( 'PasswordReset' )
2366 # Always grant access to the login page.
2367 # Even anons need to be able to log in.
2368 $whitelisted = true;
2369 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2370 # Time to check the whitelist
2371 # Only do these checks is there's something to check against
2372 $name = $this->getPrefixedText();
2373 $dbName = $this->getPrefixedDBkey();
2375 // Check for explicit whitelisting with and without underscores
2376 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2377 $whitelisted = true;
2378 } elseif ( $this->getNamespace() == NS_MAIN
) {
2379 # Old settings might have the title prefixed with
2380 # a colon for main-namespace pages
2381 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2382 $whitelisted = true;
2384 } elseif ( $this->isSpecialPage() ) {
2385 # If it's a special page, ditch the subpage bit and check again
2386 $name = $this->getDBkey();
2387 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2389 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2390 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2391 $whitelisted = true;
2397 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2398 $name = $this->getPrefixedText();
2399 // Check for regex whitelisting
2400 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2401 if ( preg_match( $listItem, $name ) ) {
2402 $whitelisted = true;
2408 if ( !$whitelisted ) {
2409 # If the title is not whitelisted, give extensions a chance to do so...
2410 Hooks
::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2411 if ( !$whitelisted ) {
2412 $errors[] = $this->missingPermissionError( $action, $short );
2420 * Get a description array when the user doesn't have the right to perform
2421 * $action (i.e. when User::isAllowed() returns false)
2423 * @param string $action The action to check
2424 * @param bool $short Short circuit on first error
2425 * @return array List of errors
2427 private function missingPermissionError( $action, $short ) {
2428 // We avoid expensive display logic for quickUserCan's and such
2430 return array( 'badaccess-group0' );
2433 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2434 User
::getGroupsWithPermission( $action ) );
2436 if ( count( $groups ) ) {
2440 $wgLang->commaList( $groups ),
2444 return array( 'badaccess-group0' );
2449 * Can $user perform $action on this page? This is an internal function,
2450 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2451 * checks on wfReadOnly() and blocks)
2453 * @param string $action Action that permission needs to be checked for
2454 * @param User $user User to check
2455 * @param string $rigor One of (quick,full,secure)
2456 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2457 * - full : does cheap and expensive checks possibly from a slave
2458 * - secure : does cheap and expensive checks, using the master as needed
2459 * @param bool $short Set this to true to stop after the first permission error.
2460 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2462 protected function getUserPermissionsErrorsInternal(
2463 $action, $user, $rigor = 'secure', $short = false
2465 if ( $rigor === true ) {
2466 $rigor = 'secure'; // b/c
2467 } elseif ( $rigor === false ) {
2468 $rigor = 'quick'; // b/c
2469 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2470 throw new Exception( "Invalid rigor parameter '$rigor'." );
2473 # Read has special handling
2474 if ( $action == 'read' ) {
2476 'checkPermissionHooks',
2477 'checkReadPermissions',
2479 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2480 # here as it will lead to duplicate error messages. This is okay to do
2481 # since anywhere that checks for create will also check for edit, and
2482 # those checks are called for edit.
2483 } elseif ( $action == 'create' ) {
2485 'checkQuickPermissions',
2486 'checkPermissionHooks',
2487 'checkPageRestrictions',
2488 'checkCascadingSourcesRestrictions',
2489 'checkActionPermissions',
2494 'checkQuickPermissions',
2495 'checkPermissionHooks',
2496 'checkSpecialsAndNSPermissions',
2497 'checkCSSandJSPermissions',
2498 'checkPageRestrictions',
2499 'checkCascadingSourcesRestrictions',
2500 'checkActionPermissions',
2506 while ( count( $checks ) > 0 &&
2507 !( $short && count( $errors ) > 0 ) ) {
2508 $method = array_shift( $checks );
2509 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2516 * Get a filtered list of all restriction types supported by this wiki.
2517 * @param bool $exists True to get all restriction types that apply to
2518 * titles that do exist, False for all restriction types that apply to
2519 * titles that do not exist
2522 public static function getFilteredRestrictionTypes( $exists = true ) {
2523 global $wgRestrictionTypes;
2524 $types = $wgRestrictionTypes;
2526 # Remove the create restriction for existing titles
2527 $types = array_diff( $types, array( 'create' ) );
2529 # Only the create and upload restrictions apply to non-existing titles
2530 $types = array_intersect( $types, array( 'create', 'upload' ) );
2536 * Returns restriction types for the current Title
2538 * @return array Applicable restriction types
2540 public function getRestrictionTypes() {
2541 if ( $this->isSpecialPage() ) {
2545 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2547 if ( $this->getNamespace() != NS_FILE
) {
2548 # Remove the upload restriction for non-file titles
2549 $types = array_diff( $types, array( 'upload' ) );
2552 Hooks
::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2554 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2555 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2561 * Is this title subject to title protection?
2562 * Title protection is the one applied against creation of such title.
2564 * @return array|bool An associative array representing any existent title
2565 * protection, or false if there's none.
2567 public function getTitleProtection() {
2568 // Can't protect pages in special namespaces
2569 if ( $this->getNamespace() < 0 ) {
2573 // Can't protect pages that exist.
2574 if ( $this->exists() ) {
2578 if ( $this->mTitleProtection
=== null ) {
2579 $dbr = wfGetDB( DB_SLAVE
);
2580 $res = $dbr->select(
2583 'user' => 'pt_user',
2584 'reason' => 'pt_reason',
2585 'expiry' => 'pt_expiry',
2586 'permission' => 'pt_create_perm'
2588 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2592 // fetchRow returns false if there are no rows.
2593 $row = $dbr->fetchRow( $res );
2595 if ( $row['permission'] == 'sysop' ) {
2596 $row['permission'] = 'editprotected'; // B/C
2598 if ( $row['permission'] == 'autoconfirmed' ) {
2599 $row['permission'] = 'editsemiprotected'; // B/C
2601 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2603 $this->mTitleProtection
= $row;
2605 return $this->mTitleProtection
;
2609 * Remove any title protection due to page existing
2611 public function deleteTitleProtection() {
2612 $dbw = wfGetDB( DB_MASTER
);
2616 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2619 $this->mTitleProtection
= false;
2623 * Is this page "semi-protected" - the *only* protection levels are listed
2624 * in $wgSemiprotectedRestrictionLevels?
2626 * @param string $action Action to check (default: edit)
2629 public function isSemiProtected( $action = 'edit' ) {
2630 global $wgSemiprotectedRestrictionLevels;
2632 $restrictions = $this->getRestrictions( $action );
2633 $semi = $wgSemiprotectedRestrictionLevels;
2634 if ( !$restrictions ||
!$semi ) {
2635 // Not protected, or all protection is full protection
2639 // Remap autoconfirmed to editsemiprotected for BC
2640 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2641 $semi[$key] = 'editsemiprotected';
2643 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2644 $restrictions[$key] = 'editsemiprotected';
2647 return !array_diff( $restrictions, $semi );
2651 * Does the title correspond to a protected article?
2653 * @param string $action The action the page is protected from,
2654 * by default checks all actions.
2657 public function isProtected( $action = '' ) {
2658 global $wgRestrictionLevels;
2660 $restrictionTypes = $this->getRestrictionTypes();
2662 # Special pages have inherent protection
2663 if ( $this->isSpecialPage() ) {
2667 # Check regular protection levels
2668 foreach ( $restrictionTypes as $type ) {
2669 if ( $action == $type ||
$action == '' ) {
2670 $r = $this->getRestrictions( $type );
2671 foreach ( $wgRestrictionLevels as $level ) {
2672 if ( in_array( $level, $r ) && $level != '' ) {
2683 * Determines if $user is unable to edit this page because it has been protected
2684 * by $wgNamespaceProtection.
2686 * @param User $user User object to check permissions
2689 public function isNamespaceProtected( User
$user ) {
2690 global $wgNamespaceProtection;
2692 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2693 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2694 if ( $right != '' && !$user->isAllowed( $right ) ) {
2703 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2705 * @return bool If the page is subject to cascading restrictions.
2707 public function isCascadeProtected() {
2708 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2709 return ( $sources > 0 );
2713 * Determines whether cascading protection sources have already been loaded from
2716 * @param bool $getPages True to check if the pages are loaded, or false to check
2717 * if the status is loaded.
2718 * @return bool Whether or not the specified information has been loaded
2721 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2722 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2726 * Cascading protection: Get the source of any cascading restrictions on this page.
2728 * @param bool $getPages Whether or not to retrieve the actual pages
2729 * that the restrictions have come from and the actual restrictions
2731 * @return array Two elements: First is an array of Title objects of the
2732 * pages from which cascading restrictions have come, false for
2733 * none, or true if such restrictions exist but $getPages was not
2734 * set. Second is an array like that returned by
2735 * Title::getAllRestrictions(), or an empty array if $getPages is
2738 public function getCascadeProtectionSources( $getPages = true ) {
2739 $pagerestrictions = array();
2741 if ( $this->mCascadeSources
!== null && $getPages ) {
2742 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2743 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2744 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2747 $dbr = wfGetDB( DB_SLAVE
);
2749 if ( $this->getNamespace() == NS_FILE
) {
2750 $tables = array( 'imagelinks', 'page_restrictions' );
2751 $where_clauses = array(
2752 'il_to' => $this->getDBkey(),
2757 $tables = array( 'templatelinks', 'page_restrictions' );
2758 $where_clauses = array(
2759 'tl_namespace' => $this->getNamespace(),
2760 'tl_title' => $this->getDBkey(),
2767 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2768 'pr_expiry', 'pr_type', 'pr_level' );
2769 $where_clauses[] = 'page_id=pr_page';
2772 $cols = array( 'pr_expiry' );
2775 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2777 $sources = $getPages ?
array() : false;
2778 $now = wfTimestampNow();
2780 foreach ( $res as $row ) {
2781 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2782 if ( $expiry > $now ) {
2784 $page_id = $row->pr_page
;
2785 $page_ns = $row->page_namespace
;
2786 $page_title = $row->page_title
;
2787 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2788 # Add groups needed for each restriction type if its not already there
2789 # Make sure this restriction type still exists
2791 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2792 $pagerestrictions[$row->pr_type
] = array();
2796 isset( $pagerestrictions[$row->pr_type
] )
2797 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2799 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2808 $this->mCascadeSources
= $sources;
2809 $this->mCascadingRestrictions
= $pagerestrictions;
2811 $this->mHasCascadingRestrictions
= $sources;
2814 return array( $sources, $pagerestrictions );
2818 * Accessor for mRestrictionsLoaded
2820 * @return bool Whether or not the page's restrictions have already been
2821 * loaded from the database
2824 public function areRestrictionsLoaded() {
2825 return $this->mRestrictionsLoaded
;
2829 * Accessor/initialisation for mRestrictions
2831 * @param string $action Action that permission needs to be checked for
2832 * @return array Restriction levels needed to take the action. All levels are
2833 * required. Note that restriction levels are normally user rights, but 'sysop'
2834 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2835 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2837 public function getRestrictions( $action ) {
2838 if ( !$this->mRestrictionsLoaded
) {
2839 $this->loadRestrictions();
2841 return isset( $this->mRestrictions
[$action] )
2842 ?
$this->mRestrictions
[$action]
2847 * Accessor/initialisation for mRestrictions
2849 * @return array Keys are actions, values are arrays as returned by
2850 * Title::getRestrictions()
2853 public function getAllRestrictions() {
2854 if ( !$this->mRestrictionsLoaded
) {
2855 $this->loadRestrictions();
2857 return $this->mRestrictions
;
2861 * Get the expiry time for the restriction against a given action
2863 * @param string $action
2864 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2865 * or not protected at all, or false if the action is not recognised.
2867 public function getRestrictionExpiry( $action ) {
2868 if ( !$this->mRestrictionsLoaded
) {
2869 $this->loadRestrictions();
2871 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2875 * Returns cascading restrictions for the current article
2879 function areRestrictionsCascading() {
2880 if ( !$this->mRestrictionsLoaded
) {
2881 $this->loadRestrictions();
2884 return $this->mCascadeRestriction
;
2888 * Loads a string into mRestrictions array
2890 * @param ResultWrapper $res Resource restrictions as an SQL result.
2891 * @param string $oldFashionedRestrictions Comma-separated list of page
2892 * restrictions from page table (pre 1.10)
2894 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2897 foreach ( $res as $row ) {
2901 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2905 * Compiles list of active page restrictions from both page table (pre 1.10)
2906 * and page_restrictions table for this existing page.
2907 * Public for usage by LiquidThreads.
2909 * @param array $rows Array of db result objects
2910 * @param string $oldFashionedRestrictions Comma-separated list of page
2911 * restrictions from page table (pre 1.10)
2913 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2914 $dbr = wfGetDB( DB_SLAVE
);
2916 $restrictionTypes = $this->getRestrictionTypes();
2918 foreach ( $restrictionTypes as $type ) {
2919 $this->mRestrictions
[$type] = array();
2920 $this->mRestrictionsExpiry
[$type] = 'infinity';
2923 $this->mCascadeRestriction
= false;
2925 # Backwards-compatibility: also load the restrictions from the page record (old format).
2926 if ( $oldFashionedRestrictions !== null ) {
2927 $this->mOldRestrictions
= $oldFashionedRestrictions;
2930 if ( $this->mOldRestrictions
=== false ) {
2931 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2932 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2935 if ( $this->mOldRestrictions
!= '' ) {
2936 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2937 $temp = explode( '=', trim( $restrict ) );
2938 if ( count( $temp ) == 1 ) {
2939 // old old format should be treated as edit/move restriction
2940 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2941 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2943 $restriction = trim( $temp[1] );
2944 if ( $restriction != '' ) { // some old entries are empty
2945 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2951 if ( count( $rows ) ) {
2952 # Current system - load second to make them override.
2953 $now = wfTimestampNow();
2955 # Cycle through all the restrictions.
2956 foreach ( $rows as $row ) {
2958 // Don't take care of restrictions types that aren't allowed
2959 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2963 // This code should be refactored, now that it's being used more generally,
2964 // But I don't really see any harm in leaving it in Block for now -werdna
2965 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2967 // Only apply the restrictions if they haven't expired!
2968 if ( !$expiry ||
$expiry > $now ) {
2969 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2970 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2972 $this->mCascadeRestriction |
= $row->pr_cascade
;
2977 $this->mRestrictionsLoaded
= true;
2981 * Load restrictions from the page_restrictions table
2983 * @param string $oldFashionedRestrictions Comma-separated list of page
2984 * restrictions from page table (pre 1.10)
2986 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2987 if ( !$this->mRestrictionsLoaded
) {
2988 $dbr = wfGetDB( DB_SLAVE
);
2989 if ( $this->exists() ) {
2990 $res = $dbr->select(
2991 'page_restrictions',
2992 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2993 array( 'pr_page' => $this->getArticleID() ),
2997 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2999 $title_protection = $this->getTitleProtection();
3001 if ( $title_protection ) {
3002 $now = wfTimestampNow();
3003 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
3005 if ( !$expiry ||
$expiry > $now ) {
3006 // Apply the restrictions
3007 $this->mRestrictionsExpiry
['create'] = $expiry;
3008 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
3009 } else { // Get rid of the old restrictions
3010 $this->mTitleProtection
= false;
3013 $this->mRestrictionsExpiry
['create'] = 'infinity';
3015 $this->mRestrictionsLoaded
= true;
3021 * Flush the protection cache in this object and force reload from the database.
3022 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3024 public function flushRestrictions() {
3025 $this->mRestrictionsLoaded
= false;
3026 $this->mTitleProtection
= null;
3030 * Purge expired restrictions from the page_restrictions table
3032 static function purgeExpiredRestrictions() {
3033 if ( wfReadOnly() ) {
3037 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3038 wfGetDB( DB_MASTER
),
3040 function ( IDatabase
$dbw, $fname ) {
3042 'page_restrictions',
3043 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3048 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3056 * Does this have subpages? (Warning, usually requires an extra DB query.)
3060 public function hasSubpages() {
3061 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3066 # We dynamically add a member variable for the purpose of this method
3067 # alone to cache the result. There's no point in having it hanging
3068 # around uninitialized in every Title object; therefore we only add it
3069 # if needed and don't declare it statically.
3070 if ( $this->mHasSubpages
=== null ) {
3071 $this->mHasSubpages
= false;
3072 $subpages = $this->getSubpages( 1 );
3073 if ( $subpages instanceof TitleArray
) {
3074 $this->mHasSubpages
= (bool)$subpages->count();
3078 return $this->mHasSubpages
;
3082 * Get all subpages of this page.
3084 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3085 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3086 * doesn't allow subpages
3088 public function getSubpages( $limit = -1 ) {
3089 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3093 $dbr = wfGetDB( DB_SLAVE
);
3094 $conds['page_namespace'] = $this->getNamespace();
3095 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3097 if ( $limit > -1 ) {
3098 $options['LIMIT'] = $limit;
3100 $this->mSubpages
= TitleArray
::newFromResult(
3101 $dbr->select( 'page',
3102 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3108 return $this->mSubpages
;
3112 * Is there a version of this page in the deletion archive?
3114 * @return int The number of archived revisions
3116 public function isDeleted() {
3117 if ( $this->getNamespace() < 0 ) {
3120 $dbr = wfGetDB( DB_SLAVE
);
3122 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3123 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3126 if ( $this->getNamespace() == NS_FILE
) {
3127 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3128 array( 'fa_name' => $this->getDBkey() ),
3137 * Is there a version of this page in the deletion archive?
3141 public function isDeletedQuick() {
3142 if ( $this->getNamespace() < 0 ) {
3145 $dbr = wfGetDB( DB_SLAVE
);
3146 $deleted = (bool)$dbr->selectField( 'archive', '1',
3147 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3150 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3151 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3152 array( 'fa_name' => $this->getDBkey() ),
3160 * Get the article ID for this Title from the link cache,
3161 * adding it if necessary
3163 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3165 * @return int The ID
3167 public function getArticleID( $flags = 0 ) {
3168 if ( $this->getNamespace() < 0 ) {
3169 $this->mArticleID
= 0;
3170 return $this->mArticleID
;
3172 $linkCache = LinkCache
::singleton();
3173 if ( $flags & self
::GAID_FOR_UPDATE
) {
3174 $oldUpdate = $linkCache->forUpdate( true );
3175 $linkCache->clearLink( $this );
3176 $this->mArticleID
= $linkCache->addLinkObj( $this );
3177 $linkCache->forUpdate( $oldUpdate );
3179 if ( -1 == $this->mArticleID
) {
3180 $this->mArticleID
= $linkCache->addLinkObj( $this );
3183 return $this->mArticleID
;
3187 * Is this an article that is a redirect page?
3188 * Uses link cache, adding it if necessary
3190 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3193 public function isRedirect( $flags = 0 ) {
3194 if ( !is_null( $this->mRedirect
) ) {
3195 return $this->mRedirect
;
3197 if ( !$this->getArticleID( $flags ) ) {
3198 $this->mRedirect
= false;
3199 return $this->mRedirect
;
3202 $linkCache = LinkCache
::singleton();
3203 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3204 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3205 if ( $cached === null ) {
3206 # Trust LinkCache's state over our own
3207 # LinkCache is telling us that the page doesn't exist, despite there being cached
3208 # data relating to an existing page in $this->mArticleID. Updaters should clear
3209 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3210 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3211 # LinkCache to refresh its data from the master.
3212 $this->mRedirect
= false;
3213 return $this->mRedirect
;
3216 $this->mRedirect
= (bool)$cached;
3218 return $this->mRedirect
;
3222 * What is the length of this page?
3223 * Uses link cache, adding it if necessary
3225 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3228 public function getLength( $flags = 0 ) {
3229 if ( $this->mLength
!= -1 ) {
3230 return $this->mLength
;
3232 if ( !$this->getArticleID( $flags ) ) {
3234 return $this->mLength
;
3236 $linkCache = LinkCache
::singleton();
3237 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3238 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3239 if ( $cached === null ) {
3240 # Trust LinkCache's state over our own, as for isRedirect()
3242 return $this->mLength
;
3245 $this->mLength
= intval( $cached );
3247 return $this->mLength
;
3251 * What is the page_latest field for this page?
3253 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3254 * @return int Int or 0 if the page doesn't exist
3256 public function getLatestRevID( $flags = 0 ) {
3257 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3258 return intval( $this->mLatestID
);
3260 if ( !$this->getArticleID( $flags ) ) {
3261 $this->mLatestID
= 0;
3262 return $this->mLatestID
;
3264 $linkCache = LinkCache
::singleton();
3265 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3266 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3267 if ( $cached === null ) {
3268 # Trust LinkCache's state over our own, as for isRedirect()
3269 $this->mLatestID
= 0;
3270 return $this->mLatestID
;
3273 $this->mLatestID
= intval( $cached );
3275 return $this->mLatestID
;
3279 * This clears some fields in this object, and clears any associated
3280 * keys in the "bad links" section of the link cache.
3282 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3283 * loading of the new page_id. It's also called from
3284 * WikiPage::doDeleteArticleReal()
3286 * @param int $newid The new Article ID
3288 public function resetArticleID( $newid ) {
3289 $linkCache = LinkCache
::singleton();
3290 $linkCache->clearLink( $this );
3292 if ( $newid === false ) {
3293 $this->mArticleID
= -1;
3295 $this->mArticleID
= intval( $newid );
3297 $this->mRestrictionsLoaded
= false;
3298 $this->mRestrictions
= array();
3299 $this->mOldRestrictions
= false;
3300 $this->mRedirect
= null;
3301 $this->mLength
= -1;
3302 $this->mLatestID
= false;
3303 $this->mContentModel
= false;
3304 $this->mEstimateRevisions
= null;
3305 $this->mPageLanguage
= false;
3306 $this->mDbPageLanguage
= null;
3307 $this->mIsBigDeletion
= null;
3310 public static function clearCaches() {
3311 $linkCache = LinkCache
::singleton();
3312 $linkCache->clear();
3314 $titleCache = self
::getTitleCache();
3315 $titleCache->clear();
3319 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3321 * @param string $text Containing title to capitalize
3322 * @param int $ns Namespace index, defaults to NS_MAIN
3323 * @return string Containing capitalized title
3325 public static function capitalize( $text, $ns = NS_MAIN
) {
3328 if ( MWNamespace
::isCapitalized( $ns ) ) {
3329 return $wgContLang->ucfirst( $text );
3336 * Secure and split - main initialisation function for this object
3338 * Assumes that mDbkeyform has been set, and is urldecoded
3339 * and uses underscores, but not otherwise munged. This function
3340 * removes illegal characters, splits off the interwiki and
3341 * namespace prefixes, sets the other forms, and canonicalizes
3344 * @throws MalformedTitleException On invalid titles
3345 * @return bool True on success
3347 private function secureAndSplit() {
3349 $this->mInterwiki
= '';
3350 $this->mFragment
= '';
3351 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3353 $dbkey = $this->mDbkeyform
;
3355 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3356 // the parsing code with Title, while avoiding massive refactoring.
3357 // @todo: get rid of secureAndSplit, refactor parsing code.
3358 $titleParser = self
::getMediaWikiTitleCodec();
3359 // MalformedTitleException can be thrown here
3360 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3363 $this->setFragment( '#' . $parts['fragment'] );
3364 $this->mInterwiki
= $parts['interwiki'];
3365 $this->mLocalInterwiki
= $parts['local_interwiki'];
3366 $this->mNamespace
= $parts['namespace'];
3367 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3369 $this->mDbkeyform
= $parts['dbkey'];
3370 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3371 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3373 # We already know that some pages won't be in the database!
3374 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3375 $this->mArticleID
= 0;
3382 * Get an array of Title objects linking to this Title
3383 * Also stores the IDs in the link cache.
3385 * WARNING: do not use this function on arbitrary user-supplied titles!
3386 * On heavily-used templates it will max out the memory.
3388 * @param array $options May be FOR UPDATE
3389 * @param string $table Table name
3390 * @param string $prefix Fields prefix
3391 * @return Title[] Array of Title objects linking here
3393 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3394 if ( count( $options ) > 0 ) {
3395 $db = wfGetDB( DB_MASTER
);
3397 $db = wfGetDB( DB_SLAVE
);
3401 array( 'page', $table ),
3402 self
::getSelectFields(),
3404 "{$prefix}_from=page_id",
3405 "{$prefix}_namespace" => $this->getNamespace(),
3406 "{$prefix}_title" => $this->getDBkey() ),
3412 if ( $res->numRows() ) {
3413 $linkCache = LinkCache
::singleton();
3414 foreach ( $res as $row ) {
3415 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3417 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3418 $retVal[] = $titleObj;
3426 * Get an array of Title objects using this Title as a template
3427 * Also stores the IDs in the link cache.
3429 * WARNING: do not use this function on arbitrary user-supplied titles!
3430 * On heavily-used templates it will max out the memory.
3432 * @param array $options May be FOR UPDATE
3433 * @return Title[] Array of Title the Title objects linking here
3435 public function getTemplateLinksTo( $options = array() ) {
3436 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3440 * Get an array of Title objects linked from this Title
3441 * Also stores the IDs in the link cache.
3443 * WARNING: do not use this function on arbitrary user-supplied titles!
3444 * On heavily-used templates it will max out the memory.
3446 * @param array $options May be FOR UPDATE
3447 * @param string $table Table name
3448 * @param string $prefix Fields prefix
3449 * @return array Array of Title objects linking here
3451 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3452 $id = $this->getArticleID();
3454 # If the page doesn't exist; there can't be any link from this page
3459 if ( count( $options ) > 0 ) {
3460 $db = wfGetDB( DB_MASTER
);
3462 $db = wfGetDB( DB_SLAVE
);
3465 $blNamespace = "{$prefix}_namespace";
3466 $blTitle = "{$prefix}_title";
3469 array( $table, 'page' ),
3471 array( $blNamespace, $blTitle ),
3472 WikiPage
::selectFields()
3474 array( "{$prefix}_from" => $id ),
3477 array( 'page' => array(
3479 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3484 $linkCache = LinkCache
::singleton();
3485 foreach ( $res as $row ) {
3486 if ( $row->page_id
) {
3487 $titleObj = Title
::newFromRow( $row );
3489 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3490 $linkCache->addBadLinkObj( $titleObj );
3492 $retVal[] = $titleObj;
3499 * Get an array of Title objects used on this Title as a template
3500 * Also stores the IDs in the link cache.
3502 * WARNING: do not use this function on arbitrary user-supplied titles!
3503 * On heavily-used templates it will max out the memory.
3505 * @param array $options May be FOR UPDATE
3506 * @return Title[] Array of Title the Title objects used here
3508 public function getTemplateLinksFrom( $options = array() ) {
3509 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3513 * Get an array of Title objects referring to non-existent articles linked
3516 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3517 * should use redirect table in this case).
3518 * @return Title[] Array of Title the Title objects
3520 public function getBrokenLinksFrom() {
3521 if ( $this->getArticleID() == 0 ) {
3522 # All links from article ID 0 are false positives
3526 $dbr = wfGetDB( DB_SLAVE
);
3527 $res = $dbr->select(
3528 array( 'page', 'pagelinks' ),
3529 array( 'pl_namespace', 'pl_title' ),
3531 'pl_from' => $this->getArticleID(),
3532 'page_namespace IS NULL'
3534 __METHOD__
, array(),
3538 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3544 foreach ( $res as $row ) {
3545 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3551 * Get a list of URLs to purge from the CDN cache when this
3554 * @return string[] Array of String the URLs
3556 public function getCdnUrls() {
3558 $this->getInternalURL(),
3559 $this->getInternalURL( 'action=history' )
3562 $pageLang = $this->getPageLanguage();
3563 if ( $pageLang->hasVariants() ) {
3564 $variants = $pageLang->getVariants();
3565 foreach ( $variants as $vCode ) {
3566 $urls[] = $this->getInternalURL( $vCode );
3570 // If we are looking at a css/js user subpage, purge the action=raw.
3571 if ( $this->isJsSubpage() ) {
3572 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3573 } elseif ( $this->isCssSubpage() ) {
3574 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3577 Hooks
::run( 'TitleSquidURLs', array( $this, &$urls ) );
3582 * @deprecated since 1.27 use getCdnUrls()
3584 public function getSquidURLs() {
3585 return $this->getCdnUrls();
3589 * Purge all applicable CDN URLs
3591 public function purgeSquid() {
3592 DeferredUpdates
::addUpdate(
3593 new CdnCacheUpdate( $this->getCdnUrls() ),
3594 DeferredUpdates
::PRESEND
3599 * Move this page without authentication
3601 * @deprecated since 1.25 use MovePage class instead
3602 * @param Title $nt The new page Title
3603 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3605 public function moveNoAuth( &$nt ) {
3606 wfDeprecated( __METHOD__
, '1.25' );
3607 return $this->moveTo( $nt, false );
3611 * Check whether a given move operation would be valid.
3612 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3614 * @deprecated since 1.25, use MovePage's methods instead
3615 * @param Title $nt The new title
3616 * @param bool $auth Whether to check user permissions (uses $wgUser)
3617 * @param string $reason Is the log summary of the move, used for spam checking
3618 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3620 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3623 if ( !( $nt instanceof Title
) ) {
3624 // Normally we'd add this to $errors, but we'll get
3625 // lots of syntax errors if $nt is not an object
3626 return array( array( 'badtitletext' ) );
3629 $mp = new MovePage( $this, $nt );
3630 $errors = $mp->isValidMove()->getErrorsArray();
3632 $errors = wfMergeErrorArrays(
3634 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3638 return $errors ?
: true;
3642 * Check if the requested move target is a valid file move target
3643 * @todo move this to MovePage
3644 * @param Title $nt Target title
3645 * @return array List of errors
3647 protected function validateFileMoveOperation( $nt ) {
3652 $destFile = wfLocalFile( $nt );
3653 $destFile->load( File
::READ_LATEST
);
3654 if ( !$wgUser->isAllowed( 'reupload-shared' )
3655 && !$destFile->exists() && wfFindFile( $nt )
3657 $errors[] = array( 'file-exists-sharedrepo' );
3664 * Move a title to a new location
3666 * @deprecated since 1.25, use the MovePage class instead
3667 * @param Title $nt The new title
3668 * @param bool $auth Indicates whether $wgUser's permissions
3670 * @param string $reason The reason for the move
3671 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3672 * Ignored if the user doesn't have the suppressredirect right.
3673 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3675 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3677 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3678 if ( is_array( $err ) ) {
3679 // Auto-block user's IP if the account was "hard" blocked
3680 $wgUser->spreadAnyEditBlock();
3683 // Check suppressredirect permission
3684 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3685 $createRedirect = true;
3688 $mp = new MovePage( $this, $nt );
3689 $status = $mp->move( $wgUser, $reason, $createRedirect );
3690 if ( $status->isOK() ) {
3693 return $status->getErrorsArray();
3698 * Move this page's subpages to be subpages of $nt
3700 * @param Title $nt Move target
3701 * @param bool $auth Whether $wgUser's permissions should be checked
3702 * @param string $reason The reason for the move
3703 * @param bool $createRedirect Whether to create redirects from the old subpages to
3704 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3705 * @return array Array with old page titles as keys, and strings (new page titles) or
3706 * arrays (errors) as values, or an error array with numeric indices if no pages
3709 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3710 global $wgMaximumMovedPages;
3711 // Check permissions
3712 if ( !$this->userCan( 'move-subpages' ) ) {
3713 return array( 'cant-move-subpages' );
3715 // Do the source and target namespaces support subpages?
3716 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3717 return array( 'namespace-nosubpages',
3718 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3720 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3721 return array( 'namespace-nosubpages',
3722 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3725 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3728 foreach ( $subpages as $oldSubpage ) {
3730 if ( $count > $wgMaximumMovedPages ) {
3731 $retval[$oldSubpage->getPrefixedText()] =
3732 array( 'movepage-max-pages',
3733 $wgMaximumMovedPages );
3737 // We don't know whether this function was called before
3738 // or after moving the root page, so check both
3740 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3741 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3743 // When moving a page to a subpage of itself,
3744 // don't move it twice
3747 $newPageName = preg_replace(
3748 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3749 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3750 $oldSubpage->getDBkey() );
3751 if ( $oldSubpage->isTalkPage() ) {
3752 $newNs = $nt->getTalkPage()->getNamespace();
3754 $newNs = $nt->getSubjectPage()->getNamespace();
3756 # Bug 14385: we need makeTitleSafe because the new page names may
3757 # be longer than 255 characters.
3758 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3760 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3761 if ( $success === true ) {
3762 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3764 $retval[$oldSubpage->getPrefixedText()] = $success;
3771 * Checks if this page is just a one-rev redirect.
3772 * Adds lock, so don't use just for light purposes.
3776 public function isSingleRevRedirect() {
3777 global $wgContentHandlerUseDB;
3779 $dbw = wfGetDB( DB_MASTER
);
3782 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3783 if ( $wgContentHandlerUseDB ) {
3784 $fields[] = 'page_content_model';
3787 $row = $dbw->selectRow( 'page',
3791 array( 'FOR UPDATE' )
3793 # Cache some fields we may want
3794 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3795 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3796 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3797 $this->mContentModel
= $row && isset( $row->page_content_model
)
3798 ?
strval( $row->page_content_model
)
3801 if ( !$this->mRedirect
) {
3804 # Does the article have a history?
3805 $row = $dbw->selectField( array( 'page', 'revision' ),
3807 array( 'page_namespace' => $this->getNamespace(),
3808 'page_title' => $this->getDBkey(),
3810 'page_latest != rev_id'
3813 array( 'FOR UPDATE' )
3815 # Return true if there was no history
3816 return ( $row === false );
3820 * Checks if $this can be moved to a given Title
3821 * - Selects for update, so don't call it unless you mean business
3823 * @deprecated since 1.25, use MovePage's methods instead
3824 * @param Title $nt The new title to check
3827 public function isValidMoveTarget( $nt ) {
3828 # Is it an existing file?
3829 if ( $nt->getNamespace() == NS_FILE
) {
3830 $file = wfLocalFile( $nt );
3831 $file->load( File
::READ_LATEST
);
3832 if ( $file->exists() ) {
3833 wfDebug( __METHOD__
. ": file exists\n" );
3837 # Is it a redirect with no history?
3838 if ( !$nt->isSingleRevRedirect() ) {
3839 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3842 # Get the article text
3843 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3844 if ( !is_object( $rev ) ) {
3847 $content = $rev->getContent();
3848 # Does the redirect point to the source?
3849 # Or is it a broken self-redirect, usually caused by namespace collisions?
3850 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3852 if ( $redirTitle ) {
3853 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3854 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3855 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3861 # Fail safe (not a redirect after all. strange.)
3862 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3863 " is a redirect, but it doesn't contain a valid redirect.\n" );
3869 * Get categories to which this Title belongs and return an array of
3870 * categories' names.
3872 * @return array Array of parents in the form:
3873 * $parent => $currentarticle
3875 public function getParentCategories() {
3880 $titleKey = $this->getArticleID();
3882 if ( $titleKey === 0 ) {
3886 $dbr = wfGetDB( DB_SLAVE
);
3888 $res = $dbr->select(
3891 array( 'cl_from' => $titleKey ),
3895 if ( $res->numRows() > 0 ) {
3896 foreach ( $res as $row ) {
3897 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3898 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3905 * Get a tree of parent categories
3907 * @param array $children Array with the children in the keys, to check for circular refs
3908 * @return array Tree of parent categories
3910 public function getParentCategoryTree( $children = array() ) {
3912 $parents = $this->getParentCategories();
3915 foreach ( $parents as $parent => $current ) {
3916 if ( array_key_exists( $parent, $children ) ) {
3917 # Circular reference
3918 $stack[$parent] = array();
3920 $nt = Title
::newFromText( $parent );
3922 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3932 * Get an associative array for selecting this title from
3935 * @return array Array suitable for the $where parameter of DB::select()
3937 public function pageCond() {
3938 if ( $this->mArticleID
> 0 ) {
3939 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3940 return array( 'page_id' => $this->mArticleID
);
3942 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3947 * Get the revision ID of the previous revision
3949 * @param int $revId Revision ID. Get the revision that was before this one.
3950 * @param int $flags Title::GAID_FOR_UPDATE
3951 * @return int|bool Old revision ID, or false if none exists
3953 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3954 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3955 $revId = $db->selectField( 'revision', 'rev_id',
3957 'rev_page' => $this->getArticleID( $flags ),
3958 'rev_id < ' . intval( $revId )
3961 array( 'ORDER BY' => 'rev_id DESC' )
3964 if ( $revId === false ) {
3967 return intval( $revId );
3972 * Get the revision ID of the next revision
3974 * @param int $revId Revision ID. Get the revision that was after this one.
3975 * @param int $flags Title::GAID_FOR_UPDATE
3976 * @return int|bool Next revision ID, or false if none exists
3978 public function getNextRevisionID( $revId, $flags = 0 ) {
3979 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3980 $revId = $db->selectField( 'revision', 'rev_id',
3982 'rev_page' => $this->getArticleID( $flags ),
3983 'rev_id > ' . intval( $revId )
3986 array( 'ORDER BY' => 'rev_id' )
3989 if ( $revId === false ) {
3992 return intval( $revId );
3997 * Get the first revision of the page
3999 * @param int $flags Title::GAID_FOR_UPDATE
4000 * @return Revision|null If page doesn't exist
4002 public function getFirstRevision( $flags = 0 ) {
4003 $pageId = $this->getArticleID( $flags );
4005 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4006 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4007 array( 'rev_page' => $pageId ),
4009 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4012 return new Revision( $row );
4019 * Get the oldest revision timestamp of this page
4021 * @param int $flags Title::GAID_FOR_UPDATE
4022 * @return string MW timestamp
4024 public function getEarliestRevTime( $flags = 0 ) {
4025 $rev = $this->getFirstRevision( $flags );
4026 return $rev ?
$rev->getTimestamp() : null;
4030 * Check if this is a new page
4034 public function isNewPage() {
4035 $dbr = wfGetDB( DB_SLAVE
);
4036 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4040 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4044 public function isBigDeletion() {
4045 global $wgDeleteRevisionsLimit;
4047 if ( !$wgDeleteRevisionsLimit ) {
4051 if ( $this->mIsBigDeletion
=== null ) {
4052 $dbr = wfGetDB( DB_SLAVE
);
4054 $revCount = $dbr->selectRowCount(
4057 array( 'rev_page' => $this->getArticleID() ),
4059 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4062 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4065 return $this->mIsBigDeletion
;
4069 * Get the approximate revision count of this page.
4073 public function estimateRevisionCount() {
4074 if ( !$this->exists() ) {
4078 if ( $this->mEstimateRevisions
=== null ) {
4079 $dbr = wfGetDB( DB_SLAVE
);
4080 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4081 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4084 return $this->mEstimateRevisions
;
4088 * Get the number of revisions between the given revision.
4089 * Used for diffs and other things that really need it.
4091 * @param int|Revision $old Old revision or rev ID (first before range)
4092 * @param int|Revision $new New revision or rev ID (first after range)
4093 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4094 * @return int Number of revisions between these revisions.
4096 public function countRevisionsBetween( $old, $new, $max = null ) {
4097 if ( !( $old instanceof Revision
) ) {
4098 $old = Revision
::newFromTitle( $this, (int)$old );
4100 if ( !( $new instanceof Revision
) ) {
4101 $new = Revision
::newFromTitle( $this, (int)$new );
4103 if ( !$old ||
!$new ) {
4104 return 0; // nothing to compare
4106 $dbr = wfGetDB( DB_SLAVE
);
4108 'rev_page' => $this->getArticleID(),
4109 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4110 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4112 if ( $max !== null ) {
4113 return $dbr->selectRowCount( 'revision', '1',
4116 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4119 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4124 * Get the authors between the given revisions or revision IDs.
4125 * Used for diffs and other things that really need it.
4129 * @param int|Revision $old Old revision or rev ID (first before range by default)
4130 * @param int|Revision $new New revision or rev ID (first after range by default)
4131 * @param int $limit Maximum number of authors
4132 * @param string|array $options (Optional): Single option, or an array of options:
4133 * 'include_old' Include $old in the range; $new is excluded.
4134 * 'include_new' Include $new in the range; $old is excluded.
4135 * 'include_both' Include both $old and $new in the range.
4136 * Unknown option values are ignored.
4137 * @return array|null Names of revision authors in the range; null if not both revisions exist
4139 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4140 if ( !( $old instanceof Revision
) ) {
4141 $old = Revision
::newFromTitle( $this, (int)$old );
4143 if ( !( $new instanceof Revision
) ) {
4144 $new = Revision
::newFromTitle( $this, (int)$new );
4146 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4147 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4148 // in the sanity check below?
4149 if ( !$old ||
!$new ) {
4150 return null; // nothing to compare
4155 $options = (array)$options;
4156 if ( in_array( 'include_old', $options ) ) {
4159 if ( in_array( 'include_new', $options ) ) {
4162 if ( in_array( 'include_both', $options ) ) {
4166 // No DB query needed if $old and $new are the same or successive revisions:
4167 if ( $old->getId() === $new->getId() ) {
4168 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4170 array( $old->getUserText( Revision
::RAW
) );
4171 } elseif ( $old->getId() === $new->getParentId() ) {
4172 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4173 $authors[] = $old->getUserText( Revision
::RAW
);
4174 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4175 $authors[] = $new->getUserText( Revision
::RAW
);
4177 } elseif ( $old_cmp === '>=' ) {
4178 $authors[] = $old->getUserText( Revision
::RAW
);
4179 } elseif ( $new_cmp === '<=' ) {
4180 $authors[] = $new->getUserText( Revision
::RAW
);
4184 $dbr = wfGetDB( DB_SLAVE
);
4185 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4187 'rev_page' => $this->getArticleID(),
4188 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4189 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4191 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4193 foreach ( $res as $row ) {
4194 $authors[] = $row->rev_user_text
;
4200 * Get the number of authors between the given revisions or revision IDs.
4201 * Used for diffs and other things that really need it.
4203 * @param int|Revision $old Old revision or rev ID (first before range by default)
4204 * @param int|Revision $new New revision or rev ID (first after range by default)
4205 * @param int $limit Maximum number of authors
4206 * @param string|array $options (Optional): Single option, or an array of options:
4207 * 'include_old' Include $old in the range; $new is excluded.
4208 * 'include_new' Include $new in the range; $old is excluded.
4209 * 'include_both' Include both $old and $new in the range.
4210 * Unknown option values are ignored.
4211 * @return int Number of revision authors in the range; zero if not both revisions exist
4213 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4214 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4215 return $authors ?
count( $authors ) : 0;
4219 * Compare with another title.
4221 * @param Title $title
4224 public function equals( Title
$title ) {
4225 // Note: === is necessary for proper matching of number-like titles.
4226 return $this->getInterwiki() === $title->getInterwiki()
4227 && $this->getNamespace() == $title->getNamespace()
4228 && $this->getDBkey() === $title->getDBkey();
4232 * Check if this title is a subpage of another title
4234 * @param Title $title
4237 public function isSubpageOf( Title
$title ) {
4238 return $this->getInterwiki() === $title->getInterwiki()
4239 && $this->getNamespace() == $title->getNamespace()
4240 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4244 * Check if page exists. For historical reasons, this function simply
4245 * checks for the existence of the title in the page table, and will
4246 * thus return false for interwiki links, special pages and the like.
4247 * If you want to know if a title can be meaningfully viewed, you should
4248 * probably call the isKnown() method instead.
4250 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4251 * from master/for update
4254 public function exists( $flags = 0 ) {
4255 $exists = $this->getArticleID( $flags ) != 0;
4256 Hooks
::run( 'TitleExists', array( $this, &$exists ) );
4261 * Should links to this title be shown as potentially viewable (i.e. as
4262 * "bluelinks"), even if there's no record by this title in the page
4265 * This function is semi-deprecated for public use, as well as somewhat
4266 * misleadingly named. You probably just want to call isKnown(), which
4267 * calls this function internally.
4269 * (ISSUE: Most of these checks are cheap, but the file existence check
4270 * can potentially be quite expensive. Including it here fixes a lot of
4271 * existing code, but we might want to add an optional parameter to skip
4272 * it and any other expensive checks.)
4276 public function isAlwaysKnown() {
4280 * Allows overriding default behavior for determining if a page exists.
4281 * If $isKnown is kept as null, regular checks happen. If it's
4282 * a boolean, this value is returned by the isKnown method.
4286 * @param Title $title
4287 * @param bool|null $isKnown
4289 Hooks
::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4291 if ( !is_null( $isKnown ) ) {
4295 if ( $this->isExternal() ) {
4296 return true; // any interwiki link might be viewable, for all we know
4299 switch ( $this->mNamespace
) {
4302 // file exists, possibly in a foreign repo
4303 return (bool)wfFindFile( $this );
4305 // valid special page
4306 return SpecialPageFactory
::exists( $this->getDBkey() );
4308 // selflink, possibly with fragment
4309 return $this->mDbkeyform
== '';
4311 // known system message
4312 return $this->hasSourceText() !== false;
4319 * Does this title refer to a page that can (or might) be meaningfully
4320 * viewed? In particular, this function may be used to determine if
4321 * links to the title should be rendered as "bluelinks" (as opposed to
4322 * "redlinks" to non-existent pages).
4323 * Adding something else to this function will cause inconsistency
4324 * since LinkHolderArray calls isAlwaysKnown() and does its own
4325 * page existence check.
4329 public function isKnown() {
4330 return $this->isAlwaysKnown() ||
$this->exists();
4334 * Does this page have source text?
4338 public function hasSourceText() {
4339 if ( $this->exists() ) {
4343 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4344 // If the page doesn't exist but is a known system message, default
4345 // message content will be displayed, same for language subpages-
4346 // Use always content language to avoid loading hundreds of languages
4347 // to get the link color.
4349 list( $name, ) = MessageCache
::singleton()->figureMessage(
4350 $wgContLang->lcfirst( $this->getText() )
4352 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4353 return $message->exists();
4360 * Get the default message text or false if the message doesn't exist
4362 * @return string|bool
4364 public function getDefaultMessageText() {
4367 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4371 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4372 $wgContLang->lcfirst( $this->getText() )
4374 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4376 if ( $message->exists() ) {
4377 return $message->plain();
4384 * Updates page_touched for this page; called from LinksUpdate.php
4386 * @param string $purgeTime [optional] TS_MW timestamp
4387 * @return bool True if the update succeeded
4389 public function invalidateCache( $purgeTime = null ) {
4390 if ( wfReadOnly() ) {
4394 if ( $this->mArticleID
=== 0 ) {
4395 return true; // avoid gap locking if we know it's not there
4398 $method = __METHOD__
;
4399 $dbw = wfGetDB( DB_MASTER
);
4400 $conds = $this->pageCond();
4401 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4402 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4406 array( 'page_touched' => $dbTimestamp ),
4407 $conds +
array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4416 * Update page_touched timestamps and send CDN purge messages for
4417 * pages linking to this title. May be sent to the job queue depending
4418 * on the number of links. Typically called on create and delete.
4420 public function touchLinks() {
4421 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4422 if ( $this->getNamespace() == NS_CATEGORY
) {
4423 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4428 * Get the last touched timestamp
4430 * @param IDatabase $db Optional db
4431 * @return string Last-touched timestamp
4433 public function getTouched( $db = null ) {
4434 if ( $db === null ) {
4435 $db = wfGetDB( DB_SLAVE
);
4437 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4442 * Get the timestamp when this page was updated since the user last saw it.
4445 * @return string|null
4447 public function getNotificationTimestamp( $user = null ) {
4450 // Assume current user if none given
4454 // Check cache first
4455 $uid = $user->getId();
4459 // avoid isset here, as it'll return false for null entries
4460 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4461 return $this->mNotificationTimestamp
[$uid];
4463 // Don't cache too much!
4464 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4465 $this->mNotificationTimestamp
= array();
4468 $watchedItem = WatchedItem
::fromUserTitle( $user, $this );
4469 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4471 return $this->mNotificationTimestamp
[$uid];
4475 * Generate strings used for xml 'id' names in monobook tabs
4477 * @param string $prepend Defaults to 'nstab-'
4478 * @return string XML 'id' name
4480 public function getNamespaceKey( $prepend = 'nstab-' ) {
4482 // Gets the subject namespace if this title
4483 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4484 // Checks if canonical namespace name exists for namespace
4485 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4486 // Uses canonical namespace name
4487 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4489 // Uses text of namespace
4490 $namespaceKey = $this->getSubjectNsText();
4492 // Makes namespace key lowercase
4493 $namespaceKey = $wgContLang->lc( $namespaceKey );
4495 if ( $namespaceKey == '' ) {
4496 $namespaceKey = 'main';
4498 // Changes file to image for backwards compatibility
4499 if ( $namespaceKey == 'file' ) {
4500 $namespaceKey = 'image';
4502 return $prepend . $namespaceKey;
4506 * Get all extant redirects to this Title
4508 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4509 * @return Title[] Array of Title redirects to this title
4511 public function getRedirectsHere( $ns = null ) {
4514 $dbr = wfGetDB( DB_SLAVE
);
4516 'rd_namespace' => $this->getNamespace(),
4517 'rd_title' => $this->getDBkey(),
4520 if ( $this->isExternal() ) {
4521 $where['rd_interwiki'] = $this->getInterwiki();
4523 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4525 if ( !is_null( $ns ) ) {
4526 $where['page_namespace'] = $ns;
4529 $res = $dbr->select(
4530 array( 'redirect', 'page' ),
4531 array( 'page_namespace', 'page_title' ),
4536 foreach ( $res as $row ) {
4537 $redirs[] = self
::newFromRow( $row );
4543 * Check if this Title is a valid redirect target
4547 public function isValidRedirectTarget() {
4548 global $wgInvalidRedirectTargets;
4550 if ( $this->isSpecialPage() ) {
4551 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4552 if ( $this->isSpecial( 'Userlogout' ) ) {
4556 foreach ( $wgInvalidRedirectTargets as $target ) {
4557 if ( $this->isSpecial( $target ) ) {
4567 * Get a backlink cache object
4569 * @return BacklinkCache
4571 public function getBacklinkCache() {
4572 return BacklinkCache
::get( $this );
4576 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4580 public function canUseNoindex() {
4581 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4583 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4584 ?
$wgContentNamespaces
4585 : $wgExemptFromUserRobotsControl;
4587 return !in_array( $this->mNamespace
, $bannedNamespaces );
4592 * Returns the raw sort key to be used for categories, with the specified
4593 * prefix. This will be fed to Collation::getSortKey() to get a
4594 * binary sortkey that can be used for actual sorting.
4596 * @param string $prefix The prefix to be used, specified using
4597 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4601 public function getCategorySortkey( $prefix = '' ) {
4602 $unprefixed = $this->getText();
4604 // Anything that uses this hook should only depend
4605 // on the Title object passed in, and should probably
4606 // tell the users to run updateCollations.php --force
4607 // in order to re-sort existing category relations.
4608 Hooks
::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4609 if ( $prefix !== '' ) {
4610 # Separate with a line feed, so the unprefixed part is only used as
4611 # a tiebreaker when two pages have the exact same prefix.
4612 # In UCA, tab is the only character that can sort above LF
4613 # so we strip both of them from the original prefix.
4614 $prefix = strtr( $prefix, "\n\t", ' ' );
4615 return "$prefix\n$unprefixed";
4621 * Get the language in which the content of this page is written in
4622 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4623 * e.g. $wgLang (such as special pages, which are in the user language).
4628 public function getPageLanguage() {
4629 global $wgLang, $wgLanguageCode;
4630 if ( $this->isSpecialPage() ) {
4631 // special pages are in the user language
4635 // Checking if DB language is set
4636 if ( $this->mDbPageLanguage
) {
4637 return wfGetLangObj( $this->mDbPageLanguage
);
4640 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4641 // Note that this may depend on user settings, so the cache should
4642 // be only per-request.
4643 // NOTE: ContentHandler::getPageLanguage() may need to load the
4644 // content to determine the page language!
4645 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4647 $contentHandler = ContentHandler
::getForTitle( $this );
4648 $langObj = $contentHandler->getPageLanguage( $this );
4649 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4651 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4658 * Get the language in which the content of this page is written when
4659 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4660 * e.g. $wgLang (such as special pages, which are in the user language).
4665 public function getPageViewLanguage() {
4668 if ( $this->isSpecialPage() ) {
4669 // If the user chooses a variant, the content is actually
4670 // in a language whose code is the variant code.
4671 $variant = $wgLang->getPreferredVariant();
4672 if ( $wgLang->getCode() !== $variant ) {
4673 return Language
::factory( $variant );
4679 // @note Can't be cached persistently, depends on user settings.
4680 // @note ContentHandler::getPageViewLanguage() may need to load the
4681 // content to determine the page language!
4682 $contentHandler = ContentHandler
::getForTitle( $this );
4683 $pageLang = $contentHandler->getPageViewLanguage( $this );
4688 * Get a list of rendered edit notices for this page.
4690 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4691 * they will already be wrapped in paragraphs.
4694 * @param int $oldid Revision ID that's being edited
4697 public function getEditNotices( $oldid = 0 ) {
4700 // Optional notice for the entire namespace
4701 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4702 $msg = wfMessage( $editnotice_ns );
4703 if ( $msg->exists() ) {
4704 $html = $msg->parseAsBlock();
4705 // Edit notices may have complex logic, but output nothing (T91715)
4706 if ( trim( $html ) !== '' ) {
4707 $notices[$editnotice_ns] = Html
::rawElement(
4709 array( 'class' => array(
4711 'mw-editnotice-namespace',
4712 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4719 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4720 // Optional notice for page itself and any parent page
4721 $parts = explode( '/', $this->getDBkey() );
4722 $editnotice_base = $editnotice_ns;
4723 while ( count( $parts ) > 0 ) {
4724 $editnotice_base .= '-' . array_shift( $parts );
4725 $msg = wfMessage( $editnotice_base );
4726 if ( $msg->exists() ) {
4727 $html = $msg->parseAsBlock();
4728 if ( trim( $html ) !== '' ) {
4729 $notices[$editnotice_base] = Html
::rawElement(
4731 array( 'class' => array(
4733 'mw-editnotice-base',
4734 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4742 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4743 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4744 $msg = wfMessage( $editnoticeText );
4745 if ( $msg->exists() ) {
4746 $html = $msg->parseAsBlock();
4747 if ( trim( $html ) !== '' ) {
4748 $notices[$editnoticeText] = Html
::rawElement(
4750 array( 'class' => array(
4752 'mw-editnotice-page',
4753 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4761 Hooks
::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4768 public function __sleep() {
4776 'mDefaultNamespace',
4780 public function __wakeup() {
4781 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4782 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4783 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );