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 TitleParser
166 private static function getTitleParser() {
167 global $wgContLang, $wgLocalInterwikis;
169 static $titleCodec = null;
170 static $titleCodecFingerprint = null;
172 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
173 // make sure we are using the right one. To detect changes over the course
174 // of a request, we remember a fingerprint of the config used to create the
175 // codec singleton, and re-create it if the fingerprint doesn't match.
176 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
178 if ( $fingerprint !== $titleCodecFingerprint ) {
182 if ( !$titleCodec ) {
183 $titleCodec = new MediaWikiTitleCodec(
185 GenderCache
::singleton(),
188 $titleCodecFingerprint = $fingerprint;
195 * B/C kludge: provide a TitleParser for use by Title.
196 * Ideally, Title would have no methods that need this.
197 * Avoid usage of this singleton by using TitleValue
198 * and the associated services when possible.
200 * @return TitleFormatter
202 private static function getTitleFormatter() {
203 // NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
204 // which implements TitleFormatter.
205 return self
::getTitleParser();
208 function __construct() {
212 * Create a new Title from a prefixed DB key
214 * @param string $key The database key, which has underscores
215 * instead of spaces, possibly including namespace and
217 * @return Title|null Title, or null on an error
219 public static function newFromDBkey( $key ) {
221 $t->mDbkeyform
= $key;
224 $t->secureAndSplit();
226 } catch ( MalformedTitleException
$ex ) {
232 * Create a new Title from a TitleValue
234 * @param TitleValue $titleValue Assumed to be safe.
238 public static function newFromTitleValue( TitleValue
$titleValue ) {
239 return self
::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|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 if ( $text !== null && !is_string( $text ) ) {
274 wfDebugLog( 'T76305', wfGetAllCallers( 5 ) );
277 if ( $text === null ) {
282 return Title
::newFromTextThrow( $text, $defaultNamespace );
283 } catch ( MalformedTitleException
$ex ) {
289 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
290 * rather than returning null.
292 * The exception subclasses encode detailed information about why the title is invalid.
294 * @see Title::newFromText
297 * @param string $text Title text to check
298 * @param int $defaultNamespace
299 * @throws MalformedTitleException If the title is invalid
302 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
303 if ( is_object( $text ) ) {
304 throw new MWException( '$text must be a string, given an object' );
307 $titleCache = self
::getTitleCache();
309 // Wiki pages often contain multiple links to the same page.
310 // Title normalization and parsing can become expensive on pages with many
311 // links, so we can save a little time by caching them.
312 // In theory these are value objects and won't get changed...
313 if ( $defaultNamespace == NS_MAIN
) {
314 $t = $titleCache->get( $text );
320 // Convert things like é ā or 〗 into normalized (bug 14952) text
321 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
324 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
325 $t->mDefaultNamespace
= intval( $defaultNamespace );
327 $t->secureAndSplit();
328 if ( $defaultNamespace == NS_MAIN
) {
329 $titleCache->set( $text, $t );
335 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
337 * Example of wrong and broken code:
338 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
340 * Example of right code:
341 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
343 * Create a new Title from URL-encoded text. Ensures that
344 * the given title's length does not exceed the maximum.
346 * @param string $url The title, as might be taken from a URL
347 * @return Title|null The new object, or null on an error
349 public static function newFromURL( $url ) {
352 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
353 # but some URLs used it as a space replacement and they still come
354 # from some external search tools.
355 if ( strpos( self
::legalChars(), '+' ) === false ) {
356 $url = strtr( $url, '+', ' ' );
359 $t->mDbkeyform
= strtr( $url, ' ', '_' );
362 $t->secureAndSplit();
364 } catch ( MalformedTitleException
$ex ) {
370 * @return HashBagOStuff
372 private static function getTitleCache() {
373 if ( self
::$titleCache == null ) {
374 self
::$titleCache = new HashBagOStuff( array( 'maxKeys' => self
::CACHE_MAX
) );
376 return self
::$titleCache;
380 * Returns a list of fields that are to be selected for initializing Title
381 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
382 * whether to include page_content_model.
386 protected static function getSelectFields() {
387 global $wgContentHandlerUseDB;
390 'page_namespace', 'page_title', 'page_id',
391 'page_len', 'page_is_redirect', 'page_latest',
394 if ( $wgContentHandlerUseDB ) {
395 $fields[] = 'page_content_model';
402 * Create a new Title from an article ID
404 * @param int $id The page_id corresponding to the Title to create
405 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
406 * @return Title|null The new object, or null on an error
408 public static function newFromID( $id, $flags = 0 ) {
409 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
410 $row = $db->selectRow(
412 self
::getSelectFields(),
413 array( 'page_id' => $id ),
416 if ( $row !== false ) {
417 $title = Title
::newFromRow( $row );
425 * Make an array of titles from an array of IDs
427 * @param int[] $ids Array of IDs
428 * @return Title[] Array of Titles
430 public static function newFromIDs( $ids ) {
431 if ( !count( $ids ) ) {
434 $dbr = wfGetDB( DB_SLAVE
);
438 self
::getSelectFields(),
439 array( 'page_id' => $ids ),
444 foreach ( $res as $row ) {
445 $titles[] = Title
::newFromRow( $row );
451 * Make a Title object from a DB row
453 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
454 * @return Title Corresponding Title
456 public static function newFromRow( $row ) {
457 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
458 $t->loadFromRow( $row );
463 * Load Title object fields from a DB row.
464 * If false is given, the title will be treated as non-existing.
466 * @param stdClass|bool $row Database row
468 public function loadFromRow( $row ) {
469 if ( $row ) { // page found
470 if ( isset( $row->page_id
) ) {
471 $this->mArticleID
= (int)$row->page_id
;
473 if ( isset( $row->page_len
) ) {
474 $this->mLength
= (int)$row->page_len
;
476 if ( isset( $row->page_is_redirect
) ) {
477 $this->mRedirect
= (bool)$row->page_is_redirect
;
479 if ( isset( $row->page_latest
) ) {
480 $this->mLatestID
= (int)$row->page_latest
;
482 if ( isset( $row->page_content_model
) ) {
483 $this->mContentModel
= strval( $row->page_content_model
);
485 $this->mContentModel
= false; # initialized lazily in getContentModel()
487 if ( isset( $row->page_lang
) ) {
488 $this->mDbPageLanguage
= (string)$row->page_lang
;
490 if ( isset( $row->page_restrictions
) ) {
491 $this->mOldRestrictions
= $row->page_restrictions
;
493 } else { // page not found
494 $this->mArticleID
= 0;
496 $this->mRedirect
= false;
497 $this->mLatestID
= 0;
498 $this->mContentModel
= false; # initialized lazily in getContentModel()
503 * Create a new Title from a namespace index and a DB key.
504 * It's assumed that $ns and $title are *valid*, for instance when
505 * they came directly from the database or a special page name.
506 * For convenience, spaces are converted to underscores so that
507 * eg user_text fields can be used directly.
509 * @param int $ns The namespace of the article
510 * @param string $title The unprefixed database key form
511 * @param string $fragment The link fragment (after the "#")
512 * @param string $interwiki The interwiki prefix
513 * @return Title The new object
515 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
517 $t->mInterwiki
= $interwiki;
518 $t->mFragment
= $fragment;
519 $t->mNamespace
= $ns = intval( $ns );
520 $t->mDbkeyform
= strtr( $title, ' ', '_' );
521 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
522 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
523 $t->mTextform
= strtr( $title, '_', ' ' );
524 $t->mContentModel
= false; # initialized lazily in getContentModel()
529 * Create a new Title from a namespace index and a DB key.
530 * The parameters will be checked for validity, which is a bit slower
531 * than makeTitle() but safer for user-provided data.
533 * @param int $ns The namespace of the article
534 * @param string $title Database key form
535 * @param string $fragment The link fragment (after the "#")
536 * @param string $interwiki Interwiki prefix
537 * @return Title|null The new object, or null on an error
539 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
540 if ( !MWNamespace
::exists( $ns ) ) {
545 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
548 $t->secureAndSplit();
550 } catch ( MalformedTitleException
$ex ) {
556 * Create a new Title for the Main Page
558 * @return Title The new object
560 public static function newMainPage() {
561 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
562 // Don't give fatal errors if the message is broken
564 $title = Title
::newFromText( 'Main Page' );
570 * Extract a redirect destination from a string and return the
571 * Title, or null if the text doesn't contain a valid redirect
572 * This will only return the very next target, useful for
573 * the redirect table and other checks that don't need full recursion
575 * @param string $text Text with possible redirect
576 * @return Title The corresponding Title
577 * @deprecated since 1.21, use Content::getRedirectTarget instead.
579 public static function newFromRedirect( $text ) {
580 ContentHandler
::deprecated( __METHOD__
, '1.21' );
582 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
583 return $content->getRedirectTarget();
587 * Extract a redirect destination from a string and return the
588 * Title, or null if the text doesn't contain a valid redirect
589 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
590 * in order to provide (hopefully) the Title of the final destination instead of another redirect
592 * @param string $text Text with possible redirect
594 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
596 public static function newFromRedirectRecurse( $text ) {
597 ContentHandler
::deprecated( __METHOD__
, '1.21' );
599 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
600 return $content->getUltimateRedirectTarget();
604 * Extract a redirect destination from a string and return an
605 * array of Titles, or null if the text doesn't contain a valid redirect
606 * The last element in the array is the final destination after all redirects
607 * have been resolved (up to $wgMaxRedirects times)
609 * @param string $text Text with possible redirect
610 * @return Title[] Array of Titles, with the destination last
611 * @deprecated since 1.21, use Content::getRedirectChain instead.
613 public static function newFromRedirectArray( $text ) {
614 ContentHandler
::deprecated( __METHOD__
, '1.21' );
616 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
617 return $content->getRedirectChain();
621 * Get the prefixed DB key associated with an ID
623 * @param int $id The page_id of the article
624 * @return Title|null An object representing the article, or null if no such article was found
626 public static function nameOf( $id ) {
627 $dbr = wfGetDB( DB_SLAVE
);
629 $s = $dbr->selectRow(
631 array( 'page_namespace', 'page_title' ),
632 array( 'page_id' => $id ),
635 if ( $s === false ) {
639 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
644 * Get a regex character class describing the legal characters in a link
646 * @return string The list of characters, not delimited
648 public static function legalChars() {
649 global $wgLegalTitleChars;
650 return $wgLegalTitleChars;
654 * Returns a simple regex that will match on characters and sequences invalid in titles.
655 * Note that this doesn't pick up many things that could be wrong with titles, but that
656 * replacing this regex with something valid will make many titles valid.
658 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
660 * @return string Regex string
662 static function getTitleInvalidRegex() {
663 wfDeprecated( __METHOD__
, '1.25' );
664 return MediaWikiTitleCodec
::getTitleInvalidRegex();
668 * Utility method for converting a character sequence from bytes to Unicode.
670 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
671 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
673 * @param string $byteClass
676 public static function convertByteClassToUnicodeClass( $byteClass ) {
677 $length = strlen( $byteClass );
679 $x0 = $x1 = $x2 = '';
681 $d0 = $d1 = $d2 = '';
682 // Decoded integer codepoints
683 $ord0 = $ord1 = $ord2 = 0;
685 $r0 = $r1 = $r2 = '';
689 $allowUnicode = false;
690 for ( $pos = 0; $pos < $length; $pos++
) {
691 // Shift the queues down
700 // Load the current input token and decoded values
701 $inChar = $byteClass[$pos];
702 if ( $inChar == '\\' ) {
703 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
704 $x0 = $inChar . $m[0];
705 $d0 = chr( hexdec( $m[1] ) );
706 $pos +
= strlen( $m[0] );
707 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
708 $x0 = $inChar . $m[0];
709 $d0 = chr( octdec( $m[0] ) );
710 $pos +
= strlen( $m[0] );
711 } elseif ( $pos +
1 >= $length ) {
714 $d0 = $byteClass[$pos +
1];
722 // Load the current re-encoded value
723 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
724 $r0 = sprintf( '\x%02x', $ord0 );
725 } elseif ( $ord0 >= 0x80 ) {
726 // Allow unicode if a single high-bit character appears
727 $r0 = sprintf( '\x%02x', $ord0 );
728 $allowUnicode = true;
729 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
735 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
737 if ( $ord2 > $ord0 ) {
739 } elseif ( $ord0 >= 0x80 ) {
741 $allowUnicode = true;
742 if ( $ord2 < 0x80 ) {
743 // Keep the non-unicode section of the range
750 // Reset state to the initial value
751 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
752 } elseif ( $ord2 < 0x80 ) {
757 if ( $ord1 < 0x80 ) {
760 if ( $ord0 < 0x80 ) {
763 if ( $allowUnicode ) {
764 $out .= '\u0080-\uFFFF';
770 * Make a prefixed DB key from a DB key and a namespace index
772 * @param int $ns Numerical representation of the namespace
773 * @param string $title The DB key form the title
774 * @param string $fragment The link fragment (after the "#")
775 * @param string $interwiki The interwiki prefix
776 * @param bool $canonicalNamespace If true, use the canonical name for
777 * $ns instead of the localized version.
778 * @return string The prefixed form of the title
780 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
781 $canonicalNamespace = false
785 if ( $canonicalNamespace ) {
786 $namespace = MWNamespace
::getCanonicalName( $ns );
788 $namespace = $wgContLang->getNsText( $ns );
790 $name = $namespace == '' ?
$title : "$namespace:$title";
791 if ( strval( $interwiki ) != '' ) {
792 $name = "$interwiki:$name";
794 if ( strval( $fragment ) != '' ) {
795 $name .= '#' . $fragment;
801 * Escape a text fragment, say from a link, for a URL
803 * @param string $fragment Containing a URL or link fragment (after the "#")
804 * @return string Escaped string
806 static function escapeFragmentForURL( $fragment ) {
807 # Note that we don't urlencode the fragment. urlencoded Unicode
808 # fragments appear not to work in IE (at least up to 7) or in at least
809 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
810 # to care if they aren't encoded.
811 return Sanitizer
::escapeId( $fragment, 'noninitial' );
815 * Callback for usort() to do title sorts by (namespace, title)
820 * @return int Result of string comparison, or namespace comparison
822 public static function compare( $a, $b ) {
823 if ( $a->getNamespace() == $b->getNamespace() ) {
824 return strcmp( $a->getText(), $b->getText() );
826 return $a->getNamespace() - $b->getNamespace();
831 * Determine whether the object refers to a page within
832 * this project (either this wiki or a wiki with a local
833 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
835 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
837 public function isLocal() {
838 if ( $this->isExternal() ) {
839 $iw = Interwiki
::fetch( $this->mInterwiki
);
841 return $iw->isLocal();
848 * Is this Title interwiki?
852 public function isExternal() {
853 return $this->mInterwiki
!== '';
857 * Get the interwiki prefix
859 * Use Title::isExternal to check if a interwiki is set
861 * @return string Interwiki prefix
863 public function getInterwiki() {
864 return $this->mInterwiki
;
868 * Was this a local interwiki link?
872 public function wasLocalInterwiki() {
873 return $this->mLocalInterwiki
;
877 * Determine whether the object refers to a page within
878 * this project and is transcludable.
880 * @return bool True if this is transcludable
882 public function isTrans() {
883 if ( !$this->isExternal() ) {
887 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
891 * Returns the DB name of the distant wiki which owns the object.
893 * @return string The DB name
895 public function getTransWikiID() {
896 if ( !$this->isExternal() ) {
900 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
904 * Get a TitleValue object representing this Title.
906 * @note Not all valid Titles have a corresponding valid TitleValue
907 * (e.g. TitleValues cannot represent page-local links that have a
908 * fragment but no title text).
910 * @return TitleValue|null
912 public function getTitleValue() {
913 if ( $this->mTitleValue
=== null ) {
915 $this->mTitleValue
= new TitleValue(
916 $this->getNamespace(),
918 $this->getFragment() );
919 } catch ( InvalidArgumentException
$ex ) {
920 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
921 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
925 return $this->mTitleValue
;
929 * Get the text form (spaces not underscores) of the main part
931 * @return string Main part of the title
933 public function getText() {
934 return $this->mTextform
;
938 * Get the URL-encoded form of the main part
940 * @return string Main part of the title, URL-encoded
942 public function getPartialURL() {
943 return $this->mUrlform
;
947 * Get the main part with underscores
949 * @return string Main part of the title, with underscores
951 public function getDBkey() {
952 return $this->mDbkeyform
;
956 * Get the DB key with the initial letter case as specified by the user
958 * @return string DB key
960 function getUserCaseDBKey() {
961 if ( !is_null( $this->mUserCaseDBKey
) ) {
962 return $this->mUserCaseDBKey
;
964 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
965 return $this->mDbkeyform
;
970 * Get the namespace index, i.e. one of the NS_xxxx constants.
972 * @return int Namespace index
974 public function getNamespace() {
975 return $this->mNamespace
;
979 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
981 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
982 * @return string Content model id
984 public function getContentModel( $flags = 0 ) {
985 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
986 $linkCache = LinkCache
::singleton();
987 $linkCache->addLinkObj( $this ); # in case we already had an article ID
988 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
991 if ( !$this->mContentModel
) {
992 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
995 return $this->mContentModel
;
999 * Convenience method for checking a title's content model name
1001 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1002 * @return bool True if $this->getContentModel() == $id
1004 public function hasContentModel( $id ) {
1005 return $this->getContentModel() == $id;
1009 * Get the namespace text
1011 * @return string Namespace text
1013 public function getNsText() {
1014 if ( $this->isExternal() ) {
1015 // This probably shouldn't even happen,
1016 // but for interwiki transclusion it sometimes does.
1017 // Use the canonical namespaces if possible to try to
1018 // resolve a foreign namespace.
1019 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1020 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1025 $formatter = self
::getTitleFormatter();
1026 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1027 } catch ( InvalidArgumentException
$ex ) {
1028 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1034 * Get the namespace text of the subject (rather than talk) page
1036 * @return string Namespace text
1038 public function getSubjectNsText() {
1040 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1044 * Get the namespace text of the talk page
1046 * @return string Namespace text
1048 public function getTalkNsText() {
1050 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1054 * Could this title have a corresponding talk page?
1058 public function canTalk() {
1059 return MWNamespace
::canTalk( $this->mNamespace
);
1063 * Is this in a namespace that allows actual pages?
1067 public function canExist() {
1068 return $this->mNamespace
>= NS_MAIN
;
1072 * Can this title be added to a user's watchlist?
1076 public function isWatchable() {
1077 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1081 * Returns true if this is a special page.
1085 public function isSpecialPage() {
1086 return $this->getNamespace() == NS_SPECIAL
;
1090 * Returns true if this title resolves to the named special page
1092 * @param string $name The special page name
1095 public function isSpecial( $name ) {
1096 if ( $this->isSpecialPage() ) {
1097 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1098 if ( $name == $thisName ) {
1106 * If the Title refers to a special page alias which is not the local default, resolve
1107 * the alias, and localise the name as necessary. Otherwise, return $this
1111 public function fixSpecialName() {
1112 if ( $this->isSpecialPage() ) {
1113 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1114 if ( $canonicalName ) {
1115 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1116 if ( $localName != $this->mDbkeyform
) {
1117 return Title
::makeTitle( NS_SPECIAL
, $localName );
1125 * Returns true if the title is inside the specified namespace.
1127 * Please make use of this instead of comparing to getNamespace()
1128 * This function is much more resistant to changes we may make
1129 * to namespaces than code that makes direct comparisons.
1130 * @param int $ns The namespace
1134 public function inNamespace( $ns ) {
1135 return MWNamespace
::equals( $this->getNamespace(), $ns );
1139 * Returns true if the title is inside one of the specified namespaces.
1141 * @param int $namespaces,... The namespaces to check for
1145 public function inNamespaces( /* ... */ ) {
1146 $namespaces = func_get_args();
1147 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1148 $namespaces = $namespaces[0];
1151 foreach ( $namespaces as $ns ) {
1152 if ( $this->inNamespace( $ns ) ) {
1161 * Returns true if the title has the same subject namespace as the
1162 * namespace specified.
1163 * For example this method will take NS_USER and return true if namespace
1164 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1165 * as their subject namespace.
1167 * This is MUCH simpler than individually testing for equivalence
1168 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1173 public function hasSubjectNamespace( $ns ) {
1174 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1178 * Is this Title in a namespace which contains content?
1179 * In other words, is this a content page, for the purposes of calculating
1184 public function isContentPage() {
1185 return MWNamespace
::isContent( $this->getNamespace() );
1189 * Would anybody with sufficient privileges be able to move this page?
1190 * Some pages just aren't movable.
1194 public function isMovable() {
1195 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1196 // Interwiki title or immovable namespace. Hooks don't get to override here
1201 Hooks
::run( 'TitleIsMovable', array( $this, &$result ) );
1206 * Is this the mainpage?
1207 * @note Title::newFromText seems to be sufficiently optimized by the title
1208 * cache that we don't need to over-optimize by doing direct comparisons and
1209 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1210 * ends up reporting something differently than $title->isMainPage();
1215 public function isMainPage() {
1216 return $this->equals( Title
::newMainPage() );
1220 * Is this a subpage?
1224 public function isSubpage() {
1225 return MWNamespace
::hasSubpages( $this->mNamespace
)
1226 ?
strpos( $this->getText(), '/' ) !== false
1231 * Is this a conversion table for the LanguageConverter?
1235 public function isConversionTable() {
1236 // @todo ConversionTable should become a separate content model.
1238 return $this->getNamespace() == NS_MEDIAWIKI
&&
1239 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1243 * Does that page contain wikitext, or it is JS, CSS or whatever?
1247 public function isWikitextPage() {
1248 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1252 * Could this page contain custom CSS or JavaScript for the global UI.
1253 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1254 * or CONTENT_MODEL_JAVASCRIPT.
1256 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1259 * Note that this method should not return true for pages that contain and
1260 * show "inactive" CSS or JS.
1264 public function isCssOrJsPage() {
1265 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1266 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1267 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1269 # @note This hook is also called in ContentHandler::getDefaultModel.
1270 # It's called here again to make sure hook functions can force this
1271 # method to return true even outside the MediaWiki namespace.
1273 Hooks
::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1275 return $isCssOrJsPage;
1279 * Is this a .css or .js subpage of a user page?
1282 public function isCssJsSubpage() {
1283 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1284 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1285 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1289 * Trim down a .css or .js subpage title to get the corresponding skin name
1291 * @return string Containing skin name from .css or .js subpage title
1293 public function getSkinFromCssJsSubpage() {
1294 $subpage = explode( '/', $this->mTextform
);
1295 $subpage = $subpage[count( $subpage ) - 1];
1296 $lastdot = strrpos( $subpage, '.' );
1297 if ( $lastdot === false ) {
1298 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1300 return substr( $subpage, 0, $lastdot );
1304 * Is this a .css subpage of a user page?
1308 public function isCssSubpage() {
1309 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1310 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1314 * Is this a .js subpage of a user page?
1318 public function isJsSubpage() {
1319 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1320 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1324 * Is this a talk page of some sort?
1328 public function isTalkPage() {
1329 return MWNamespace
::isTalk( $this->getNamespace() );
1333 * Get a Title object associated with the talk page of this article
1335 * @return Title The object for the talk page
1337 public function getTalkPage() {
1338 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1342 * Get a title object associated with the subject page of this
1345 * @return Title The object for the subject page
1347 public function getSubjectPage() {
1348 // Is this the same title?
1349 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1350 if ( $this->getNamespace() == $subjectNS ) {
1353 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1357 * Get the other title for this page, if this is a subject page
1358 * get the talk page, if it is a subject page get the talk page
1361 * @throws MWException
1364 public function getOtherPage() {
1365 if ( $this->isSpecialPage() ) {
1366 throw new MWException( 'Special pages cannot have other pages' );
1368 if ( $this->isTalkPage() ) {
1369 return $this->getSubjectPage();
1371 return $this->getTalkPage();
1376 * Get the default namespace index, for when there is no namespace
1378 * @return int Default namespace index
1380 public function getDefaultNamespace() {
1381 return $this->mDefaultNamespace
;
1385 * Get the Title fragment (i.e.\ the bit after the #) in text form
1387 * Use Title::hasFragment to check for a fragment
1389 * @return string Title fragment
1391 public function getFragment() {
1392 return $this->mFragment
;
1396 * Check if a Title fragment is set
1401 public function hasFragment() {
1402 return $this->mFragment
!== '';
1406 * Get the fragment in URL form, including the "#" character if there is one
1407 * @return string Fragment in URL form
1409 public function getFragmentForURL() {
1410 if ( !$this->hasFragment() ) {
1413 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1418 * Set the fragment for this title. Removes the first character from the
1419 * specified fragment before setting, so it assumes you're passing it with
1422 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1423 * Still in active use privately.
1426 * @param string $fragment Text
1428 public function setFragment( $fragment ) {
1429 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1433 * Prefix some arbitrary text with the namespace or interwiki prefix
1436 * @param string $name The text
1437 * @return string The prefixed text
1439 private function prefix( $name ) {
1441 if ( $this->isExternal() ) {
1442 $p = $this->mInterwiki
. ':';
1445 if ( 0 != $this->mNamespace
) {
1446 $p .= $this->getNsText() . ':';
1452 * Get the prefixed database key form
1454 * @return string The prefixed title, with underscores and
1455 * any interwiki and namespace prefixes
1457 public function getPrefixedDBkey() {
1458 $s = $this->prefix( $this->mDbkeyform
);
1459 $s = strtr( $s, ' ', '_' );
1464 * Get the prefixed title with spaces.
1465 * This is the form usually used for display
1467 * @return string The prefixed title, with spaces
1469 public function getPrefixedText() {
1470 if ( $this->mPrefixedText
=== null ) {
1471 $s = $this->prefix( $this->mTextform
);
1472 $s = strtr( $s, '_', ' ' );
1473 $this->mPrefixedText
= $s;
1475 return $this->mPrefixedText
;
1479 * Return a string representation of this title
1481 * @return string Representation of this title
1483 public function __toString() {
1484 return $this->getPrefixedText();
1488 * Get the prefixed title with spaces, plus any fragment
1489 * (part beginning with '#')
1491 * @return string The prefixed title, with spaces and the fragment, including '#'
1493 public function getFullText() {
1494 $text = $this->getPrefixedText();
1495 if ( $this->hasFragment() ) {
1496 $text .= '#' . $this->getFragment();
1502 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1506 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1510 * @return string Root name
1513 public function getRootText() {
1514 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1515 return $this->getText();
1518 return strtok( $this->getText(), '/' );
1522 * Get the root page name title, i.e. the leftmost part before any slashes
1526 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1527 * # returns: Title{User:Foo}
1530 * @return Title Root title
1533 public function getRootTitle() {
1534 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1538 * Get the base page name without a namespace, i.e. the part before the subpage name
1542 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1543 * # returns: 'Foo/Bar'
1546 * @return string Base name
1548 public function getBaseText() {
1549 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1550 return $this->getText();
1553 $parts = explode( '/', $this->getText() );
1554 # Don't discard the real title if there's no subpage involved
1555 if ( count( $parts ) > 1 ) {
1556 unset( $parts[count( $parts ) - 1] );
1558 return implode( '/', $parts );
1562 * Get the base page name title, i.e. the part before the subpage name
1566 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1567 * # returns: Title{User:Foo/Bar}
1570 * @return Title Base title
1573 public function getBaseTitle() {
1574 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1578 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1582 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1586 * @return string Subpage name
1588 public function getSubpageText() {
1589 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1590 return $this->mTextform
;
1592 $parts = explode( '/', $this->mTextform
);
1593 return $parts[count( $parts ) - 1];
1597 * Get the title for a subpage of the current page
1601 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1602 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1605 * @param string $text The subpage name to add to the title
1606 * @return Title Subpage title
1609 public function getSubpage( $text ) {
1610 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1614 * Get a URL-encoded form of the subpage text
1616 * @return string URL-encoded subpage name
1618 public function getSubpageUrlForm() {
1619 $text = $this->getSubpageText();
1620 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1625 * Get a URL-encoded title (not an actual URL) including interwiki
1627 * @return string The URL-encoded form
1629 public function getPrefixedURL() {
1630 $s = $this->prefix( $this->mDbkeyform
);
1631 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1636 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1637 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1638 * second argument named variant. This was deprecated in favor
1639 * of passing an array of option with a "variant" key
1640 * Once $query2 is removed for good, this helper can be dropped
1641 * and the wfArrayToCgi moved to getLocalURL();
1643 * @since 1.19 (r105919)
1644 * @param array|string $query
1645 * @param bool $query2
1648 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1649 if ( $query2 !== false ) {
1650 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1651 "method called with a second parameter is deprecated. Add your " .
1652 "parameter to an array passed as the first parameter.", "1.19" );
1654 if ( is_array( $query ) ) {
1655 $query = wfArrayToCgi( $query );
1658 if ( is_string( $query2 ) ) {
1659 // $query2 is a string, we will consider this to be
1660 // a deprecated $variant argument and add it to the query
1661 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1663 $query2 = wfArrayToCgi( $query2 );
1665 // If we have $query content add a & to it first
1669 // Now append the queries together
1676 * Get a real URL referring to this title, with interwiki link and
1679 * @see self::getLocalURL for the arguments.
1681 * @param array|string $query
1682 * @param bool $query2
1683 * @param string $proto Protocol type to use in URL
1684 * @return string The URL
1686 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1687 $query = self
::fixUrlQueryArgs( $query, $query2 );
1689 # Hand off all the decisions on urls to getLocalURL
1690 $url = $this->getLocalURL( $query );
1692 # Expand the url to make it a full url. Note that getLocalURL has the
1693 # potential to output full urls for a variety of reasons, so we use
1694 # wfExpandUrl instead of simply prepending $wgServer
1695 $url = wfExpandUrl( $url, $proto );
1697 # Finally, add the fragment.
1698 $url .= $this->getFragmentForURL();
1700 Hooks
::run( 'GetFullURL', array( &$this, &$url, $query ) );
1705 * Get a URL with no fragment or server name (relative URL) from a Title object.
1706 * If this page is generated with action=render, however,
1707 * $wgServer is prepended to make an absolute URL.
1709 * @see self::getFullURL to always get an absolute URL.
1710 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1711 * valid to link, locally, to the current Title.
1712 * @see self::newFromText to produce a Title object.
1714 * @param string|array $query An optional query string,
1715 * not used for interwiki links. Can be specified as an associative array as well,
1716 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1717 * Some query patterns will trigger various shorturl path replacements.
1718 * @param array $query2 An optional secondary query array. This one MUST
1719 * be an array. If a string is passed it will be interpreted as a deprecated
1720 * variant argument and urlencoded into a variant= argument.
1721 * This second query argument will be added to the $query
1722 * The second parameter is deprecated since 1.19. Pass it as a key,value
1723 * pair in the first parameter array instead.
1725 * @return string String of the URL.
1727 public function getLocalURL( $query = '', $query2 = false ) {
1728 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1730 $query = self
::fixUrlQueryArgs( $query, $query2 );
1732 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1734 $namespace = $this->getNsText();
1735 if ( $namespace != '' ) {
1736 # Can this actually happen? Interwikis shouldn't be parsed.
1737 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1740 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1741 $url = wfAppendQuery( $url, $query );
1743 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1744 if ( $query == '' ) {
1745 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1746 Hooks
::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1748 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1752 if ( !empty( $wgActionPaths )
1753 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1755 $action = urldecode( $matches[2] );
1756 if ( isset( $wgActionPaths[$action] ) ) {
1757 $query = $matches[1];
1758 if ( isset( $matches[4] ) ) {
1759 $query .= $matches[4];
1761 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1762 if ( $query != '' ) {
1763 $url = wfAppendQuery( $url, $query );
1769 && $wgVariantArticlePath
1770 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1771 && $this->getPageLanguage()->hasVariants()
1772 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1774 $variant = urldecode( $matches[1] );
1775 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1776 // Only do the variant replacement if the given variant is a valid
1777 // variant for the page's language.
1778 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1779 $url = str_replace( '$1', $dbkey, $url );
1783 if ( $url === false ) {
1784 if ( $query == '-' ) {
1787 $url = "{$wgScript}?title={$dbkey}&{$query}";
1791 Hooks
::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1793 // @todo FIXME: This causes breakage in various places when we
1794 // actually expected a local URL and end up with dupe prefixes.
1795 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1796 $url = $wgServer . $url;
1799 Hooks
::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1804 * Get a URL that's the simplest URL that will be valid to link, locally,
1805 * to the current Title. It includes the fragment, but does not include
1806 * the server unless action=render is used (or the link is external). If
1807 * there's a fragment but the prefixed text is empty, we just return a link
1810 * The result obviously should not be URL-escaped, but does need to be
1811 * HTML-escaped if it's being output in HTML.
1813 * @param array $query
1814 * @param bool $query2
1815 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1816 * @see self::getLocalURL for the arguments.
1817 * @return string The URL
1819 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1820 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1821 $ret = $this->getFullURL( $query, $query2, $proto );
1822 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1823 $ret = $this->getFragmentForURL();
1825 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1831 * Get the URL form for an internal link.
1832 * - Used in various CDN-related code, in case we have a different
1833 * internal hostname for the server from the exposed one.
1835 * This uses $wgInternalServer to qualify the path, or $wgServer
1836 * if $wgInternalServer is not set. If the server variable used is
1837 * protocol-relative, the URL will be expanded to http://
1839 * @see self::getLocalURL for the arguments.
1840 * @return string The URL
1842 public function getInternalURL( $query = '', $query2 = false ) {
1843 global $wgInternalServer, $wgServer;
1844 $query = self
::fixUrlQueryArgs( $query, $query2 );
1845 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1846 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1847 Hooks
::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1852 * Get the URL for a canonical link, for use in things like IRC and
1853 * e-mail notifications. Uses $wgCanonicalServer and the
1854 * GetCanonicalURL hook.
1856 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1858 * @see self::getLocalURL for the arguments.
1859 * @return string The URL
1862 public function getCanonicalURL( $query = '', $query2 = false ) {
1863 $query = self
::fixUrlQueryArgs( $query, $query2 );
1864 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1865 Hooks
::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1870 * Get the edit URL for this Title
1872 * @return string The URL, or a null string if this is an interwiki link
1874 public function getEditURL() {
1875 if ( $this->isExternal() ) {
1878 $s = $this->getLocalURL( 'action=edit' );
1884 * Can $user perform $action on this page?
1885 * This skips potentially expensive cascading permission checks
1886 * as well as avoids expensive error formatting
1888 * Suitable for use for nonessential UI controls in common cases, but
1889 * _not_ for functional access control.
1891 * May provide false positives, but should never provide a false negative.
1893 * @param string $action Action that permission needs to be checked for
1894 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1897 public function quickUserCan( $action, $user = null ) {
1898 return $this->userCan( $action, $user, false );
1902 * Can $user perform $action on this page?
1904 * @param string $action Action that permission needs to be checked for
1905 * @param User $user User to check (since 1.19); $wgUser will be used if not
1907 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1910 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1911 if ( !$user instanceof User
) {
1916 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1920 * Can $user perform $action on this page?
1922 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1924 * @param string $action Action that permission needs to be checked for
1925 * @param User $user User to check
1926 * @param string $rigor One of (quick,full,secure)
1927 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1928 * - full : does cheap and expensive checks possibly from a slave
1929 * - secure : does cheap and expensive checks, using the master as needed
1930 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1931 * whose corresponding errors may be ignored.
1932 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1934 public function getUserPermissionsErrors(
1935 $action, $user, $rigor = 'secure', $ignoreErrors = array()
1937 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1939 // Remove the errors being ignored.
1940 foreach ( $errors as $index => $error ) {
1941 $errKey = is_array( $error ) ?
$error[0] : $error;
1943 if ( in_array( $errKey, $ignoreErrors ) ) {
1944 unset( $errors[$index] );
1946 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1947 unset( $errors[$index] );
1955 * Permissions checks that fail most often, and which are easiest to test.
1957 * @param string $action The action to check
1958 * @param User $user User to check
1959 * @param array $errors List of current errors
1960 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1961 * @param bool $short Short circuit on first error
1963 * @return array List of errors
1965 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1966 if ( !Hooks
::run( 'TitleQuickPermissions',
1967 array( $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ) )
1972 if ( $action == 'create' ) {
1974 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1975 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1977 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1979 } elseif ( $action == 'move' ) {
1980 if ( !$user->isAllowed( 'move-rootuserpages' )
1981 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1982 // Show user page-specific message only if the user can move other pages
1983 $errors[] = array( 'cant-move-user-page' );
1986 // Check if user is allowed to move files if it's a file
1987 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1988 $errors[] = array( 'movenotallowedfile' );
1991 // Check if user is allowed to move category pages if it's a category page
1992 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1993 $errors[] = array( 'cant-move-category-page' );
1996 if ( !$user->isAllowed( 'move' ) ) {
1997 // User can't move anything
1998 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1999 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2000 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2001 // custom message if logged-in users without any special rights can move
2002 $errors[] = array( 'movenologintext' );
2004 $errors[] = array( 'movenotallowed' );
2007 } elseif ( $action == 'move-target' ) {
2008 if ( !$user->isAllowed( 'move' ) ) {
2009 // User can't move anything
2010 $errors[] = array( 'movenotallowed' );
2011 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2012 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2013 // Show user page-specific message only if the user can move other pages
2014 $errors[] = array( 'cant-move-to-user-page' );
2015 } elseif ( !$user->isAllowed( 'move-categorypages' )
2016 && $this->mNamespace
== NS_CATEGORY
) {
2017 // Show category page-specific message only if the user can move other pages
2018 $errors[] = array( 'cant-move-to-category-page' );
2020 } elseif ( !$user->isAllowed( $action ) ) {
2021 $errors[] = $this->missingPermissionError( $action, $short );
2028 * Add the resulting error code to the errors array
2030 * @param array $errors List of current errors
2031 * @param array $result Result of errors
2033 * @return array List of errors
2035 private function resultToError( $errors, $result ) {
2036 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2037 // A single array representing an error
2038 $errors[] = $result;
2039 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2040 // A nested array representing multiple errors
2041 $errors = array_merge( $errors, $result );
2042 } elseif ( $result !== '' && is_string( $result ) ) {
2043 // A string representing a message-id
2044 $errors[] = array( $result );
2045 } elseif ( $result instanceof MessageSpecifier
) {
2046 // A message specifier representing an error
2047 $errors[] = array( $result );
2048 } elseif ( $result === false ) {
2049 // a generic "We don't want them to do that"
2050 $errors[] = array( 'badaccess-group0' );
2056 * Check various permission hooks
2058 * @param string $action The action to check
2059 * @param User $user User to check
2060 * @param array $errors List of current errors
2061 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2062 * @param bool $short Short circuit on first error
2064 * @return array List of errors
2066 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2067 // Use getUserPermissionsErrors instead
2069 if ( !Hooks
::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2070 return $result ?
array() : array( array( 'badaccess-group0' ) );
2072 // Check getUserPermissionsErrors hook
2073 if ( !Hooks
::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2074 $errors = $this->resultToError( $errors, $result );
2076 // Check getUserPermissionsErrorsExpensive hook
2079 && !( $short && count( $errors ) > 0 )
2080 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2082 $errors = $this->resultToError( $errors, $result );
2089 * Check permissions on special pages & namespaces
2091 * @param string $action The action to check
2092 * @param User $user User to check
2093 * @param array $errors List of current errors
2094 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2095 * @param bool $short Short circuit on first error
2097 * @return array List of errors
2099 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2100 # Only 'createaccount' can be performed on special pages,
2101 # which don't actually exist in the DB.
2102 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2103 $errors[] = array( 'ns-specialprotected' );
2106 # Check $wgNamespaceProtection for restricted namespaces
2107 if ( $this->isNamespaceProtected( $user ) ) {
2108 $ns = $this->mNamespace
== NS_MAIN ?
2109 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2110 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2111 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2118 * Check CSS/JS sub-page permissions
2120 * @param string $action The action to check
2121 * @param User $user User to check
2122 * @param array $errors List of current errors
2123 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2124 * @param bool $short Short circuit on first error
2126 * @return array List of errors
2128 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2129 # Protect css/js subpages of user pages
2130 # XXX: this might be better using restrictions
2131 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2132 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2133 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2134 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2135 $errors[] = array( 'mycustomcssprotected', $action );
2136 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2137 $errors[] = array( 'mycustomjsprotected', $action );
2140 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2141 $errors[] = array( 'customcssprotected', $action );
2142 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2143 $errors[] = array( 'customjsprotected', $action );
2152 * Check against page_restrictions table requirements on this
2153 * page. The user must possess all required rights for this
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2160 * @param bool $short Short circuit on first error
2162 * @return array List of errors
2164 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2165 foreach ( $this->getRestrictions( $action ) as $right ) {
2166 // Backwards compatibility, rewrite sysop -> editprotected
2167 if ( $right == 'sysop' ) {
2168 $right = 'editprotected';
2170 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2171 if ( $right == 'autoconfirmed' ) {
2172 $right = 'editsemiprotected';
2174 if ( $right == '' ) {
2177 if ( !$user->isAllowed( $right ) ) {
2178 $errors[] = array( 'protectedpagetext', $right, $action );
2179 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2180 $errors[] = array( 'protectedpagetext', 'protect', $action );
2188 * Check restrictions on cascading pages.
2190 * @param string $action The action to check
2191 * @param User $user User to check
2192 * @param array $errors List of current errors
2193 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2194 * @param bool $short Short circuit on first error
2196 * @return array List of errors
2198 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2199 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2200 # We /could/ use the protection level on the source page, but it's
2201 # fairly ugly as we have to establish a precedence hierarchy for pages
2202 # included by multiple cascade-protected pages. So just restrict
2203 # it to people with 'protect' permission, as they could remove the
2204 # protection anyway.
2205 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2206 # Cascading protection depends on more than this page...
2207 # Several cascading protected pages may include this page...
2208 # Check each cascading level
2209 # This is only for protection restrictions, not for all actions
2210 if ( isset( $restrictions[$action] ) ) {
2211 foreach ( $restrictions[$action] as $right ) {
2212 // Backwards compatibility, rewrite sysop -> editprotected
2213 if ( $right == 'sysop' ) {
2214 $right = 'editprotected';
2216 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2217 if ( $right == 'autoconfirmed' ) {
2218 $right = 'editsemiprotected';
2220 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2222 foreach ( $cascadingSources as $page ) {
2223 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2225 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2235 * Check action permissions not already checked in checkQuickPermissions
2237 * @param string $action The action to check
2238 * @param User $user User to check
2239 * @param array $errors List of current errors
2240 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2241 * @param bool $short Short circuit on first error
2243 * @return array List of errors
2245 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2246 global $wgDeleteRevisionsLimit, $wgLang;
2248 if ( $action == 'protect' ) {
2249 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2250 // If they can't edit, they shouldn't protect.
2251 $errors[] = array( 'protect-cantedit' );
2253 } elseif ( $action == 'create' ) {
2254 $title_protection = $this->getTitleProtection();
2255 if ( $title_protection ) {
2256 if ( $title_protection['permission'] == ''
2257 ||
!$user->isAllowed( $title_protection['permission'] )
2261 User
::whoIs( $title_protection['user'] ),
2262 $title_protection['reason']
2266 } elseif ( $action == 'move' ) {
2267 // Check for immobile pages
2268 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2269 // Specific message for this case
2270 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2271 } elseif ( !$this->isMovable() ) {
2272 // Less specific message for rarer cases
2273 $errors[] = array( 'immobile-source-page' );
2275 } elseif ( $action == 'move-target' ) {
2276 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2277 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2278 } elseif ( !$this->isMovable() ) {
2279 $errors[] = array( 'immobile-target-page' );
2281 } elseif ( $action == 'delete' ) {
2282 $tempErrors = $this->checkPageRestrictions( 'edit', $user, array(), $rigor, true );
2283 if ( !$tempErrors ) {
2284 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2285 $user, $tempErrors, $rigor, true );
2287 if ( $tempErrors ) {
2288 // If protection keeps them from editing, they shouldn't be able to delete.
2289 $errors[] = array( 'deleteprotected' );
2291 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2292 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2294 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2301 * Check that the user isn't blocked from editing.
2303 * @param string $action The action to check
2304 * @param User $user User to check
2305 * @param array $errors List of current errors
2306 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2307 * @param bool $short Short circuit on first error
2309 * @return array List of errors
2311 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2312 // Account creation blocks handled at userlogin.
2313 // Unblocking handled in SpecialUnblock
2314 if ( $rigor === 'quick' ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2318 global $wgEmailConfirmToEdit;
2320 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2321 $errors[] = array( 'confirmedittext' );
2324 $useSlave = ( $rigor !== 'secure' );
2325 if ( ( $action == 'edit' ||
$action == 'create' )
2326 && !$user->isBlockedFrom( $this, $useSlave )
2328 // Don't block the user from editing their own talk page unless they've been
2329 // explicitly blocked from that too.
2330 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2331 // @todo FIXME: Pass the relevant context into this function.
2332 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2339 * Check that the user is allowed to read this page.
2341 * @param string $action The action to check
2342 * @param User $user User to check
2343 * @param array $errors List of current errors
2344 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2345 * @param bool $short Short circuit on first error
2347 * @return array List of errors
2349 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2350 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2352 $whitelisted = false;
2353 if ( User
::isEveryoneAllowed( 'read' ) ) {
2354 # Shortcut for public wikis, allows skipping quite a bit of code
2355 $whitelisted = true;
2356 } elseif ( $user->isAllowed( 'read' ) ) {
2357 # If the user is allowed to read pages, he is allowed to read all pages
2358 $whitelisted = true;
2359 } elseif ( $this->isSpecial( 'Userlogin' )
2360 ||
$this->isSpecial( 'ChangePassword' )
2361 ||
$this->isSpecial( 'PasswordReset' )
2363 # Always grant access to the login page.
2364 # Even anons need to be able to log in.
2365 $whitelisted = true;
2366 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2367 # Time to check the whitelist
2368 # Only do these checks is there's something to check against
2369 $name = $this->getPrefixedText();
2370 $dbName = $this->getPrefixedDBkey();
2372 // Check for explicit whitelisting with and without underscores
2373 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2374 $whitelisted = true;
2375 } elseif ( $this->getNamespace() == NS_MAIN
) {
2376 # Old settings might have the title prefixed with
2377 # a colon for main-namespace pages
2378 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2379 $whitelisted = true;
2381 } elseif ( $this->isSpecialPage() ) {
2382 # If it's a special page, ditch the subpage bit and check again
2383 $name = $this->getDBkey();
2384 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2386 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2387 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2388 $whitelisted = true;
2394 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2395 $name = $this->getPrefixedText();
2396 // Check for regex whitelisting
2397 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2398 if ( preg_match( $listItem, $name ) ) {
2399 $whitelisted = true;
2405 if ( !$whitelisted ) {
2406 # If the title is not whitelisted, give extensions a chance to do so...
2407 Hooks
::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2408 if ( !$whitelisted ) {
2409 $errors[] = $this->missingPermissionError( $action, $short );
2417 * Get a description array when the user doesn't have the right to perform
2418 * $action (i.e. when User::isAllowed() returns false)
2420 * @param string $action The action to check
2421 * @param bool $short Short circuit on first error
2422 * @return array List of errors
2424 private function missingPermissionError( $action, $short ) {
2425 // We avoid expensive display logic for quickUserCan's and such
2427 return array( 'badaccess-group0' );
2430 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2431 User
::getGroupsWithPermission( $action ) );
2433 if ( count( $groups ) ) {
2437 $wgLang->commaList( $groups ),
2441 return array( 'badaccess-group0' );
2446 * Can $user perform $action on this page? This is an internal function,
2447 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2448 * checks on wfReadOnly() and blocks)
2450 * @param string $action Action that permission needs to be checked for
2451 * @param User $user User to check
2452 * @param string $rigor One of (quick,full,secure)
2453 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2454 * - full : does cheap and expensive checks possibly from a slave
2455 * - secure : does cheap and expensive checks, using the master as needed
2456 * @param bool $short Set this to true to stop after the first permission error.
2457 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2459 protected function getUserPermissionsErrorsInternal(
2460 $action, $user, $rigor = 'secure', $short = false
2462 if ( $rigor === true ) {
2463 $rigor = 'secure'; // b/c
2464 } elseif ( $rigor === false ) {
2465 $rigor = 'quick'; // b/c
2466 } elseif ( !in_array( $rigor, array( 'quick', 'full', 'secure' ) ) ) {
2467 throw new Exception( "Invalid rigor parameter '$rigor'." );
2470 # Read has special handling
2471 if ( $action == 'read' ) {
2473 'checkPermissionHooks',
2474 'checkReadPermissions',
2476 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2477 # here as it will lead to duplicate error messages. This is okay to do
2478 # since anywhere that checks for create will also check for edit, and
2479 # those checks are called for edit.
2480 } elseif ( $action == 'create' ) {
2482 'checkQuickPermissions',
2483 'checkPermissionHooks',
2484 'checkPageRestrictions',
2485 'checkCascadingSourcesRestrictions',
2486 'checkActionPermissions',
2491 'checkQuickPermissions',
2492 'checkPermissionHooks',
2493 'checkSpecialsAndNSPermissions',
2494 'checkCSSandJSPermissions',
2495 'checkPageRestrictions',
2496 'checkCascadingSourcesRestrictions',
2497 'checkActionPermissions',
2503 while ( count( $checks ) > 0 &&
2504 !( $short && count( $errors ) > 0 ) ) {
2505 $method = array_shift( $checks );
2506 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2513 * Get a filtered list of all restriction types supported by this wiki.
2514 * @param bool $exists True to get all restriction types that apply to
2515 * titles that do exist, False for all restriction types that apply to
2516 * titles that do not exist
2519 public static function getFilteredRestrictionTypes( $exists = true ) {
2520 global $wgRestrictionTypes;
2521 $types = $wgRestrictionTypes;
2523 # Remove the create restriction for existing titles
2524 $types = array_diff( $types, array( 'create' ) );
2526 # Only the create and upload restrictions apply to non-existing titles
2527 $types = array_intersect( $types, array( 'create', 'upload' ) );
2533 * Returns restriction types for the current Title
2535 * @return array Applicable restriction types
2537 public function getRestrictionTypes() {
2538 if ( $this->isSpecialPage() ) {
2542 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2544 if ( $this->getNamespace() != NS_FILE
) {
2545 # Remove the upload restriction for non-file titles
2546 $types = array_diff( $types, array( 'upload' ) );
2549 Hooks
::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2551 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2552 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2558 * Is this title subject to title protection?
2559 * Title protection is the one applied against creation of such title.
2561 * @return array|bool An associative array representing any existent title
2562 * protection, or false if there's none.
2564 public function getTitleProtection() {
2565 // Can't protect pages in special namespaces
2566 if ( $this->getNamespace() < 0 ) {
2570 // Can't protect pages that exist.
2571 if ( $this->exists() ) {
2575 if ( $this->mTitleProtection
=== null ) {
2576 $dbr = wfGetDB( DB_SLAVE
);
2577 $res = $dbr->select(
2580 'user' => 'pt_user',
2581 'reason' => 'pt_reason',
2582 'expiry' => 'pt_expiry',
2583 'permission' => 'pt_create_perm'
2585 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2589 // fetchRow returns false if there are no rows.
2590 $row = $dbr->fetchRow( $res );
2592 if ( $row['permission'] == 'sysop' ) {
2593 $row['permission'] = 'editprotected'; // B/C
2595 if ( $row['permission'] == 'autoconfirmed' ) {
2596 $row['permission'] = 'editsemiprotected'; // B/C
2598 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2600 $this->mTitleProtection
= $row;
2602 return $this->mTitleProtection
;
2606 * Remove any title protection due to page existing
2608 public function deleteTitleProtection() {
2609 $dbw = wfGetDB( DB_MASTER
);
2613 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2616 $this->mTitleProtection
= false;
2620 * Is this page "semi-protected" - the *only* protection levels are listed
2621 * in $wgSemiprotectedRestrictionLevels?
2623 * @param string $action Action to check (default: edit)
2626 public function isSemiProtected( $action = 'edit' ) {
2627 global $wgSemiprotectedRestrictionLevels;
2629 $restrictions = $this->getRestrictions( $action );
2630 $semi = $wgSemiprotectedRestrictionLevels;
2631 if ( !$restrictions ||
!$semi ) {
2632 // Not protected, or all protection is full protection
2636 // Remap autoconfirmed to editsemiprotected for BC
2637 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2638 $semi[$key] = 'editsemiprotected';
2640 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2641 $restrictions[$key] = 'editsemiprotected';
2644 return !array_diff( $restrictions, $semi );
2648 * Does the title correspond to a protected article?
2650 * @param string $action The action the page is protected from,
2651 * by default checks all actions.
2654 public function isProtected( $action = '' ) {
2655 global $wgRestrictionLevels;
2657 $restrictionTypes = $this->getRestrictionTypes();
2659 # Special pages have inherent protection
2660 if ( $this->isSpecialPage() ) {
2664 # Check regular protection levels
2665 foreach ( $restrictionTypes as $type ) {
2666 if ( $action == $type ||
$action == '' ) {
2667 $r = $this->getRestrictions( $type );
2668 foreach ( $wgRestrictionLevels as $level ) {
2669 if ( in_array( $level, $r ) && $level != '' ) {
2680 * Determines if $user is unable to edit this page because it has been protected
2681 * by $wgNamespaceProtection.
2683 * @param User $user User object to check permissions
2686 public function isNamespaceProtected( User
$user ) {
2687 global $wgNamespaceProtection;
2689 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2690 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2691 if ( $right != '' && !$user->isAllowed( $right ) ) {
2700 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2702 * @return bool If the page is subject to cascading restrictions.
2704 public function isCascadeProtected() {
2705 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2706 return ( $sources > 0 );
2710 * Determines whether cascading protection sources have already been loaded from
2713 * @param bool $getPages True to check if the pages are loaded, or false to check
2714 * if the status is loaded.
2715 * @return bool Whether or not the specified information has been loaded
2718 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2719 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2723 * Cascading protection: Get the source of any cascading restrictions on this page.
2725 * @param bool $getPages Whether or not to retrieve the actual pages
2726 * that the restrictions have come from and the actual restrictions
2728 * @return array Two elements: First is an array of Title objects of the
2729 * pages from which cascading restrictions have come, false for
2730 * none, or true if such restrictions exist but $getPages was not
2731 * set. Second is an array like that returned by
2732 * Title::getAllRestrictions(), or an empty array if $getPages is
2735 public function getCascadeProtectionSources( $getPages = true ) {
2736 $pagerestrictions = array();
2738 if ( $this->mCascadeSources
!== null && $getPages ) {
2739 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2740 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2741 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2744 $dbr = wfGetDB( DB_SLAVE
);
2746 if ( $this->getNamespace() == NS_FILE
) {
2747 $tables = array( 'imagelinks', 'page_restrictions' );
2748 $where_clauses = array(
2749 'il_to' => $this->getDBkey(),
2754 $tables = array( 'templatelinks', 'page_restrictions' );
2755 $where_clauses = array(
2756 'tl_namespace' => $this->getNamespace(),
2757 'tl_title' => $this->getDBkey(),
2764 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2765 'pr_expiry', 'pr_type', 'pr_level' );
2766 $where_clauses[] = 'page_id=pr_page';
2769 $cols = array( 'pr_expiry' );
2772 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2774 $sources = $getPages ?
array() : false;
2775 $now = wfTimestampNow();
2777 foreach ( $res as $row ) {
2778 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2779 if ( $expiry > $now ) {
2781 $page_id = $row->pr_page
;
2782 $page_ns = $row->page_namespace
;
2783 $page_title = $row->page_title
;
2784 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2785 # Add groups needed for each restriction type if its not already there
2786 # Make sure this restriction type still exists
2788 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2789 $pagerestrictions[$row->pr_type
] = array();
2793 isset( $pagerestrictions[$row->pr_type
] )
2794 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2796 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2805 $this->mCascadeSources
= $sources;
2806 $this->mCascadingRestrictions
= $pagerestrictions;
2808 $this->mHasCascadingRestrictions
= $sources;
2811 return array( $sources, $pagerestrictions );
2815 * Accessor for mRestrictionsLoaded
2817 * @return bool Whether or not the page's restrictions have already been
2818 * loaded from the database
2821 public function areRestrictionsLoaded() {
2822 return $this->mRestrictionsLoaded
;
2826 * Accessor/initialisation for mRestrictions
2828 * @param string $action Action that permission needs to be checked for
2829 * @return array Restriction levels needed to take the action. All levels are
2830 * required. Note that restriction levels are normally user rights, but 'sysop'
2831 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2832 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2834 public function getRestrictions( $action ) {
2835 if ( !$this->mRestrictionsLoaded
) {
2836 $this->loadRestrictions();
2838 return isset( $this->mRestrictions
[$action] )
2839 ?
$this->mRestrictions
[$action]
2844 * Accessor/initialisation for mRestrictions
2846 * @return array Keys are actions, values are arrays as returned by
2847 * Title::getRestrictions()
2850 public function getAllRestrictions() {
2851 if ( !$this->mRestrictionsLoaded
) {
2852 $this->loadRestrictions();
2854 return $this->mRestrictions
;
2858 * Get the expiry time for the restriction against a given action
2860 * @param string $action
2861 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2862 * or not protected at all, or false if the action is not recognised.
2864 public function getRestrictionExpiry( $action ) {
2865 if ( !$this->mRestrictionsLoaded
) {
2866 $this->loadRestrictions();
2868 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2872 * Returns cascading restrictions for the current article
2876 function areRestrictionsCascading() {
2877 if ( !$this->mRestrictionsLoaded
) {
2878 $this->loadRestrictions();
2881 return $this->mCascadeRestriction
;
2885 * Loads a string into mRestrictions array
2887 * @param ResultWrapper $res Resource restrictions as an SQL result.
2888 * @param string $oldFashionedRestrictions Comma-separated list of page
2889 * restrictions from page table (pre 1.10)
2891 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2894 foreach ( $res as $row ) {
2898 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2902 * Compiles list of active page restrictions from both page table (pre 1.10)
2903 * and page_restrictions table for this existing page.
2904 * Public for usage by LiquidThreads.
2906 * @param array $rows Array of db result objects
2907 * @param string $oldFashionedRestrictions Comma-separated list of page
2908 * restrictions from page table (pre 1.10)
2910 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2911 $dbr = wfGetDB( DB_SLAVE
);
2913 $restrictionTypes = $this->getRestrictionTypes();
2915 foreach ( $restrictionTypes as $type ) {
2916 $this->mRestrictions
[$type] = array();
2917 $this->mRestrictionsExpiry
[$type] = 'infinity';
2920 $this->mCascadeRestriction
= false;
2922 # Backwards-compatibility: also load the restrictions from the page record (old format).
2923 if ( $oldFashionedRestrictions !== null ) {
2924 $this->mOldRestrictions
= $oldFashionedRestrictions;
2927 if ( $this->mOldRestrictions
=== false ) {
2928 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2929 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2932 if ( $this->mOldRestrictions
!= '' ) {
2933 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2934 $temp = explode( '=', trim( $restrict ) );
2935 if ( count( $temp ) == 1 ) {
2936 // old old format should be treated as edit/move restriction
2937 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2938 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2940 $restriction = trim( $temp[1] );
2941 if ( $restriction != '' ) { // some old entries are empty
2942 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2948 if ( count( $rows ) ) {
2949 # Current system - load second to make them override.
2950 $now = wfTimestampNow();
2952 # Cycle through all the restrictions.
2953 foreach ( $rows as $row ) {
2955 // Don't take care of restrictions types that aren't allowed
2956 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2960 // This code should be refactored, now that it's being used more generally,
2961 // But I don't really see any harm in leaving it in Block for now -werdna
2962 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2964 // Only apply the restrictions if they haven't expired!
2965 if ( !$expiry ||
$expiry > $now ) {
2966 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2967 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2969 $this->mCascadeRestriction |
= $row->pr_cascade
;
2974 $this->mRestrictionsLoaded
= true;
2978 * Load restrictions from the page_restrictions table
2980 * @param string $oldFashionedRestrictions Comma-separated list of page
2981 * restrictions from page table (pre 1.10)
2983 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2984 if ( !$this->mRestrictionsLoaded
) {
2985 $dbr = wfGetDB( DB_SLAVE
);
2986 if ( $this->exists() ) {
2987 $res = $dbr->select(
2988 'page_restrictions',
2989 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2990 array( 'pr_page' => $this->getArticleID() ),
2994 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2996 $title_protection = $this->getTitleProtection();
2998 if ( $title_protection ) {
2999 $now = wfTimestampNow();
3000 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
3002 if ( !$expiry ||
$expiry > $now ) {
3003 // Apply the restrictions
3004 $this->mRestrictionsExpiry
['create'] = $expiry;
3005 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
3006 } else { // Get rid of the old restrictions
3007 $this->mTitleProtection
= false;
3010 $this->mRestrictionsExpiry
['create'] = 'infinity';
3012 $this->mRestrictionsLoaded
= true;
3018 * Flush the protection cache in this object and force reload from the database.
3019 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3021 public function flushRestrictions() {
3022 $this->mRestrictionsLoaded
= false;
3023 $this->mTitleProtection
= null;
3027 * Purge expired restrictions from the page_restrictions table
3029 static function purgeExpiredRestrictions() {
3030 if ( wfReadOnly() ) {
3034 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3035 wfGetDB( DB_MASTER
),
3037 function ( IDatabase
$dbw, $fname ) {
3039 'page_restrictions',
3040 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3045 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3053 * Does this have subpages? (Warning, usually requires an extra DB query.)
3057 public function hasSubpages() {
3058 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3063 # We dynamically add a member variable for the purpose of this method
3064 # alone to cache the result. There's no point in having it hanging
3065 # around uninitialized in every Title object; therefore we only add it
3066 # if needed and don't declare it statically.
3067 if ( $this->mHasSubpages
=== null ) {
3068 $this->mHasSubpages
= false;
3069 $subpages = $this->getSubpages( 1 );
3070 if ( $subpages instanceof TitleArray
) {
3071 $this->mHasSubpages
= (bool)$subpages->count();
3075 return $this->mHasSubpages
;
3079 * Get all subpages of this page.
3081 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3082 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3083 * doesn't allow subpages
3085 public function getSubpages( $limit = -1 ) {
3086 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3090 $dbr = wfGetDB( DB_SLAVE
);
3091 $conds['page_namespace'] = $this->getNamespace();
3092 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3094 if ( $limit > -1 ) {
3095 $options['LIMIT'] = $limit;
3097 $this->mSubpages
= TitleArray
::newFromResult(
3098 $dbr->select( 'page',
3099 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3105 return $this->mSubpages
;
3109 * Is there a version of this page in the deletion archive?
3111 * @return int The number of archived revisions
3113 public function isDeleted() {
3114 if ( $this->getNamespace() < 0 ) {
3117 $dbr = wfGetDB( DB_SLAVE
);
3119 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3120 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3123 if ( $this->getNamespace() == NS_FILE
) {
3124 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3125 array( 'fa_name' => $this->getDBkey() ),
3134 * Is there a version of this page in the deletion archive?
3138 public function isDeletedQuick() {
3139 if ( $this->getNamespace() < 0 ) {
3142 $dbr = wfGetDB( DB_SLAVE
);
3143 $deleted = (bool)$dbr->selectField( 'archive', '1',
3144 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3147 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3148 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3149 array( 'fa_name' => $this->getDBkey() ),
3157 * Get the article ID for this Title from the link cache,
3158 * adding it if necessary
3160 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3162 * @return int The ID
3164 public function getArticleID( $flags = 0 ) {
3165 if ( $this->getNamespace() < 0 ) {
3166 $this->mArticleID
= 0;
3167 return $this->mArticleID
;
3169 $linkCache = LinkCache
::singleton();
3170 if ( $flags & self
::GAID_FOR_UPDATE
) {
3171 $oldUpdate = $linkCache->forUpdate( true );
3172 $linkCache->clearLink( $this );
3173 $this->mArticleID
= $linkCache->addLinkObj( $this );
3174 $linkCache->forUpdate( $oldUpdate );
3176 if ( -1 == $this->mArticleID
) {
3177 $this->mArticleID
= $linkCache->addLinkObj( $this );
3180 return $this->mArticleID
;
3184 * Is this an article that is a redirect page?
3185 * Uses link cache, adding it if necessary
3187 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3190 public function isRedirect( $flags = 0 ) {
3191 if ( !is_null( $this->mRedirect
) ) {
3192 return $this->mRedirect
;
3194 if ( !$this->getArticleID( $flags ) ) {
3195 $this->mRedirect
= false;
3196 return $this->mRedirect
;
3199 $linkCache = LinkCache
::singleton();
3200 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3201 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3202 if ( $cached === null ) {
3203 # Trust LinkCache's state over our own
3204 # LinkCache is telling us that the page doesn't exist, despite there being cached
3205 # data relating to an existing page in $this->mArticleID. Updaters should clear
3206 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3207 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3208 # LinkCache to refresh its data from the master.
3209 $this->mRedirect
= false;
3210 return $this->mRedirect
;
3213 $this->mRedirect
= (bool)$cached;
3215 return $this->mRedirect
;
3219 * What is the length of this page?
3220 * Uses link cache, adding it if necessary
3222 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3225 public function getLength( $flags = 0 ) {
3226 if ( $this->mLength
!= -1 ) {
3227 return $this->mLength
;
3229 if ( !$this->getArticleID( $flags ) ) {
3231 return $this->mLength
;
3233 $linkCache = LinkCache
::singleton();
3234 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3235 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3236 if ( $cached === null ) {
3237 # Trust LinkCache's state over our own, as for isRedirect()
3239 return $this->mLength
;
3242 $this->mLength
= intval( $cached );
3244 return $this->mLength
;
3248 * What is the page_latest field for this page?
3250 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3251 * @return int Int or 0 if the page doesn't exist
3253 public function getLatestRevID( $flags = 0 ) {
3254 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3255 return intval( $this->mLatestID
);
3257 if ( !$this->getArticleID( $flags ) ) {
3258 $this->mLatestID
= 0;
3259 return $this->mLatestID
;
3261 $linkCache = LinkCache
::singleton();
3262 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3263 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3264 if ( $cached === null ) {
3265 # Trust LinkCache's state over our own, as for isRedirect()
3266 $this->mLatestID
= 0;
3267 return $this->mLatestID
;
3270 $this->mLatestID
= intval( $cached );
3272 return $this->mLatestID
;
3276 * This clears some fields in this object, and clears any associated
3277 * keys in the "bad links" section of the link cache.
3279 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3280 * loading of the new page_id. It's also called from
3281 * WikiPage::doDeleteArticleReal()
3283 * @param int $newid The new Article ID
3285 public function resetArticleID( $newid ) {
3286 $linkCache = LinkCache
::singleton();
3287 $linkCache->clearLink( $this );
3289 if ( $newid === false ) {
3290 $this->mArticleID
= -1;
3292 $this->mArticleID
= intval( $newid );
3294 $this->mRestrictionsLoaded
= false;
3295 $this->mRestrictions
= array();
3296 $this->mOldRestrictions
= false;
3297 $this->mRedirect
= null;
3298 $this->mLength
= -1;
3299 $this->mLatestID
= false;
3300 $this->mContentModel
= false;
3301 $this->mEstimateRevisions
= null;
3302 $this->mPageLanguage
= false;
3303 $this->mDbPageLanguage
= null;
3304 $this->mIsBigDeletion
= null;
3307 public static function clearCaches() {
3308 $linkCache = LinkCache
::singleton();
3309 $linkCache->clear();
3311 $titleCache = self
::getTitleCache();
3312 $titleCache->clear();
3316 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3318 * @param string $text Containing title to capitalize
3319 * @param int $ns Namespace index, defaults to NS_MAIN
3320 * @return string Containing capitalized title
3322 public static function capitalize( $text, $ns = NS_MAIN
) {
3325 if ( MWNamespace
::isCapitalized( $ns ) ) {
3326 return $wgContLang->ucfirst( $text );
3333 * Secure and split - main initialisation function for this object
3335 * Assumes that mDbkeyform has been set, and is urldecoded
3336 * and uses underscores, but not otherwise munged. This function
3337 * removes illegal characters, splits off the interwiki and
3338 * namespace prefixes, sets the other forms, and canonicalizes
3341 * @throws MalformedTitleException On invalid titles
3342 * @return bool True on success
3344 private function secureAndSplit() {
3346 $this->mInterwiki
= '';
3347 $this->mFragment
= '';
3348 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3350 $dbkey = $this->mDbkeyform
;
3352 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3353 // the parsing code with Title, while avoiding massive refactoring.
3354 // @todo: get rid of secureAndSplit, refactor parsing code.
3355 $titleParser = self
::getTitleParser();
3356 // MalformedTitleException can be thrown here
3357 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3360 $this->setFragment( '#' . $parts['fragment'] );
3361 $this->mInterwiki
= $parts['interwiki'];
3362 $this->mLocalInterwiki
= $parts['local_interwiki'];
3363 $this->mNamespace
= $parts['namespace'];
3364 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3366 $this->mDbkeyform
= $parts['dbkey'];
3367 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3368 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3370 # We already know that some pages won't be in the database!
3371 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3372 $this->mArticleID
= 0;
3379 * Get an array of Title objects linking to this Title
3380 * Also stores the IDs in the link cache.
3382 * WARNING: do not use this function on arbitrary user-supplied titles!
3383 * On heavily-used templates it will max out the memory.
3385 * @param array $options May be FOR UPDATE
3386 * @param string $table Table name
3387 * @param string $prefix Fields prefix
3388 * @return Title[] Array of Title objects linking here
3390 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3391 if ( count( $options ) > 0 ) {
3392 $db = wfGetDB( DB_MASTER
);
3394 $db = wfGetDB( DB_SLAVE
);
3398 array( 'page', $table ),
3399 self
::getSelectFields(),
3401 "{$prefix}_from=page_id",
3402 "{$prefix}_namespace" => $this->getNamespace(),
3403 "{$prefix}_title" => $this->getDBkey() ),
3409 if ( $res->numRows() ) {
3410 $linkCache = LinkCache
::singleton();
3411 foreach ( $res as $row ) {
3412 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3414 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3415 $retVal[] = $titleObj;
3423 * Get an array of Title objects using this Title as a template
3424 * Also stores the IDs in the link cache.
3426 * WARNING: do not use this function on arbitrary user-supplied titles!
3427 * On heavily-used templates it will max out the memory.
3429 * @param array $options May be FOR UPDATE
3430 * @return Title[] Array of Title the Title objects linking here
3432 public function getTemplateLinksTo( $options = array() ) {
3433 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3437 * Get an array of Title objects linked from this Title
3438 * Also stores the IDs in the link cache.
3440 * WARNING: do not use this function on arbitrary user-supplied titles!
3441 * On heavily-used templates it will max out the memory.
3443 * @param array $options May be FOR UPDATE
3444 * @param string $table Table name
3445 * @param string $prefix Fields prefix
3446 * @return array Array of Title objects linking here
3448 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3449 $id = $this->getArticleID();
3451 # If the page doesn't exist; there can't be any link from this page
3456 if ( count( $options ) > 0 ) {
3457 $db = wfGetDB( DB_MASTER
);
3459 $db = wfGetDB( DB_SLAVE
);
3462 $blNamespace = "{$prefix}_namespace";
3463 $blTitle = "{$prefix}_title";
3466 array( $table, 'page' ),
3468 array( $blNamespace, $blTitle ),
3469 WikiPage
::selectFields()
3471 array( "{$prefix}_from" => $id ),
3474 array( 'page' => array(
3476 array( "page_namespace=$blNamespace", "page_title=$blTitle" )
3481 $linkCache = LinkCache
::singleton();
3482 foreach ( $res as $row ) {
3483 if ( $row->page_id
) {
3484 $titleObj = Title
::newFromRow( $row );
3486 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3487 $linkCache->addBadLinkObj( $titleObj );
3489 $retVal[] = $titleObj;
3496 * Get an array of Title objects used on this Title as a template
3497 * Also stores the IDs in the link cache.
3499 * WARNING: do not use this function on arbitrary user-supplied titles!
3500 * On heavily-used templates it will max out the memory.
3502 * @param array $options May be FOR UPDATE
3503 * @return Title[] Array of Title the Title objects used here
3505 public function getTemplateLinksFrom( $options = array() ) {
3506 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3510 * Get an array of Title objects referring to non-existent articles linked
3513 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3514 * should use redirect table in this case).
3515 * @return Title[] Array of Title the Title objects
3517 public function getBrokenLinksFrom() {
3518 if ( $this->getArticleID() == 0 ) {
3519 # All links from article ID 0 are false positives
3523 $dbr = wfGetDB( DB_SLAVE
);
3524 $res = $dbr->select(
3525 array( 'page', 'pagelinks' ),
3526 array( 'pl_namespace', 'pl_title' ),
3528 'pl_from' => $this->getArticleID(),
3529 'page_namespace IS NULL'
3531 __METHOD__
, array(),
3535 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3541 foreach ( $res as $row ) {
3542 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3548 * Get a list of URLs to purge from the CDN cache when this
3551 * @return string[] Array of String the URLs
3553 public function getCdnUrls() {
3555 $this->getInternalURL(),
3556 $this->getInternalURL( 'action=history' )
3559 $pageLang = $this->getPageLanguage();
3560 if ( $pageLang->hasVariants() ) {
3561 $variants = $pageLang->getVariants();
3562 foreach ( $variants as $vCode ) {
3563 $urls[] = $this->getInternalURL( $vCode );
3567 // If we are looking at a css/js user subpage, purge the action=raw.
3568 if ( $this->isJsSubpage() ) {
3569 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3570 } elseif ( $this->isCssSubpage() ) {
3571 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3574 Hooks
::run( 'TitleSquidURLs', array( $this, &$urls ) );
3579 * @deprecated since 1.27 use getCdnUrls()
3581 public function getSquidURLs() {
3582 return $this->getCdnUrls();
3586 * Purge all applicable CDN URLs
3588 public function purgeSquid() {
3589 DeferredUpdates
::addUpdate(
3590 new CdnCacheUpdate( $this->getCdnUrls() ),
3591 DeferredUpdates
::PRESEND
3596 * Move this page without authentication
3598 * @deprecated since 1.25 use MovePage class instead
3599 * @param Title $nt The new page Title
3600 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3602 public function moveNoAuth( &$nt ) {
3603 wfDeprecated( __METHOD__
, '1.25' );
3604 return $this->moveTo( $nt, false );
3608 * Check whether a given move operation would be valid.
3609 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3611 * @deprecated since 1.25, use MovePage's methods instead
3612 * @param Title $nt The new title
3613 * @param bool $auth Whether to check user permissions (uses $wgUser)
3614 * @param string $reason Is the log summary of the move, used for spam checking
3615 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3617 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3620 if ( !( $nt instanceof Title
) ) {
3621 // Normally we'd add this to $errors, but we'll get
3622 // lots of syntax errors if $nt is not an object
3623 return array( array( 'badtitletext' ) );
3626 $mp = new MovePage( $this, $nt );
3627 $errors = $mp->isValidMove()->getErrorsArray();
3629 $errors = wfMergeErrorArrays(
3631 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3635 return $errors ?
: true;
3639 * Check if the requested move target is a valid file move target
3640 * @todo move this to MovePage
3641 * @param Title $nt Target title
3642 * @return array List of errors
3644 protected function validateFileMoveOperation( $nt ) {
3649 $destFile = wfLocalFile( $nt );
3650 $destFile->load( File
::READ_LATEST
);
3651 if ( !$wgUser->isAllowed( 'reupload-shared' )
3652 && !$destFile->exists() && wfFindFile( $nt )
3654 $errors[] = array( 'file-exists-sharedrepo' );
3661 * Move a title to a new location
3663 * @deprecated since 1.25, use the MovePage class instead
3664 * @param Title $nt The new title
3665 * @param bool $auth Indicates whether $wgUser's permissions
3667 * @param string $reason The reason for the move
3668 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3669 * Ignored if the user doesn't have the suppressredirect right.
3670 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3672 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3674 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3675 if ( is_array( $err ) ) {
3676 // Auto-block user's IP if the account was "hard" blocked
3677 $wgUser->spreadAnyEditBlock();
3680 // Check suppressredirect permission
3681 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3682 $createRedirect = true;
3685 $mp = new MovePage( $this, $nt );
3686 $status = $mp->move( $wgUser, $reason, $createRedirect );
3687 if ( $status->isOK() ) {
3690 return $status->getErrorsArray();
3695 * Move this page's subpages to be subpages of $nt
3697 * @param Title $nt Move target
3698 * @param bool $auth Whether $wgUser's permissions should be checked
3699 * @param string $reason The reason for the move
3700 * @param bool $createRedirect Whether to create redirects from the old subpages to
3701 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3702 * @return array Array with old page titles as keys, and strings (new page titles) or
3703 * arrays (errors) as values, or an error array with numeric indices if no pages
3706 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3707 global $wgMaximumMovedPages;
3708 // Check permissions
3709 if ( !$this->userCan( 'move-subpages' ) ) {
3710 return array( 'cant-move-subpages' );
3712 // Do the source and target namespaces support subpages?
3713 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3714 return array( 'namespace-nosubpages',
3715 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3717 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3718 return array( 'namespace-nosubpages',
3719 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3722 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3725 foreach ( $subpages as $oldSubpage ) {
3727 if ( $count > $wgMaximumMovedPages ) {
3728 $retval[$oldSubpage->getPrefixedText()] =
3729 array( 'movepage-max-pages',
3730 $wgMaximumMovedPages );
3734 // We don't know whether this function was called before
3735 // or after moving the root page, so check both
3737 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3738 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3740 // When moving a page to a subpage of itself,
3741 // don't move it twice
3744 $newPageName = preg_replace(
3745 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3746 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3747 $oldSubpage->getDBkey() );
3748 if ( $oldSubpage->isTalkPage() ) {
3749 $newNs = $nt->getTalkPage()->getNamespace();
3751 $newNs = $nt->getSubjectPage()->getNamespace();
3753 # Bug 14385: we need makeTitleSafe because the new page names may
3754 # be longer than 255 characters.
3755 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3757 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3758 if ( $success === true ) {
3759 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3761 $retval[$oldSubpage->getPrefixedText()] = $success;
3768 * Checks if this page is just a one-rev redirect.
3769 * Adds lock, so don't use just for light purposes.
3773 public function isSingleRevRedirect() {
3774 global $wgContentHandlerUseDB;
3776 $dbw = wfGetDB( DB_MASTER
);
3779 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3780 if ( $wgContentHandlerUseDB ) {
3781 $fields[] = 'page_content_model';
3784 $row = $dbw->selectRow( 'page',
3788 array( 'FOR UPDATE' )
3790 # Cache some fields we may want
3791 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3792 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3793 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3794 $this->mContentModel
= $row && isset( $row->page_content_model
)
3795 ?
strval( $row->page_content_model
)
3798 if ( !$this->mRedirect
) {
3801 # Does the article have a history?
3802 $row = $dbw->selectField( array( 'page', 'revision' ),
3804 array( 'page_namespace' => $this->getNamespace(),
3805 'page_title' => $this->getDBkey(),
3807 'page_latest != rev_id'
3810 array( 'FOR UPDATE' )
3812 # Return true if there was no history
3813 return ( $row === false );
3817 * Checks if $this can be moved to a given Title
3818 * - Selects for update, so don't call it unless you mean business
3820 * @deprecated since 1.25, use MovePage's methods instead
3821 * @param Title $nt The new title to check
3824 public function isValidMoveTarget( $nt ) {
3825 # Is it an existing file?
3826 if ( $nt->getNamespace() == NS_FILE
) {
3827 $file = wfLocalFile( $nt );
3828 $file->load( File
::READ_LATEST
);
3829 if ( $file->exists() ) {
3830 wfDebug( __METHOD__
. ": file exists\n" );
3834 # Is it a redirect with no history?
3835 if ( !$nt->isSingleRevRedirect() ) {
3836 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3839 # Get the article text
3840 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3841 if ( !is_object( $rev ) ) {
3844 $content = $rev->getContent();
3845 # Does the redirect point to the source?
3846 # Or is it a broken self-redirect, usually caused by namespace collisions?
3847 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3849 if ( $redirTitle ) {
3850 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3851 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3852 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3858 # Fail safe (not a redirect after all. strange.)
3859 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3860 " is a redirect, but it doesn't contain a valid redirect.\n" );
3866 * Get categories to which this Title belongs and return an array of
3867 * categories' names.
3869 * @return array Array of parents in the form:
3870 * $parent => $currentarticle
3872 public function getParentCategories() {
3877 $titleKey = $this->getArticleID();
3879 if ( $titleKey === 0 ) {
3883 $dbr = wfGetDB( DB_SLAVE
);
3885 $res = $dbr->select(
3888 array( 'cl_from' => $titleKey ),
3892 if ( $res->numRows() > 0 ) {
3893 foreach ( $res as $row ) {
3894 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3895 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3902 * Get a tree of parent categories
3904 * @param array $children Array with the children in the keys, to check for circular refs
3905 * @return array Tree of parent categories
3907 public function getParentCategoryTree( $children = array() ) {
3909 $parents = $this->getParentCategories();
3912 foreach ( $parents as $parent => $current ) {
3913 if ( array_key_exists( $parent, $children ) ) {
3914 # Circular reference
3915 $stack[$parent] = array();
3917 $nt = Title
::newFromText( $parent );
3919 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3929 * Get an associative array for selecting this title from
3932 * @return array Array suitable for the $where parameter of DB::select()
3934 public function pageCond() {
3935 if ( $this->mArticleID
> 0 ) {
3936 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3937 return array( 'page_id' => $this->mArticleID
);
3939 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3944 * Get the revision ID of the previous revision
3946 * @param int $revId Revision ID. Get the revision that was before this one.
3947 * @param int $flags Title::GAID_FOR_UPDATE
3948 * @return int|bool Old revision ID, or false if none exists
3950 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3951 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3952 $revId = $db->selectField( 'revision', 'rev_id',
3954 'rev_page' => $this->getArticleID( $flags ),
3955 'rev_id < ' . intval( $revId )
3958 array( 'ORDER BY' => 'rev_id DESC' )
3961 if ( $revId === false ) {
3964 return intval( $revId );
3969 * Get the revision ID of the next revision
3971 * @param int $revId Revision ID. Get the revision that was after this one.
3972 * @param int $flags Title::GAID_FOR_UPDATE
3973 * @return int|bool Next revision ID, or false if none exists
3975 public function getNextRevisionID( $revId, $flags = 0 ) {
3976 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3977 $revId = $db->selectField( 'revision', 'rev_id',
3979 'rev_page' => $this->getArticleID( $flags ),
3980 'rev_id > ' . intval( $revId )
3983 array( 'ORDER BY' => 'rev_id' )
3986 if ( $revId === false ) {
3989 return intval( $revId );
3994 * Get the first revision of the page
3996 * @param int $flags Title::GAID_FOR_UPDATE
3997 * @return Revision|null If page doesn't exist
3999 public function getFirstRevision( $flags = 0 ) {
4000 $pageId = $this->getArticleID( $flags );
4002 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4003 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4004 array( 'rev_page' => $pageId ),
4006 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4009 return new Revision( $row );
4016 * Get the oldest revision timestamp of this page
4018 * @param int $flags Title::GAID_FOR_UPDATE
4019 * @return string MW timestamp
4021 public function getEarliestRevTime( $flags = 0 ) {
4022 $rev = $this->getFirstRevision( $flags );
4023 return $rev ?
$rev->getTimestamp() : null;
4027 * Check if this is a new page
4031 public function isNewPage() {
4032 $dbr = wfGetDB( DB_SLAVE
);
4033 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4037 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4041 public function isBigDeletion() {
4042 global $wgDeleteRevisionsLimit;
4044 if ( !$wgDeleteRevisionsLimit ) {
4048 if ( $this->mIsBigDeletion
=== null ) {
4049 $dbr = wfGetDB( DB_SLAVE
);
4051 $revCount = $dbr->selectRowCount(
4054 array( 'rev_page' => $this->getArticleID() ),
4056 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4059 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4062 return $this->mIsBigDeletion
;
4066 * Get the approximate revision count of this page.
4070 public function estimateRevisionCount() {
4071 if ( !$this->exists() ) {
4075 if ( $this->mEstimateRevisions
=== null ) {
4076 $dbr = wfGetDB( DB_SLAVE
);
4077 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4078 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4081 return $this->mEstimateRevisions
;
4085 * Get the number of revisions between the given revision.
4086 * Used for diffs and other things that really need it.
4088 * @param int|Revision $old Old revision or rev ID (first before range)
4089 * @param int|Revision $new New revision or rev ID (first after range)
4090 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4091 * @return int Number of revisions between these revisions.
4093 public function countRevisionsBetween( $old, $new, $max = null ) {
4094 if ( !( $old instanceof Revision
) ) {
4095 $old = Revision
::newFromTitle( $this, (int)$old );
4097 if ( !( $new instanceof Revision
) ) {
4098 $new = Revision
::newFromTitle( $this, (int)$new );
4100 if ( !$old ||
!$new ) {
4101 return 0; // nothing to compare
4103 $dbr = wfGetDB( DB_SLAVE
);
4105 'rev_page' => $this->getArticleID(),
4106 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4107 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4109 if ( $max !== null ) {
4110 return $dbr->selectRowCount( 'revision', '1',
4113 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4116 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4121 * Get the authors between the given revisions or revision IDs.
4122 * Used for diffs and other things that really need it.
4126 * @param int|Revision $old Old revision or rev ID (first before range by default)
4127 * @param int|Revision $new New revision or rev ID (first after range by default)
4128 * @param int $limit Maximum number of authors
4129 * @param string|array $options (Optional): Single option, or an array of options:
4130 * 'include_old' Include $old in the range; $new is excluded.
4131 * 'include_new' Include $new in the range; $old is excluded.
4132 * 'include_both' Include both $old and $new in the range.
4133 * Unknown option values are ignored.
4134 * @return array|null Names of revision authors in the range; null if not both revisions exist
4136 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4137 if ( !( $old instanceof Revision
) ) {
4138 $old = Revision
::newFromTitle( $this, (int)$old );
4140 if ( !( $new instanceof Revision
) ) {
4141 $new = Revision
::newFromTitle( $this, (int)$new );
4143 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4144 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4145 // in the sanity check below?
4146 if ( !$old ||
!$new ) {
4147 return null; // nothing to compare
4152 $options = (array)$options;
4153 if ( in_array( 'include_old', $options ) ) {
4156 if ( in_array( 'include_new', $options ) ) {
4159 if ( in_array( 'include_both', $options ) ) {
4163 // No DB query needed if $old and $new are the same or successive revisions:
4164 if ( $old->getId() === $new->getId() ) {
4165 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4167 array( $old->getUserText( Revision
::RAW
) );
4168 } elseif ( $old->getId() === $new->getParentId() ) {
4169 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4170 $authors[] = $old->getUserText( Revision
::RAW
);
4171 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4172 $authors[] = $new->getUserText( Revision
::RAW
);
4174 } elseif ( $old_cmp === '>=' ) {
4175 $authors[] = $old->getUserText( Revision
::RAW
);
4176 } elseif ( $new_cmp === '<=' ) {
4177 $authors[] = $new->getUserText( Revision
::RAW
);
4181 $dbr = wfGetDB( DB_SLAVE
);
4182 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4184 'rev_page' => $this->getArticleID(),
4185 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4186 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4188 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4190 foreach ( $res as $row ) {
4191 $authors[] = $row->rev_user_text
;
4197 * Get the number of authors between the given revisions or revision IDs.
4198 * Used for diffs and other things that really need it.
4200 * @param int|Revision $old Old revision or rev ID (first before range by default)
4201 * @param int|Revision $new New revision or rev ID (first after range by default)
4202 * @param int $limit Maximum number of authors
4203 * @param string|array $options (Optional): Single option, or an array of options:
4204 * 'include_old' Include $old in the range; $new is excluded.
4205 * 'include_new' Include $new in the range; $old is excluded.
4206 * 'include_both' Include both $old and $new in the range.
4207 * Unknown option values are ignored.
4208 * @return int Number of revision authors in the range; zero if not both revisions exist
4210 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4211 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4212 return $authors ?
count( $authors ) : 0;
4216 * Compare with another title.
4218 * @param Title $title
4221 public function equals( Title
$title ) {
4222 // Note: === is necessary for proper matching of number-like titles.
4223 return $this->getInterwiki() === $title->getInterwiki()
4224 && $this->getNamespace() == $title->getNamespace()
4225 && $this->getDBkey() === $title->getDBkey();
4229 * Check if this title is a subpage of another title
4231 * @param Title $title
4234 public function isSubpageOf( Title
$title ) {
4235 return $this->getInterwiki() === $title->getInterwiki()
4236 && $this->getNamespace() == $title->getNamespace()
4237 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4241 * Check if page exists. For historical reasons, this function simply
4242 * checks for the existence of the title in the page table, and will
4243 * thus return false for interwiki links, special pages and the like.
4244 * If you want to know if a title can be meaningfully viewed, you should
4245 * probably call the isKnown() method instead.
4247 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4248 * from master/for update
4251 public function exists( $flags = 0 ) {
4252 $exists = $this->getArticleID( $flags ) != 0;
4253 Hooks
::run( 'TitleExists', array( $this, &$exists ) );
4258 * Should links to this title be shown as potentially viewable (i.e. as
4259 * "bluelinks"), even if there's no record by this title in the page
4262 * This function is semi-deprecated for public use, as well as somewhat
4263 * misleadingly named. You probably just want to call isKnown(), which
4264 * calls this function internally.
4266 * (ISSUE: Most of these checks are cheap, but the file existence check
4267 * can potentially be quite expensive. Including it here fixes a lot of
4268 * existing code, but we might want to add an optional parameter to skip
4269 * it and any other expensive checks.)
4273 public function isAlwaysKnown() {
4277 * Allows overriding default behavior for determining if a page exists.
4278 * If $isKnown is kept as null, regular checks happen. If it's
4279 * a boolean, this value is returned by the isKnown method.
4283 * @param Title $title
4284 * @param bool|null $isKnown
4286 Hooks
::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4288 if ( !is_null( $isKnown ) ) {
4292 if ( $this->isExternal() ) {
4293 return true; // any interwiki link might be viewable, for all we know
4296 switch ( $this->mNamespace
) {
4299 // file exists, possibly in a foreign repo
4300 return (bool)wfFindFile( $this );
4302 // valid special page
4303 return SpecialPageFactory
::exists( $this->getDBkey() );
4305 // selflink, possibly with fragment
4306 return $this->mDbkeyform
== '';
4308 // known system message
4309 return $this->hasSourceText() !== false;
4316 * Does this title refer to a page that can (or might) be meaningfully
4317 * viewed? In particular, this function may be used to determine if
4318 * links to the title should be rendered as "bluelinks" (as opposed to
4319 * "redlinks" to non-existent pages).
4320 * Adding something else to this function will cause inconsistency
4321 * since LinkHolderArray calls isAlwaysKnown() and does its own
4322 * page existence check.
4326 public function isKnown() {
4327 return $this->isAlwaysKnown() ||
$this->exists();
4331 * Does this page have source text?
4335 public function hasSourceText() {
4336 if ( $this->exists() ) {
4340 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4341 // If the page doesn't exist but is a known system message, default
4342 // message content will be displayed, same for language subpages-
4343 // Use always content language to avoid loading hundreds of languages
4344 // to get the link color.
4346 list( $name, ) = MessageCache
::singleton()->figureMessage(
4347 $wgContLang->lcfirst( $this->getText() )
4349 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4350 return $message->exists();
4357 * Get the default message text or false if the message doesn't exist
4359 * @return string|bool
4361 public function getDefaultMessageText() {
4364 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4368 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4369 $wgContLang->lcfirst( $this->getText() )
4371 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4373 if ( $message->exists() ) {
4374 return $message->plain();
4381 * Updates page_touched for this page; called from LinksUpdate.php
4383 * @param string $purgeTime [optional] TS_MW timestamp
4384 * @return bool True if the update succeeded
4386 public function invalidateCache( $purgeTime = null ) {
4387 if ( wfReadOnly() ) {
4391 if ( $this->mArticleID
=== 0 ) {
4392 return true; // avoid gap locking if we know it's not there
4395 $method = __METHOD__
;
4396 $dbw = wfGetDB( DB_MASTER
);
4397 $conds = $this->pageCond();
4398 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4399 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4403 array( 'page_touched' => $dbTimestamp ),
4404 $conds +
array( 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ),
4413 * Update page_touched timestamps and send CDN purge messages for
4414 * pages linking to this title. May be sent to the job queue depending
4415 * on the number of links. Typically called on create and delete.
4417 public function touchLinks() {
4418 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4419 if ( $this->getNamespace() == NS_CATEGORY
) {
4420 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4425 * Get the last touched timestamp
4427 * @param IDatabase $db Optional db
4428 * @return string Last-touched timestamp
4430 public function getTouched( $db = null ) {
4431 if ( $db === null ) {
4432 $db = wfGetDB( DB_SLAVE
);
4434 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4439 * Get the timestamp when this page was updated since the user last saw it.
4442 * @return string|null
4444 public function getNotificationTimestamp( $user = null ) {
4447 // Assume current user if none given
4451 // Check cache first
4452 $uid = $user->getId();
4456 // avoid isset here, as it'll return false for null entries
4457 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4458 return $this->mNotificationTimestamp
[$uid];
4460 // Don't cache too much!
4461 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4462 $this->mNotificationTimestamp
= array();
4465 $watchedItem = WatchedItem
::fromUserTitle( $user, $this );
4466 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4468 return $this->mNotificationTimestamp
[$uid];
4472 * Generate strings used for xml 'id' names in monobook tabs
4474 * @param string $prepend Defaults to 'nstab-'
4475 * @return string XML 'id' name
4477 public function getNamespaceKey( $prepend = 'nstab-' ) {
4479 // Gets the subject namespace if this title
4480 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4481 // Checks if canonical namespace name exists for namespace
4482 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4483 // Uses canonical namespace name
4484 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4486 // Uses text of namespace
4487 $namespaceKey = $this->getSubjectNsText();
4489 // Makes namespace key lowercase
4490 $namespaceKey = $wgContLang->lc( $namespaceKey );
4492 if ( $namespaceKey == '' ) {
4493 $namespaceKey = 'main';
4495 // Changes file to image for backwards compatibility
4496 if ( $namespaceKey == 'file' ) {
4497 $namespaceKey = 'image';
4499 return $prepend . $namespaceKey;
4503 * Get all extant redirects to this Title
4505 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4506 * @return Title[] Array of Title redirects to this title
4508 public function getRedirectsHere( $ns = null ) {
4511 $dbr = wfGetDB( DB_SLAVE
);
4513 'rd_namespace' => $this->getNamespace(),
4514 'rd_title' => $this->getDBkey(),
4517 if ( $this->isExternal() ) {
4518 $where['rd_interwiki'] = $this->getInterwiki();
4520 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4522 if ( !is_null( $ns ) ) {
4523 $where['page_namespace'] = $ns;
4526 $res = $dbr->select(
4527 array( 'redirect', 'page' ),
4528 array( 'page_namespace', 'page_title' ),
4533 foreach ( $res as $row ) {
4534 $redirs[] = self
::newFromRow( $row );
4540 * Check if this Title is a valid redirect target
4544 public function isValidRedirectTarget() {
4545 global $wgInvalidRedirectTargets;
4547 if ( $this->isSpecialPage() ) {
4548 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4549 if ( $this->isSpecial( 'Userlogout' ) ) {
4553 foreach ( $wgInvalidRedirectTargets as $target ) {
4554 if ( $this->isSpecial( $target ) ) {
4564 * Get a backlink cache object
4566 * @return BacklinkCache
4568 public function getBacklinkCache() {
4569 return BacklinkCache
::get( $this );
4573 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4577 public function canUseNoindex() {
4578 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4580 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4581 ?
$wgContentNamespaces
4582 : $wgExemptFromUserRobotsControl;
4584 return !in_array( $this->mNamespace
, $bannedNamespaces );
4589 * Returns the raw sort key to be used for categories, with the specified
4590 * prefix. This will be fed to Collation::getSortKey() to get a
4591 * binary sortkey that can be used for actual sorting.
4593 * @param string $prefix The prefix to be used, specified using
4594 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4598 public function getCategorySortkey( $prefix = '' ) {
4599 $unprefixed = $this->getText();
4601 // Anything that uses this hook should only depend
4602 // on the Title object passed in, and should probably
4603 // tell the users to run updateCollations.php --force
4604 // in order to re-sort existing category relations.
4605 Hooks
::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4606 if ( $prefix !== '' ) {
4607 # Separate with a line feed, so the unprefixed part is only used as
4608 # a tiebreaker when two pages have the exact same prefix.
4609 # In UCA, tab is the only character that can sort above LF
4610 # so we strip both of them from the original prefix.
4611 $prefix = strtr( $prefix, "\n\t", ' ' );
4612 return "$prefix\n$unprefixed";
4618 * Get the language in which the content of this page is written in
4619 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4620 * e.g. $wgLang (such as special pages, which are in the user language).
4625 public function getPageLanguage() {
4626 global $wgLang, $wgLanguageCode;
4627 if ( $this->isSpecialPage() ) {
4628 // special pages are in the user language
4632 // Checking if DB language is set
4633 if ( $this->mDbPageLanguage
) {
4634 return wfGetLangObj( $this->mDbPageLanguage
);
4637 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4638 // Note that this may depend on user settings, so the cache should
4639 // be only per-request.
4640 // NOTE: ContentHandler::getPageLanguage() may need to load the
4641 // content to determine the page language!
4642 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4644 $contentHandler = ContentHandler
::getForTitle( $this );
4645 $langObj = $contentHandler->getPageLanguage( $this );
4646 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4648 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4655 * Get the language in which the content of this page is written when
4656 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4657 * e.g. $wgLang (such as special pages, which are in the user language).
4662 public function getPageViewLanguage() {
4665 if ( $this->isSpecialPage() ) {
4666 // If the user chooses a variant, the content is actually
4667 // in a language whose code is the variant code.
4668 $variant = $wgLang->getPreferredVariant();
4669 if ( $wgLang->getCode() !== $variant ) {
4670 return Language
::factory( $variant );
4676 // @note Can't be cached persistently, depends on user settings.
4677 // @note ContentHandler::getPageViewLanguage() may need to load the
4678 // content to determine the page language!
4679 $contentHandler = ContentHandler
::getForTitle( $this );
4680 $pageLang = $contentHandler->getPageViewLanguage( $this );
4685 * Get a list of rendered edit notices for this page.
4687 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4688 * they will already be wrapped in paragraphs.
4691 * @param int $oldid Revision ID that's being edited
4694 public function getEditNotices( $oldid = 0 ) {
4697 // Optional notice for the entire namespace
4698 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4699 $msg = wfMessage( $editnotice_ns );
4700 if ( $msg->exists() ) {
4701 $html = $msg->parseAsBlock();
4702 // Edit notices may have complex logic, but output nothing (T91715)
4703 if ( trim( $html ) !== '' ) {
4704 $notices[$editnotice_ns] = Html
::rawElement(
4706 array( 'class' => array(
4708 'mw-editnotice-namespace',
4709 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4716 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4717 // Optional notice for page itself and any parent page
4718 $parts = explode( '/', $this->getDBkey() );
4719 $editnotice_base = $editnotice_ns;
4720 while ( count( $parts ) > 0 ) {
4721 $editnotice_base .= '-' . array_shift( $parts );
4722 $msg = wfMessage( $editnotice_base );
4723 if ( $msg->exists() ) {
4724 $html = $msg->parseAsBlock();
4725 if ( trim( $html ) !== '' ) {
4726 $notices[$editnotice_base] = Html
::rawElement(
4728 array( 'class' => array(
4730 'mw-editnotice-base',
4731 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4739 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4740 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4741 $msg = wfMessage( $editnoticeText );
4742 if ( $msg->exists() ) {
4743 $html = $msg->parseAsBlock();
4744 if ( trim( $html ) !== '' ) {
4745 $notices[$editnoticeText] = Html
::rawElement(
4747 array( 'class' => array(
4749 'mw-editnotice-page',
4750 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4758 Hooks
::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4765 public function __sleep() {
4773 'mDefaultNamespace',
4777 public function __wakeup() {
4778 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4779 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4780 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );