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 * @internal documentation reviewed 15 Mar 2010
36 /** @var MapCacheLRU */
37 static private $titleCache = null;
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 /** @var string Text form (spaces not underscores) of the main part */
60 public $mTextform = '';
62 /** @var string URL-encoded form of the main part */
63 public $mUrlform = '';
65 /** @var string Main part with underscores */
66 public $mDbkeyform = '';
68 /** @var string Database key with the initial letter in the case specified by the user */
69 protected $mUserCaseDBKey;
71 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
72 public $mNamespace = NS_MAIN
;
74 /** @var string Interwiki prefix */
75 public $mInterwiki = '';
77 /** @var bool Was this Title created from a string with a local interwiki prefix? */
78 private $mLocalInterwiki = false;
80 /** @var string Title fragment (i.e. the bit after the #) */
81 public $mFragment = '';
83 /** @var int Article ID, fetched from the link cache on demand */
84 public $mArticleID = -1;
86 /** @var bool|int ID of most recent revision */
87 protected $mLatestID = false;
90 * @var bool|string ID of the page's content model, i.e. one of the
91 * CONTENT_MODEL_XXX constants
93 public $mContentModel = false;
95 /** @var int Estimated number of revisions; null of not loaded */
96 private $mEstimateRevisions;
98 /** @var array Array of groups allowed to edit this article */
99 public $mRestrictions = array();
102 protected $mOldRestrictions = false;
104 /** @var bool Cascade restrictions on this page to included templates and images? */
105 public $mCascadeRestriction;
107 /** Caching the results of getCascadeProtectionSources */
108 public $mCascadingRestrictions;
110 /** @var array When do the restrictions on this page expire? */
111 protected $mRestrictionsExpiry = array();
113 /** @var bool Are cascading restrictions in effect on this page? */
114 protected $mHasCascadingRestrictions;
116 /** @var array Where are the cascading restrictions coming from on this page? */
117 public $mCascadeSources;
119 /** @var bool Boolean for initialisation on demand */
120 public $mRestrictionsLoaded = false;
122 /** @var string Text form including namespace/interwiki, initialised on demand */
123 protected $mPrefixedText = null;
125 /** @var mixed Cached value for getTitleProtection (create protection) */
126 public $mTitleProtection;
129 * @var int Namespace index when there is no namespace. Don't change the
130 * following default, NS_MAIN is hardcoded in several places. See bug 696.
131 * Zero except in {{transclusion}} tags.
133 public $mDefaultNamespace = NS_MAIN
;
136 * @var bool Is $wgUser watching this page? null if unfilled, accessed
137 * through userIsWatching()
139 protected $mWatched = null;
141 /** @var int The page length, 0 for special pages */
142 protected $mLength = -1;
144 /** @var null Is the article at this title a redirect? */
145 public $mRedirect = null;
147 /** @var array Associative array of user ID -> timestamp/false */
148 private $mNotificationTimestamp = array();
150 /** @var bool Whether a page has any subpages */
151 private $mHasSubpages;
153 /** @var bool The (string) language code of the page's language and content code. */
154 private $mPageLanguage = false;
156 /** @var string The page language code from the database */
157 private $mDbPageLanguage = null;
159 /** @var TitleValue A corresponding TitleValue object */
160 private $mTitleValue = null;
164 * B/C kludge: provide a TitleParser for use by Title.
165 * Ideally, Title would have no methods that need this.
166 * Avoid usage of this singleton by using TitleValue
167 * and the associated services when possible.
169 * @return TitleParser
171 private static function getTitleParser() {
172 global $wgContLang, $wgLocalInterwikis;
174 static $titleCodec = null;
175 static $titleCodecFingerprint = null;
177 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
178 // make sure we are using the right one. To detect changes over the course
179 // of a request, we remember a fingerprint of the config used to create the
180 // codec singleton, and re-create it if the fingerprint doesn't match.
181 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
183 if ( $fingerprint !== $titleCodecFingerprint ) {
187 if ( !$titleCodec ) {
188 $titleCodec = new MediaWikiTitleCodec(
190 GenderCache
::singleton(),
193 $titleCodecFingerprint = $fingerprint;
200 * B/C kludge: provide a TitleParser for use by Title.
201 * Ideally, Title would have no methods that need this.
202 * Avoid usage of this singleton by using TitleValue
203 * and the associated services when possible.
205 * @return TitleFormatter
207 private static function getTitleFormatter() {
208 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
209 // which implements TitleFormatter.
210 return self
::getTitleParser();
213 function __construct() {
217 * Create a new Title from a prefixed DB key
219 * @param string $key The database key, which has underscores
220 * instead of spaces, possibly including namespace and
222 * @return Title|null Title, or null on an error
224 public static function newFromDBkey( $key ) {
226 $t->mDbkeyform
= $key;
227 if ( $t->secureAndSplit() ) {
235 * Create a new Title from a TitleValue
237 * @param TitleValue $titleValue Assumed to be safe.
241 public static function newFromTitleValue( TitleValue
$titleValue ) {
242 return self
::makeTitle(
243 $titleValue->getNamespace(),
244 $titleValue->getText(),
245 $titleValue->getFragment() );
249 * Create a new Title from text, such as what one would find in a link. De-
250 * codes any HTML entities in the text.
252 * @param string $text The link text; spaces, prefixes, and an
253 * initial ':' indicating the main namespace are accepted.
254 * @param int $defaultNamespace The namespace to use if none is specified
255 * by a prefix. If you want to force a specific namespace even if
256 * $text might begin with a namespace prefix, use makeTitle() or
258 * @throws MWException
259 * @return Title|null Title or null on an error.
261 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
262 if ( is_object( $text ) ) {
263 throw new MWException( 'Title::newFromText given an object' );
266 $cache = self
::getTitleCache();
269 * Wiki pages often contain multiple links to the same page.
270 * Title normalization and parsing can become expensive on
271 * pages with many links, so we can save a little time by
274 * In theory these are value objects and won't get changed...
276 if ( $defaultNamespace == NS_MAIN
&& $cache->has( $text ) ) {
277 return $cache->get( $text );
280 # Convert things like é ā or 〗 into normalized (bug 14952) text
281 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
284 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
285 $t->mDefaultNamespace
= intval( $defaultNamespace );
287 if ( $t->secureAndSplit() ) {
288 if ( $defaultNamespace == NS_MAIN
) {
289 $cache->set( $text, $t );
298 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
300 * Example of wrong and broken code:
301 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
303 * Example of right code:
304 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
306 * Create a new Title from URL-encoded text. Ensures that
307 * the given title's length does not exceed the maximum.
309 * @param string $url The title, as might be taken from a URL
310 * @return Title|null The new object, or null on an error
312 public static function newFromURL( $url ) {
315 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
316 # but some URLs used it as a space replacement and they still come
317 # from some external search tools.
318 if ( strpos( self
::legalChars(), '+' ) === false ) {
319 $url = str_replace( '+', ' ', $url );
322 $t->mDbkeyform
= str_replace( ' ', '_', $url );
323 if ( $t->secureAndSplit() ) {
331 * @return MapCacheLRU
333 private static function getTitleCache() {
334 if ( self
::$titleCache == null ) {
335 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
337 return self
::$titleCache;
341 * Returns a list of fields that are to be selected for initializing Title
342 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
343 * whether to include page_content_model.
347 protected static function getSelectFields() {
348 global $wgContentHandlerUseDB;
351 'page_namespace', 'page_title', 'page_id',
352 'page_len', 'page_is_redirect', 'page_latest',
355 if ( $wgContentHandlerUseDB ) {
356 $fields[] = 'page_content_model';
363 * Create a new Title from an article ID
365 * @param int $id The page_id corresponding to the Title to create
366 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
367 * @return Title|null The new object, or null on an error
369 public static function newFromID( $id, $flags = 0 ) {
370 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
371 $row = $db->selectRow(
373 self
::getSelectFields(),
374 array( 'page_id' => $id ),
377 if ( $row !== false ) {
378 $title = Title
::newFromRow( $row );
386 * Make an array of titles from an array of IDs
388 * @param int[] $ids Array of IDs
389 * @return Title[] Array of Titles
391 public static function newFromIDs( $ids ) {
392 if ( !count( $ids ) ) {
395 $dbr = wfGetDB( DB_SLAVE
);
399 self
::getSelectFields(),
400 array( 'page_id' => $ids ),
405 foreach ( $res as $row ) {
406 $titles[] = Title
::newFromRow( $row );
412 * Make a Title object from a DB row
414 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
415 * @return Title Corresponding Title
417 public static function newFromRow( $row ) {
418 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
419 $t->loadFromRow( $row );
424 * Load Title object fields from a DB row.
425 * If false is given, the title will be treated as non-existing.
427 * @param stdClass|bool $row Database row
429 public function loadFromRow( $row ) {
430 if ( $row ) { // page found
431 if ( isset( $row->page_id
) ) {
432 $this->mArticleID
= (int)$row->page_id
;
434 if ( isset( $row->page_len
) ) {
435 $this->mLength
= (int)$row->page_len
;
437 if ( isset( $row->page_is_redirect
) ) {
438 $this->mRedirect
= (bool)$row->page_is_redirect
;
440 if ( isset( $row->page_latest
) ) {
441 $this->mLatestID
= (int)$row->page_latest
;
443 if ( isset( $row->page_content_model
) ) {
444 $this->mContentModel
= strval( $row->page_content_model
);
446 $this->mContentModel
= false; # initialized lazily in getContentModel()
448 if ( isset( $row->page_lang
) ) {
449 $this->mDbPageLanguage
= (string)$row->page_lang
;
451 } else { // page not found
452 $this->mArticleID
= 0;
454 $this->mRedirect
= false;
455 $this->mLatestID
= 0;
456 $this->mContentModel
= false; # initialized lazily in getContentModel()
461 * Create a new Title from a namespace index and a DB key.
462 * It's assumed that $ns and $title are *valid*, for instance when
463 * they came directly from the database or a special page name.
464 * For convenience, spaces are converted to underscores so that
465 * eg user_text fields can be used directly.
467 * @param int $ns The namespace of the article
468 * @param string $title The unprefixed database key form
469 * @param string $fragment The link fragment (after the "#")
470 * @param string $interwiki The interwiki prefix
471 * @return Title The new object
473 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
475 $t->mInterwiki
= $interwiki;
476 $t->mFragment
= $fragment;
477 $t->mNamespace
= $ns = intval( $ns );
478 $t->mDbkeyform
= str_replace( ' ', '_', $title );
479 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
480 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
481 $t->mTextform
= str_replace( '_', ' ', $title );
482 $t->mContentModel
= false; # initialized lazily in getContentModel()
487 * Create a new Title from a namespace index and a DB key.
488 * The parameters will be checked for validity, which is a bit slower
489 * than makeTitle() but safer for user-provided data.
491 * @param int $ns The namespace of the article
492 * @param string $title Database key form
493 * @param string $fragment The link fragment (after the "#")
494 * @param string $interwiki Interwiki prefix
495 * @return Title The new object, or null on an error
497 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
498 if ( !MWNamespace
::exists( $ns ) ) {
503 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
504 if ( $t->secureAndSplit() ) {
512 * Create a new Title for the Main Page
514 * @return Title The new object
516 public static function newMainPage() {
517 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
518 // Don't give fatal errors if the message is broken
520 $title = Title
::newFromText( 'Main Page' );
526 * Extract a redirect destination from a string and return the
527 * Title, or null if the text doesn't contain a valid redirect
528 * This will only return the very next target, useful for
529 * the redirect table and other checks that don't need full recursion
531 * @param string $text Text with possible redirect
532 * @return Title The corresponding Title
533 * @deprecated since 1.21, use Content::getRedirectTarget instead.
535 public static function newFromRedirect( $text ) {
536 ContentHandler
::deprecated( __METHOD__
, '1.21' );
538 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
539 return $content->getRedirectTarget();
543 * Extract a redirect destination from a string and return the
544 * Title, or null if the text doesn't contain a valid redirect
545 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
546 * in order to provide (hopefully) the Title of the final destination instead of another redirect
548 * @param string $text Text with possible redirect
550 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
552 public static function newFromRedirectRecurse( $text ) {
553 ContentHandler
::deprecated( __METHOD__
, '1.21' );
555 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
556 return $content->getUltimateRedirectTarget();
560 * Extract a redirect destination from a string and return an
561 * array of Titles, or null if the text doesn't contain a valid redirect
562 * The last element in the array is the final destination after all redirects
563 * have been resolved (up to $wgMaxRedirects times)
565 * @param string $text Text with possible redirect
566 * @return Title[] Array of Titles, with the destination last
567 * @deprecated since 1.21, use Content::getRedirectChain instead.
569 public static function newFromRedirectArray( $text ) {
570 ContentHandler
::deprecated( __METHOD__
, '1.21' );
572 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
573 return $content->getRedirectChain();
577 * Get the prefixed DB key associated with an ID
579 * @param int $id The page_id of the article
580 * @return Title|null An object representing the article, or null if no such article was found
582 public static function nameOf( $id ) {
583 $dbr = wfGetDB( DB_SLAVE
);
585 $s = $dbr->selectRow(
587 array( 'page_namespace', 'page_title' ),
588 array( 'page_id' => $id ),
591 if ( $s === false ) {
595 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
600 * Get a regex character class describing the legal characters in a link
602 * @return string The list of characters, not delimited
604 public static function legalChars() {
605 global $wgLegalTitleChars;
606 return $wgLegalTitleChars;
610 * Returns a simple regex that will match on characters and sequences invalid in titles.
611 * Note that this doesn't pick up many things that could be wrong with titles, but that
612 * replacing this regex with something valid will make many titles valid.
614 * @todo move this into MediaWikiTitleCodec
616 * @return string Regex string
618 static function getTitleInvalidRegex() {
619 static $rxTc = false;
621 # Matching titles will be held as illegal.
623 # Any character not allowed is forbidden...
624 '[^' . self
::legalChars() . ']' .
625 # URL percent encoding sequences interfere with the ability
626 # to round-trip titles -- you can't link to them consistently.
628 # XML/HTML character references produce similar issues.
629 '|&[A-Za-z0-9\x80-\xff]+;' .
631 '|&#x[0-9A-Fa-f]+;' .
639 * Utility method for converting a character sequence from bytes to Unicode.
641 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
642 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
644 * @param string $byteClass
647 public static function convertByteClassToUnicodeClass( $byteClass ) {
648 $length = strlen( $byteClass );
650 $x0 = $x1 = $x2 = '';
652 $d0 = $d1 = $d2 = '';
653 // Decoded integer codepoints
654 $ord0 = $ord1 = $ord2 = 0;
656 $r0 = $r1 = $r2 = '';
660 $allowUnicode = false;
661 for ( $pos = 0; $pos < $length; $pos++
) {
662 // Shift the queues down
671 // Load the current input token and decoded values
672 $inChar = $byteClass[$pos];
673 if ( $inChar == '\\' ) {
674 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
675 $x0 = $inChar . $m[0];
676 $d0 = chr( hexdec( $m[1] ) );
677 $pos +
= strlen( $m[0] );
678 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
679 $x0 = $inChar . $m[0];
680 $d0 = chr( octdec( $m[0] ) );
681 $pos +
= strlen( $m[0] );
682 } elseif ( $pos +
1 >= $length ) {
685 $d0 = $byteClass[$pos +
1];
693 // Load the current re-encoded value
694 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
695 $r0 = sprintf( '\x%02x', $ord0 );
696 } elseif ( $ord0 >= 0x80 ) {
697 // Allow unicode if a single high-bit character appears
698 $r0 = sprintf( '\x%02x', $ord0 );
699 $allowUnicode = true;
700 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
706 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
708 if ( $ord2 > $ord0 ) {
710 } elseif ( $ord0 >= 0x80 ) {
712 $allowUnicode = true;
713 if ( $ord2 < 0x80 ) {
714 // Keep the non-unicode section of the range
721 // Reset state to the initial value
722 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
723 } elseif ( $ord2 < 0x80 ) {
728 if ( $ord1 < 0x80 ) {
731 if ( $ord0 < 0x80 ) {
734 if ( $allowUnicode ) {
735 $out .= '\u0080-\uFFFF';
741 * Make a prefixed DB key from a DB key and a namespace index
743 * @param int $ns Numerical representation of the namespace
744 * @param string $title The DB key form the title
745 * @param string $fragment The link fragment (after the "#")
746 * @param string $interwiki The interwiki prefix
747 * @return string The prefixed form of the title
749 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
752 $namespace = $wgContLang->getNsText( $ns );
753 $name = $namespace == '' ?
$title : "$namespace:$title";
754 if ( strval( $interwiki ) != '' ) {
755 $name = "$interwiki:$name";
757 if ( strval( $fragment ) != '' ) {
758 $name .= '#' . $fragment;
764 * Escape a text fragment, say from a link, for a URL
766 * @param string $fragment Containing a URL or link fragment (after the "#")
767 * @return string Escaped string
769 static function escapeFragmentForURL( $fragment ) {
770 # Note that we don't urlencode the fragment. urlencoded Unicode
771 # fragments appear not to work in IE (at least up to 7) or in at least
772 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
773 # to care if they aren't encoded.
774 return Sanitizer
::escapeId( $fragment, 'noninitial' );
778 * Callback for usort() to do title sorts by (namespace, title)
783 * @return int Result of string comparison, or namespace comparison
785 public static function compare( $a, $b ) {
786 if ( $a->getNamespace() == $b->getNamespace() ) {
787 return strcmp( $a->getText(), $b->getText() );
789 return $a->getNamespace() - $b->getNamespace();
794 * Determine whether the object refers to a page within
797 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
799 public function isLocal() {
800 if ( $this->isExternal() ) {
801 $iw = Interwiki
::fetch( $this->mInterwiki
);
803 return $iw->isLocal();
810 * Is this Title interwiki?
814 public function isExternal() {
815 return $this->mInterwiki
!== '';
819 * Get the interwiki prefix
821 * Use Title::isExternal to check if a interwiki is set
823 * @return string Interwiki prefix
825 public function getInterwiki() {
826 return $this->mInterwiki
;
830 * Was this a local interwiki link?
834 public function wasLocalInterwiki() {
835 return $this->mLocalInterwiki
;
839 * Determine whether the object refers to a page within
840 * this project and is transcludable.
842 * @return bool True if this is transcludable
844 public function isTrans() {
845 if ( !$this->isExternal() ) {
849 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
853 * Returns the DB name of the distant wiki which owns the object.
855 * @return string The DB name
857 public function getTransWikiID() {
858 if ( !$this->isExternal() ) {
862 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
866 * Get a TitleValue object representing this Title.
868 * @note Not all valid Titles have a corresponding valid TitleValue
869 * (e.g. TitleValues cannot represent page-local links that have a
870 * fragment but no title text).
872 * @return TitleValue|null
874 public function getTitleValue() {
875 if ( $this->mTitleValue
=== null ) {
877 $this->mTitleValue
= new TitleValue(
878 $this->getNamespace(),
880 $this->getFragment() );
881 } catch ( InvalidArgumentException
$ex ) {
882 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
883 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
887 return $this->mTitleValue
;
891 * Get the text form (spaces not underscores) of the main part
893 * @return string Main part of the title
895 public function getText() {
896 return $this->mTextform
;
900 * Get the URL-encoded form of the main part
902 * @return string Main part of the title, URL-encoded
904 public function getPartialURL() {
905 return $this->mUrlform
;
909 * Get the main part with underscores
911 * @return string Main part of the title, with underscores
913 public function getDBkey() {
914 return $this->mDbkeyform
;
918 * Get the DB key with the initial letter case as specified by the user
920 * @return string DB key
922 function getUserCaseDBKey() {
923 if ( !is_null( $this->mUserCaseDBKey
) ) {
924 return $this->mUserCaseDBKey
;
926 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
927 return $this->mDbkeyform
;
932 * Get the namespace index, i.e. one of the NS_xxxx constants.
934 * @return int Namespace index
936 public function getNamespace() {
937 return $this->mNamespace
;
941 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
943 * @throws MWException
944 * @return string Content model id
946 public function getContentModel() {
947 if ( !$this->mContentModel
) {
948 $linkCache = LinkCache
::singleton();
949 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
952 if ( !$this->mContentModel
) {
953 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
956 if ( !$this->mContentModel
) {
957 throw new MWException( 'Failed to determine content model!' );
960 return $this->mContentModel
;
964 * Convenience method for checking a title's content model name
966 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
967 * @return bool True if $this->getContentModel() == $id
969 public function hasContentModel( $id ) {
970 return $this->getContentModel() == $id;
974 * Get the namespace text
976 * @return string Namespace text
978 public function getNsText() {
979 if ( $this->isExternal() ) {
980 // This probably shouldn't even happen. ohh man, oh yuck.
981 // But for interwiki transclusion it sometimes does.
982 // Shit. Shit shit shit.
984 // Use the canonical namespaces if possible to try to
985 // resolve a foreign namespace.
986 if ( MWNamespace
::exists( $this->mNamespace
) ) {
987 return MWNamespace
::getCanonicalName( $this->mNamespace
);
992 $formatter = self
::getTitleFormatter();
993 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
994 } catch ( InvalidArgumentException
$ex ) {
995 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1001 * Get the namespace text of the subject (rather than talk) page
1003 * @return string Namespace text
1005 public function getSubjectNsText() {
1007 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1011 * Get the namespace text of the talk page
1013 * @return string Namespace text
1015 public function getTalkNsText() {
1017 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1021 * Could this title have a corresponding talk page?
1025 public function canTalk() {
1026 return MWNamespace
::canTalk( $this->mNamespace
);
1030 * Is this in a namespace that allows actual pages?
1033 * @internal note -- uses hardcoded namespace index instead of constants
1035 public function canExist() {
1036 return $this->mNamespace
>= NS_MAIN
;
1040 * Can this title be added to a user's watchlist?
1044 public function isWatchable() {
1045 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1049 * Returns true if this is a special page.
1053 public function isSpecialPage() {
1054 return $this->getNamespace() == NS_SPECIAL
;
1058 * Returns true if this title resolves to the named special page
1060 * @param string $name The special page name
1063 public function isSpecial( $name ) {
1064 if ( $this->isSpecialPage() ) {
1065 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1066 if ( $name == $thisName ) {
1074 * If the Title refers to a special page alias which is not the local default, resolve
1075 * the alias, and localise the name as necessary. Otherwise, return $this
1079 public function fixSpecialName() {
1080 if ( $this->isSpecialPage() ) {
1081 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1082 if ( $canonicalName ) {
1083 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1084 if ( $localName != $this->mDbkeyform
) {
1085 return Title
::makeTitle( NS_SPECIAL
, $localName );
1093 * Returns true if the title is inside the specified namespace.
1095 * Please make use of this instead of comparing to getNamespace()
1096 * This function is much more resistant to changes we may make
1097 * to namespaces than code that makes direct comparisons.
1098 * @param int $ns The namespace
1102 public function inNamespace( $ns ) {
1103 return MWNamespace
::equals( $this->getNamespace(), $ns );
1107 * Returns true if the title is inside one of the specified namespaces.
1109 * @param int $namespaces,... The namespaces to check for
1113 public function inNamespaces( /* ... */ ) {
1114 $namespaces = func_get_args();
1115 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1116 $namespaces = $namespaces[0];
1119 foreach ( $namespaces as $ns ) {
1120 if ( $this->inNamespace( $ns ) ) {
1129 * Returns true if the title has the same subject namespace as the
1130 * namespace specified.
1131 * For example this method will take NS_USER and return true if namespace
1132 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1133 * as their subject namespace.
1135 * This is MUCH simpler than individually testing for equivalence
1136 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1141 public function hasSubjectNamespace( $ns ) {
1142 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1146 * Is this Title in a namespace which contains content?
1147 * In other words, is this a content page, for the purposes of calculating
1152 public function isContentPage() {
1153 return MWNamespace
::isContent( $this->getNamespace() );
1157 * Would anybody with sufficient privileges be able to move this page?
1158 * Some pages just aren't movable.
1162 public function isMovable() {
1163 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1164 // Interwiki title or immovable namespace. Hooks don't get to override here
1169 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1174 * Is this the mainpage?
1175 * @note Title::newFromText seems to be sufficiently optimized by the title
1176 * cache that we don't need to over-optimize by doing direct comparisons and
1177 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1178 * ends up reporting something differently than $title->isMainPage();
1183 public function isMainPage() {
1184 return $this->equals( Title
::newMainPage() );
1188 * Is this a subpage?
1192 public function isSubpage() {
1193 return MWNamespace
::hasSubpages( $this->mNamespace
)
1194 ?
strpos( $this->getText(), '/' ) !== false
1199 * Is this a conversion table for the LanguageConverter?
1203 public function isConversionTable() {
1204 // @todo ConversionTable should become a separate content model.
1206 return $this->getNamespace() == NS_MEDIAWIKI
&&
1207 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1211 * Does that page contain wikitext, or it is JS, CSS or whatever?
1215 public function isWikitextPage() {
1216 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1220 * Could this page contain custom CSS or JavaScript for the global UI.
1221 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1222 * or CONTENT_MODEL_JAVASCRIPT.
1224 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1227 * Note that this method should not return true for pages that contain and
1228 * show "inactive" CSS or JS.
1232 public function isCssOrJsPage() {
1233 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1234 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1235 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1237 # @note This hook is also called in ContentHandler::getDefaultModel.
1238 # It's called here again to make sure hook functions can force this
1239 # method to return true even outside the mediawiki namespace.
1241 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1243 return $isCssOrJsPage;
1247 * Is this a .css or .js subpage of a user page?
1250 public function isCssJsSubpage() {
1251 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1252 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1253 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1257 * Trim down a .css or .js subpage title to get the corresponding skin name
1259 * @return string Containing skin name from .css or .js subpage title
1261 public function getSkinFromCssJsSubpage() {
1262 $subpage = explode( '/', $this->mTextform
);
1263 $subpage = $subpage[count( $subpage ) - 1];
1264 $lastdot = strrpos( $subpage, '.' );
1265 if ( $lastdot === false ) {
1266 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1268 return substr( $subpage, 0, $lastdot );
1272 * Is this a .css subpage of a user page?
1276 public function isCssSubpage() {
1277 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1278 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1282 * Is this a .js subpage of a user page?
1286 public function isJsSubpage() {
1287 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1288 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1292 * Is this a talk page of some sort?
1296 public function isTalkPage() {
1297 return MWNamespace
::isTalk( $this->getNamespace() );
1301 * Get a Title object associated with the talk page of this article
1303 * @return Title The object for the talk page
1305 public function getTalkPage() {
1306 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1310 * Get a title object associated with the subject page of this
1313 * @return Title The object for the subject page
1315 public function getSubjectPage() {
1316 // Is this the same title?
1317 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1318 if ( $this->getNamespace() == $subjectNS ) {
1321 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1325 * Get the default namespace index, for when there is no namespace
1327 * @return int Default namespace index
1329 public function getDefaultNamespace() {
1330 return $this->mDefaultNamespace
;
1334 * Get the Title fragment (i.e.\ the bit after the #) in text form
1336 * Use Title::hasFragment to check for a fragment
1338 * @return string Title fragment
1340 public function getFragment() {
1341 return $this->mFragment
;
1345 * Check if a Title fragment is set
1350 public function hasFragment() {
1351 return $this->mFragment
!== '';
1355 * Get the fragment in URL form, including the "#" character if there is one
1356 * @return string Fragment in URL form
1358 public function getFragmentForURL() {
1359 if ( !$this->hasFragment() ) {
1362 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1367 * Set the fragment for this title. Removes the first character from the
1368 * specified fragment before setting, so it assumes you're passing it with
1371 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1372 * Still in active use privately.
1374 * @param string $fragment Text
1376 public function setFragment( $fragment ) {
1377 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1381 * Prefix some arbitrary text with the namespace or interwiki prefix
1384 * @param string $name The text
1385 * @return string The prefixed text
1387 private function prefix( $name ) {
1389 if ( $this->isExternal() ) {
1390 $p = $this->mInterwiki
. ':';
1393 if ( 0 != $this->mNamespace
) {
1394 $p .= $this->getNsText() . ':';
1400 * Get the prefixed database key form
1402 * @return string The prefixed title, with underscores and
1403 * any interwiki and namespace prefixes
1405 public function getPrefixedDBkey() {
1406 $s = $this->prefix( $this->mDbkeyform
);
1407 $s = str_replace( ' ', '_', $s );
1412 * Get the prefixed title with spaces.
1413 * This is the form usually used for display
1415 * @return string The prefixed title, with spaces
1417 public function getPrefixedText() {
1418 if ( $this->mPrefixedText
=== null ) {
1419 $s = $this->prefix( $this->mTextform
);
1420 $s = str_replace( '_', ' ', $s );
1421 $this->mPrefixedText
= $s;
1423 return $this->mPrefixedText
;
1427 * Return a string representation of this title
1429 * @return string Representation of this title
1431 public function __toString() {
1432 return $this->getPrefixedText();
1436 * Get the prefixed title with spaces, plus any fragment
1437 * (part beginning with '#')
1439 * @return string The prefixed title, with spaces and the fragment, including '#'
1441 public function getFullText() {
1442 $text = $this->getPrefixedText();
1443 if ( $this->hasFragment() ) {
1444 $text .= '#' . $this->getFragment();
1450 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1454 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1458 * @return string Root name
1461 public function getRootText() {
1462 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1463 return $this->getText();
1466 return strtok( $this->getText(), '/' );
1470 * Get the root page name title, i.e. the leftmost part before any slashes
1474 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1475 * # returns: Title{User:Foo}
1478 * @return Title Root title
1481 public function getRootTitle() {
1482 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1486 * Get the base page name without a namespace, i.e. the part before the subpage name
1490 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1491 * # returns: 'Foo/Bar'
1494 * @return string Base name
1496 public function getBaseText() {
1497 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1498 return $this->getText();
1501 $parts = explode( '/', $this->getText() );
1502 # Don't discard the real title if there's no subpage involved
1503 if ( count( $parts ) > 1 ) {
1504 unset( $parts[count( $parts ) - 1] );
1506 return implode( '/', $parts );
1510 * Get the base page name title, i.e. the part before the subpage name
1514 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1515 * # returns: Title{User:Foo/Bar}
1518 * @return Title Base title
1521 public function getBaseTitle() {
1522 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1526 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1530 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1534 * @return string Subpage name
1536 public function getSubpageText() {
1537 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1538 return $this->mTextform
;
1540 $parts = explode( '/', $this->mTextform
);
1541 return $parts[count( $parts ) - 1];
1545 * Get the title for a subpage of the current page
1549 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1550 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1553 * @param string $text The subpage name to add to the title
1554 * @return Title Subpage title
1557 public function getSubpage( $text ) {
1558 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1562 * Get a URL-encoded form of the subpage text
1564 * @return string URL-encoded subpage name
1566 public function getSubpageUrlForm() {
1567 $text = $this->getSubpageText();
1568 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1573 * Get a URL-encoded title (not an actual URL) including interwiki
1575 * @return string The URL-encoded form
1577 public function getPrefixedURL() {
1578 $s = $this->prefix( $this->mDbkeyform
);
1579 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1584 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1585 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1586 * second argument named variant. This was deprecated in favor
1587 * of passing an array of option with a "variant" key
1588 * Once $query2 is removed for good, this helper can be dropped
1589 * and the wfArrayToCgi moved to getLocalURL();
1591 * @since 1.19 (r105919)
1592 * @param array|string $query
1593 * @param bool $query2
1596 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1597 if ( $query2 !== false ) {
1598 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1599 "method called with a second parameter is deprecated. Add your " .
1600 "parameter to an array passed as the first parameter.", "1.19" );
1602 if ( is_array( $query ) ) {
1603 $query = wfArrayToCgi( $query );
1606 if ( is_string( $query2 ) ) {
1607 // $query2 is a string, we will consider this to be
1608 // a deprecated $variant argument and add it to the query
1609 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1611 $query2 = wfArrayToCgi( $query2 );
1613 // If we have $query content add a & to it first
1617 // Now append the queries together
1624 * Get a real URL referring to this title, with interwiki link and
1627 * @see self::getLocalURL for the arguments.
1629 * @param array|string $query
1630 * @param bool $query2
1631 * @param string $proto Protocol type to use in URL
1632 * @return string The URL
1634 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1635 $query = self
::fixUrlQueryArgs( $query, $query2 );
1637 # Hand off all the decisions on urls to getLocalURL
1638 $url = $this->getLocalURL( $query );
1640 # Expand the url to make it a full url. Note that getLocalURL has the
1641 # potential to output full urls for a variety of reasons, so we use
1642 # wfExpandUrl instead of simply prepending $wgServer
1643 $url = wfExpandUrl( $url, $proto );
1645 # Finally, add the fragment.
1646 $url .= $this->getFragmentForURL();
1648 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1653 * Get a URL with no fragment or server name (relative URL) from a Title object.
1654 * If this page is generated with action=render, however,
1655 * $wgServer is prepended to make an absolute URL.
1657 * @see self::getFullURL to always get an absolute URL.
1658 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1659 * valid to link, locally, to the current Title.
1660 * @see self::newFromText to produce a Title object.
1662 * @param string|array $query An optional query string,
1663 * not used for interwiki links. Can be specified as an associative array as well,
1664 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1665 * Some query patterns will trigger various shorturl path replacements.
1666 * @param array $query2 An optional secondary query array. This one MUST
1667 * be an array. If a string is passed it will be interpreted as a deprecated
1668 * variant argument and urlencoded into a variant= argument.
1669 * This second query argument will be added to the $query
1670 * The second parameter is deprecated since 1.19. Pass it as a key,value
1671 * pair in the first parameter array instead.
1673 * @return string String of the URL.
1675 public function getLocalURL( $query = '', $query2 = false ) {
1676 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1678 $query = self
::fixUrlQueryArgs( $query, $query2 );
1680 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1682 $namespace = $this->getNsText();
1683 if ( $namespace != '' ) {
1684 # Can this actually happen? Interwikis shouldn't be parsed.
1685 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1688 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1689 $url = wfAppendQuery( $url, $query );
1691 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1692 if ( $query == '' ) {
1693 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1694 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1696 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1700 if ( !empty( $wgActionPaths )
1701 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1703 $action = urldecode( $matches[2] );
1704 if ( isset( $wgActionPaths[$action] ) ) {
1705 $query = $matches[1];
1706 if ( isset( $matches[4] ) ) {
1707 $query .= $matches[4];
1709 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1710 if ( $query != '' ) {
1711 $url = wfAppendQuery( $url, $query );
1717 && $wgVariantArticlePath
1718 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1719 && $this->getPageLanguage()->hasVariants()
1720 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1722 $variant = urldecode( $matches[1] );
1723 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1724 // Only do the variant replacement if the given variant is a valid
1725 // variant for the page's language.
1726 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1727 $url = str_replace( '$1', $dbkey, $url );
1731 if ( $url === false ) {
1732 if ( $query == '-' ) {
1735 $url = "{$wgScript}?title={$dbkey}&{$query}";
1739 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1741 // @todo FIXME: This causes breakage in various places when we
1742 // actually expected a local URL and end up with dupe prefixes.
1743 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1744 $url = $wgServer . $url;
1747 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1752 * Get a URL that's the simplest URL that will be valid to link, locally,
1753 * to the current Title. It includes the fragment, but does not include
1754 * the server unless action=render is used (or the link is external). If
1755 * there's a fragment but the prefixed text is empty, we just return a link
1758 * The result obviously should not be URL-escaped, but does need to be
1759 * HTML-escaped if it's being output in HTML.
1761 * @param array $query
1762 * @param bool $query2
1763 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1764 * @see self::getLocalURL for the arguments.
1765 * @return string The URL
1767 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1768 wfProfileIn( __METHOD__
);
1769 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1770 $ret = $this->getFullURL( $query, $query2, $proto );
1771 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1772 $ret = $this->getFragmentForURL();
1774 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1776 wfProfileOut( __METHOD__
);
1781 * Get the URL form for an internal link.
1782 * - Used in various Squid-related code, in case we have a different
1783 * internal hostname for the server from the exposed one.
1785 * This uses $wgInternalServer to qualify the path, or $wgServer
1786 * if $wgInternalServer is not set. If the server variable used is
1787 * protocol-relative, the URL will be expanded to http://
1789 * @see self::getLocalURL for the arguments.
1790 * @return string The URL
1792 public function getInternalURL( $query = '', $query2 = false ) {
1793 global $wgInternalServer, $wgServer;
1794 $query = self
::fixUrlQueryArgs( $query, $query2 );
1795 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1796 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1797 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1802 * Get the URL for a canonical link, for use in things like IRC and
1803 * e-mail notifications. Uses $wgCanonicalServer and the
1804 * GetCanonicalURL hook.
1806 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1808 * @see self::getLocalURL for the arguments.
1809 * @return string The URL
1812 public function getCanonicalURL( $query = '', $query2 = false ) {
1813 $query = self
::fixUrlQueryArgs( $query, $query2 );
1814 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1815 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1820 * Get the edit URL for this Title
1822 * @return string The URL, or a null string if this is an interwiki link
1824 public function getEditURL() {
1825 if ( $this->isExternal() ) {
1828 $s = $this->getLocalURL( 'action=edit' );
1834 * Is $wgUser watching this page?
1836 * @deprecated since 1.20; use User::isWatched() instead.
1839 public function userIsWatching() {
1842 if ( is_null( $this->mWatched
) ) {
1843 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1844 $this->mWatched
= false;
1846 $this->mWatched
= $wgUser->isWatched( $this );
1849 return $this->mWatched
;
1853 * Can $user perform $action on this page?
1854 * This skips potentially expensive cascading permission checks
1855 * as well as avoids expensive error formatting
1857 * Suitable for use for nonessential UI controls in common cases, but
1858 * _not_ for functional access control.
1860 * May provide false positives, but should never provide a false negative.
1862 * @param string $action Action that permission needs to be checked for
1863 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1866 public function quickUserCan( $action, $user = null ) {
1867 return $this->userCan( $action, $user, false );
1871 * Can $user perform $action on this page?
1873 * @param string $action Action that permission needs to be checked for
1874 * @param User $user User to check (since 1.19); $wgUser will be used if not
1876 * @param bool $doExpensiveQueries Set this to false to avoid doing
1877 * unnecessary queries.
1880 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1881 if ( !$user instanceof User
) {
1886 return !count( $this->getUserPermissionsErrorsInternal(
1887 $action, $user, $doExpensiveQueries, true ) );
1891 * Can $user perform $action on this page?
1893 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1895 * @param string $action Action that permission needs to be checked for
1896 * @param User $user User to check
1897 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1898 * queries by skipping checks for cascading protections and user blocks.
1899 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1900 * whose corresponding errors may be ignored.
1901 * @return array Array of arguments to wfMessage to explain permissions problems.
1903 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1904 $ignoreErrors = array()
1906 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1908 // Remove the errors being ignored.
1909 foreach ( $errors as $index => $error ) {
1910 $error_key = is_array( $error ) ?
$error[0] : $error;
1912 if ( in_array( $error_key, $ignoreErrors ) ) {
1913 unset( $errors[$index] );
1921 * Permissions checks that fail most often, and which are easiest to test.
1923 * @param string $action The action to check
1924 * @param User $user User to check
1925 * @param array $errors List of current errors
1926 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1927 * @param bool $short Short circuit on first error
1929 * @return array List of errors
1931 private function checkQuickPermissions( $action, $user, $errors,
1932 $doExpensiveQueries, $short
1934 if ( !wfRunHooks( 'TitleQuickPermissions',
1935 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1940 if ( $action == 'create' ) {
1942 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1943 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1945 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1947 } elseif ( $action == 'move' ) {
1948 if ( !$user->isAllowed( 'move-rootuserpages' )
1949 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1950 // Show user page-specific message only if the user can move other pages
1951 $errors[] = array( 'cant-move-user-page' );
1954 // Check if user is allowed to move files if it's a file
1955 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1956 $errors[] = array( 'movenotallowedfile' );
1959 // Check if user is allowed to move category pages if it's a category page
1960 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1961 $errors[] = array( 'cant-move-category-page' );
1964 if ( !$user->isAllowed( 'move' ) ) {
1965 // User can't move anything
1966 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1967 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1968 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1969 // custom message if logged-in users without any special rights can move
1970 $errors[] = array( 'movenologintext' );
1972 $errors[] = array( 'movenotallowed' );
1975 } elseif ( $action == 'move-target' ) {
1976 if ( !$user->isAllowed( 'move' ) ) {
1977 // User can't move anything
1978 $errors[] = array( 'movenotallowed' );
1979 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1980 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1981 // Show user page-specific message only if the user can move other pages
1982 $errors[] = array( 'cant-move-to-user-page' );
1983 } elseif ( !$user->isAllowed( 'move-categorypages' )
1984 && $this->mNamespace
== NS_CATEGORY
) {
1985 // Show category page-specific message only if the user can move other pages
1986 $errors[] = array( 'cant-move-to-category-page' );
1988 } elseif ( !$user->isAllowed( $action ) ) {
1989 $errors[] = $this->missingPermissionError( $action, $short );
1996 * Add the resulting error code to the errors array
1998 * @param array $errors List of current errors
1999 * @param array $result Result of errors
2001 * @return array List of errors
2003 private function resultToError( $errors, $result ) {
2004 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2005 // A single array representing an error
2006 $errors[] = $result;
2007 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2008 // A nested array representing multiple errors
2009 $errors = array_merge( $errors, $result );
2010 } elseif ( $result !== '' && is_string( $result ) ) {
2011 // A string representing a message-id
2012 $errors[] = array( $result );
2013 } elseif ( $result === false ) {
2014 // a generic "We don't want them to do that"
2015 $errors[] = array( 'badaccess-group0' );
2021 * Check various permission hooks
2023 * @param string $action The action to check
2024 * @param User $user User to check
2025 * @param array $errors List of current errors
2026 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2027 * @param bool $short Short circuit on first error
2029 * @return array List of errors
2031 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2032 // Use getUserPermissionsErrors instead
2034 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2035 return $result ?
array() : array( array( 'badaccess-group0' ) );
2037 // Check getUserPermissionsErrors hook
2038 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2039 $errors = $this->resultToError( $errors, $result );
2041 // Check getUserPermissionsErrorsExpensive hook
2044 && !( $short && count( $errors ) > 0 )
2045 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2047 $errors = $this->resultToError( $errors, $result );
2054 * Check permissions on special pages & namespaces
2056 * @param string $action The action to check
2057 * @param User $user User to check
2058 * @param array $errors List of current errors
2059 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2060 * @param bool $short Short circuit on first error
2062 * @return array List of errors
2064 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2065 $doExpensiveQueries, $short
2067 # Only 'createaccount' can be performed on special pages,
2068 # which don't actually exist in the DB.
2069 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2070 $errors[] = array( 'ns-specialprotected' );
2073 # Check $wgNamespaceProtection for restricted namespaces
2074 if ( $this->isNamespaceProtected( $user ) ) {
2075 $ns = $this->mNamespace
== NS_MAIN ?
2076 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2077 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2078 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2085 * Check CSS/JS sub-page permissions
2087 * @param string $action The action to check
2088 * @param User $user User to check
2089 * @param array $errors List of current errors
2090 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2091 * @param bool $short Short circuit on first error
2093 * @return array List of errors
2095 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2096 # Protect css/js subpages of user pages
2097 # XXX: this might be better using restrictions
2098 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2099 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2100 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2101 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2102 $errors[] = array( 'mycustomcssprotected', $action );
2103 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2104 $errors[] = array( 'mycustomjsprotected', $action );
2107 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2108 $errors[] = array( 'customcssprotected', $action );
2109 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2110 $errors[] = array( 'customjsprotected', $action );
2119 * Check against page_restrictions table requirements on this
2120 * page. The user must possess all required rights for this
2123 * @param string $action The action to check
2124 * @param User $user User to check
2125 * @param array $errors List of current errors
2126 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2127 * @param bool $short Short circuit on first error
2129 * @return array List of errors
2131 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2132 foreach ( $this->getRestrictions( $action ) as $right ) {
2133 // Backwards compatibility, rewrite sysop -> editprotected
2134 if ( $right == 'sysop' ) {
2135 $right = 'editprotected';
2137 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2138 if ( $right == 'autoconfirmed' ) {
2139 $right = 'editsemiprotected';
2141 if ( $right == '' ) {
2144 if ( !$user->isAllowed( $right ) ) {
2145 $errors[] = array( 'protectedpagetext', $right, $action );
2146 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2147 $errors[] = array( 'protectedpagetext', 'protect', $action );
2155 * Check restrictions on cascading pages.
2157 * @param string $action The action to check
2158 * @param User $user User to check
2159 * @param array $errors List of current errors
2160 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2161 * @param bool $short Short circuit on first error
2163 * @return array List of errors
2165 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2166 $doExpensiveQueries, $short
2168 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2169 # We /could/ use the protection level on the source page, but it's
2170 # fairly ugly as we have to establish a precedence hierarchy for pages
2171 # included by multiple cascade-protected pages. So just restrict
2172 # it to people with 'protect' permission, as they could remove the
2173 # protection anyway.
2174 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2175 # Cascading protection depends on more than this page...
2176 # Several cascading protected pages may include this page...
2177 # Check each cascading level
2178 # This is only for protection restrictions, not for all actions
2179 if ( isset( $restrictions[$action] ) ) {
2180 foreach ( $restrictions[$action] as $right ) {
2181 // Backwards compatibility, rewrite sysop -> editprotected
2182 if ( $right == 'sysop' ) {
2183 $right = 'editprotected';
2185 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2186 if ( $right == 'autoconfirmed' ) {
2187 $right = 'editsemiprotected';
2189 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2191 foreach ( $cascadingSources as $page ) {
2192 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2194 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2204 * Check action permissions not already checked in checkQuickPermissions
2206 * @param string $action The action to check
2207 * @param User $user User to check
2208 * @param array $errors List of current errors
2209 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2210 * @param bool $short Short circuit on first error
2212 * @return array List of errors
2214 private function checkActionPermissions( $action, $user, $errors,
2215 $doExpensiveQueries, $short
2217 global $wgDeleteRevisionsLimit, $wgLang;
2219 if ( $action == 'protect' ) {
2220 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2221 $user, $doExpensiveQueries, true ) )
2223 // If they can't edit, they shouldn't protect.
2224 $errors[] = array( 'protect-cantedit' );
2226 } elseif ( $action == 'create' ) {
2227 $title_protection = $this->getTitleProtection();
2228 if ( $title_protection ) {
2229 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
2230 $title_protection['pt_create_perm'] = 'editprotected'; // B/C
2232 if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) {
2233 $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C
2235 if ( $title_protection['pt_create_perm'] == ''
2236 ||
!$user->isAllowed( $title_protection['pt_create_perm'] )
2240 User
::whoIs( $title_protection['pt_user'] ),
2241 $title_protection['pt_reason']
2245 } elseif ( $action == 'move' ) {
2246 // Check for immobile pages
2247 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2248 // Specific message for this case
2249 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2250 } elseif ( !$this->isMovable() ) {
2251 // Less specific message for rarer cases
2252 $errors[] = array( 'immobile-source-page' );
2254 } elseif ( $action == 'move-target' ) {
2255 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2256 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2257 } elseif ( !$this->isMovable() ) {
2258 $errors[] = array( 'immobile-target-page' );
2260 } elseif ( $action == 'delete' ) {
2261 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2262 $user, $doExpensiveQueries, true ) )
2264 // If they can't edit, they shouldn't delete.
2265 $errors[] = array( 'delete-cantedit' );
2267 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2268 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2270 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2277 * Check that the user isn't blocked from editing.
2279 * @param string $action The action to check
2280 * @param User $user User to check
2281 * @param array $errors List of current errors
2282 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2283 * @param bool $short Short circuit on first error
2285 * @return array List of errors
2287 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2288 // Account creation blocks handled at userlogin.
2289 // Unblocking handled in SpecialUnblock
2290 if ( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2294 global $wgEmailConfirmToEdit;
2296 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2297 $errors[] = array( 'confirmedittext' );
2300 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2301 // Don't block the user from editing their own talk page unless they've been
2302 // explicitly blocked from that too.
2303 } elseif ( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2304 // @todo FIXME: Pass the relevant context into this function.
2305 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2312 * Check that the user is allowed to read this page.
2314 * @param string $action The action to check
2315 * @param User $user User to check
2316 * @param array $errors List of current errors
2317 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2318 * @param bool $short Short circuit on first error
2320 * @return array List of errors
2322 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2323 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2325 $whitelisted = false;
2326 if ( User
::isEveryoneAllowed( 'read' ) ) {
2327 # Shortcut for public wikis, allows skipping quite a bit of code
2328 $whitelisted = true;
2329 } elseif ( $user->isAllowed( 'read' ) ) {
2330 # If the user is allowed to read pages, he is allowed to read all pages
2331 $whitelisted = true;
2332 } elseif ( $this->isSpecial( 'Userlogin' )
2333 ||
$this->isSpecial( 'ChangePassword' )
2334 ||
$this->isSpecial( 'PasswordReset' )
2336 # Always grant access to the login page.
2337 # Even anons need to be able to log in.
2338 $whitelisted = true;
2339 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2340 # Time to check the whitelist
2341 # Only do these checks is there's something to check against
2342 $name = $this->getPrefixedText();
2343 $dbName = $this->getPrefixedDBkey();
2345 // Check for explicit whitelisting with and without underscores
2346 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2347 $whitelisted = true;
2348 } elseif ( $this->getNamespace() == NS_MAIN
) {
2349 # Old settings might have the title prefixed with
2350 # a colon for main-namespace pages
2351 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2352 $whitelisted = true;
2354 } elseif ( $this->isSpecialPage() ) {
2355 # If it's a special page, ditch the subpage bit and check again
2356 $name = $this->getDBkey();
2357 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2359 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2360 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2361 $whitelisted = true;
2367 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2368 $name = $this->getPrefixedText();
2369 // Check for regex whitelisting
2370 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2371 if ( preg_match( $listItem, $name ) ) {
2372 $whitelisted = true;
2378 if ( !$whitelisted ) {
2379 # If the title is not whitelisted, give extensions a chance to do so...
2380 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2381 if ( !$whitelisted ) {
2382 $errors[] = $this->missingPermissionError( $action, $short );
2390 * Get a description array when the user doesn't have the right to perform
2391 * $action (i.e. when User::isAllowed() returns false)
2393 * @param string $action The action to check
2394 * @param bool $short Short circuit on first error
2395 * @return array List of errors
2397 private function missingPermissionError( $action, $short ) {
2398 // We avoid expensive display logic for quickUserCan's and such
2400 return array( 'badaccess-group0' );
2403 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2404 User
::getGroupsWithPermission( $action ) );
2406 if ( count( $groups ) ) {
2410 $wgLang->commaList( $groups ),
2414 return array( 'badaccess-group0' );
2419 * Can $user perform $action on this page? This is an internal function,
2420 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2421 * checks on wfReadOnly() and blocks)
2423 * @param string $action Action that permission needs to be checked for
2424 * @param User $user User to check
2425 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2426 * @param bool $short Set this to true to stop after the first permission error.
2427 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2429 protected function getUserPermissionsErrorsInternal( $action, $user,
2430 $doExpensiveQueries = true, $short = false
2432 wfProfileIn( __METHOD__
);
2434 # Read has special handling
2435 if ( $action == 'read' ) {
2437 'checkPermissionHooks',
2438 'checkReadPermissions',
2440 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2441 # here as it will lead to duplicate error messages. This is okay to do
2442 # since anywhere that checks for create will also check for edit, and
2443 # those checks are called for edit.
2444 } elseif ( $action == 'create' ) {
2446 'checkQuickPermissions',
2447 'checkPermissionHooks',
2448 'checkPageRestrictions',
2449 'checkCascadingSourcesRestrictions',
2450 'checkActionPermissions',
2455 'checkQuickPermissions',
2456 'checkPermissionHooks',
2457 'checkSpecialsAndNSPermissions',
2458 'checkCSSandJSPermissions',
2459 'checkPageRestrictions',
2460 'checkCascadingSourcesRestrictions',
2461 'checkActionPermissions',
2467 while ( count( $checks ) > 0 &&
2468 !( $short && count( $errors ) > 0 ) ) {
2469 $method = array_shift( $checks );
2470 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2473 wfProfileOut( __METHOD__
);
2478 * Get a filtered list of all restriction types supported by this wiki.
2479 * @param bool $exists True to get all restriction types that apply to
2480 * titles that do exist, False for all restriction types that apply to
2481 * titles that do not exist
2484 public static function getFilteredRestrictionTypes( $exists = true ) {
2485 global $wgRestrictionTypes;
2486 $types = $wgRestrictionTypes;
2488 # Remove the create restriction for existing titles
2489 $types = array_diff( $types, array( 'create' ) );
2491 # Only the create and upload restrictions apply to non-existing titles
2492 $types = array_intersect( $types, array( 'create', 'upload' ) );
2498 * Returns restriction types for the current Title
2500 * @return array Applicable restriction types
2502 public function getRestrictionTypes() {
2503 if ( $this->isSpecialPage() ) {
2507 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2509 if ( $this->getNamespace() != NS_FILE
) {
2510 # Remove the upload restriction for non-file titles
2511 $types = array_diff( $types, array( 'upload' ) );
2514 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2516 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2517 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2523 * Is this title subject to title protection?
2524 * Title protection is the one applied against creation of such title.
2526 * @return array|bool An associative array representing any existent title
2527 * protection, or false if there's none.
2529 private function getTitleProtection() {
2530 // Can't protect pages in special namespaces
2531 if ( $this->getNamespace() < 0 ) {
2535 // Can't protect pages that exist.
2536 if ( $this->exists() ) {
2540 if ( $this->mTitleProtection
=== null ) {
2541 $dbr = wfGetDB( DB_SLAVE
);
2542 $res = $dbr->select(
2544 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2545 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2549 // fetchRow returns false if there are no rows.
2550 $this->mTitleProtection
= $dbr->fetchRow( $res );
2552 return $this->mTitleProtection
;
2556 * Remove any title protection due to page existing
2558 public function deleteTitleProtection() {
2559 $dbw = wfGetDB( DB_MASTER
);
2563 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2566 $this->mTitleProtection
= false;
2570 * Is this page "semi-protected" - the *only* protection levels are listed
2571 * in $wgSemiprotectedRestrictionLevels?
2573 * @param string $action Action to check (default: edit)
2576 public function isSemiProtected( $action = 'edit' ) {
2577 global $wgSemiprotectedRestrictionLevels;
2579 $restrictions = $this->getRestrictions( $action );
2580 $semi = $wgSemiprotectedRestrictionLevels;
2581 if ( !$restrictions ||
!$semi ) {
2582 // Not protected, or all protection is full protection
2586 // Remap autoconfirmed to editsemiprotected for BC
2587 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2588 $semi[$key] = 'editsemiprotected';
2590 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2591 $restrictions[$key] = 'editsemiprotected';
2594 return !array_diff( $restrictions, $semi );
2598 * Does the title correspond to a protected article?
2600 * @param string $action The action the page is protected from,
2601 * by default checks all actions.
2604 public function isProtected( $action = '' ) {
2605 global $wgRestrictionLevels;
2607 $restrictionTypes = $this->getRestrictionTypes();
2609 # Special pages have inherent protection
2610 if ( $this->isSpecialPage() ) {
2614 # Check regular protection levels
2615 foreach ( $restrictionTypes as $type ) {
2616 if ( $action == $type ||
$action == '' ) {
2617 $r = $this->getRestrictions( $type );
2618 foreach ( $wgRestrictionLevels as $level ) {
2619 if ( in_array( $level, $r ) && $level != '' ) {
2630 * Determines if $user is unable to edit this page because it has been protected
2631 * by $wgNamespaceProtection.
2633 * @param User $user User object to check permissions
2636 public function isNamespaceProtected( User
$user ) {
2637 global $wgNamespaceProtection;
2639 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2640 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2641 if ( $right != '' && !$user->isAllowed( $right ) ) {
2650 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2652 * @return bool If the page is subject to cascading restrictions.
2654 public function isCascadeProtected() {
2655 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2656 return ( $sources > 0 );
2660 * Determines whether cascading protection sources have already been loaded from
2663 * @param bool $getPages True to check if the pages are loaded, or false to check
2664 * if the status is loaded.
2665 * @return bool Whether or not the specified information has been loaded
2668 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2669 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2673 * Cascading protection: Get the source of any cascading restrictions on this page.
2675 * @param bool $getPages Whether or not to retrieve the actual pages
2676 * that the restrictions have come from and the actual restrictions
2678 * @return array Two elements: First is an array of Title objects of the
2679 * pages from which cascading restrictions have come, false for
2680 * none, or true if such restrictions exist but $getPages was not
2681 * set. Second is an array like that returned by
2682 * Title::getAllRestrictions(), or an empty array if $getPages is
2685 public function getCascadeProtectionSources( $getPages = true ) {
2687 $pagerestrictions = array();
2689 if ( $this->mCascadeSources
!== null && $getPages ) {
2690 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2691 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2692 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2695 wfProfileIn( __METHOD__
);
2697 $dbr = wfGetDB( DB_SLAVE
);
2699 if ( $this->getNamespace() == NS_FILE
) {
2700 $tables = array( 'imagelinks', 'page_restrictions' );
2701 $where_clauses = array(
2702 'il_to' => $this->getDBkey(),
2707 $tables = array( 'templatelinks', 'page_restrictions' );
2708 $where_clauses = array(
2709 'tl_namespace' => $this->getNamespace(),
2710 'tl_title' => $this->getDBkey(),
2717 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2718 'pr_expiry', 'pr_type', 'pr_level' );
2719 $where_clauses[] = 'page_id=pr_page';
2722 $cols = array( 'pr_expiry' );
2725 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2727 $sources = $getPages ?
array() : false;
2728 $now = wfTimestampNow();
2729 $purgeExpired = false;
2731 foreach ( $res as $row ) {
2732 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2733 if ( $expiry > $now ) {
2735 $page_id = $row->pr_page
;
2736 $page_ns = $row->page_namespace
;
2737 $page_title = $row->page_title
;
2738 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2739 # Add groups needed for each restriction type if its not already there
2740 # Make sure this restriction type still exists
2742 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2743 $pagerestrictions[$row->pr_type
] = array();
2747 isset( $pagerestrictions[$row->pr_type
] )
2748 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2750 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2756 // Trigger lazy purge of expired restrictions from the db
2757 $purgeExpired = true;
2760 if ( $purgeExpired ) {
2761 Title
::purgeExpiredRestrictions();
2765 $this->mCascadeSources
= $sources;
2766 $this->mCascadingRestrictions
= $pagerestrictions;
2768 $this->mHasCascadingRestrictions
= $sources;
2771 wfProfileOut( __METHOD__
);
2772 return array( $sources, $pagerestrictions );
2776 * Accessor for mRestrictionsLoaded
2778 * @return bool Whether or not the page's restrictions have already been
2779 * loaded from the database
2782 public function areRestrictionsLoaded() {
2783 return $this->mRestrictionsLoaded
;
2787 * Accessor/initialisation for mRestrictions
2789 * @param string $action Action that permission needs to be checked for
2790 * @return array Restriction levels needed to take the action. All levels
2793 public function getRestrictions( $action ) {
2794 if ( !$this->mRestrictionsLoaded
) {
2795 $this->loadRestrictions();
2797 return isset( $this->mRestrictions
[$action] )
2798 ?
$this->mRestrictions
[$action]
2803 * Accessor/initialisation for mRestrictions
2805 * @return array Keys are actions, values are arrays as returned by
2806 * Title::getRestrictions()
2809 public function getAllRestrictions() {
2810 if ( !$this->mRestrictionsLoaded
) {
2811 $this->loadRestrictions();
2813 return $this->mRestrictions
;
2817 * Get the expiry time for the restriction against a given action
2819 * @param string $action
2820 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2821 * or not protected at all, or false if the action is not recognised.
2823 public function getRestrictionExpiry( $action ) {
2824 if ( !$this->mRestrictionsLoaded
) {
2825 $this->loadRestrictions();
2827 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2831 * Returns cascading restrictions for the current article
2835 function areRestrictionsCascading() {
2836 if ( !$this->mRestrictionsLoaded
) {
2837 $this->loadRestrictions();
2840 return $this->mCascadeRestriction
;
2844 * Loads a string into mRestrictions array
2846 * @param ResultWrapper $res Resource restrictions as an SQL result.
2847 * @param string $oldFashionedRestrictions Comma-separated list of page
2848 * restrictions from page table (pre 1.10)
2850 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2853 foreach ( $res as $row ) {
2857 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2861 * Compiles list of active page restrictions from both page table (pre 1.10)
2862 * and page_restrictions table for this existing page.
2863 * Public for usage by LiquidThreads.
2865 * @param array $rows Array of db result objects
2866 * @param string $oldFashionedRestrictions Comma-separated list of page
2867 * restrictions from page table (pre 1.10)
2869 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2871 $dbr = wfGetDB( DB_SLAVE
);
2873 $restrictionTypes = $this->getRestrictionTypes();
2875 foreach ( $restrictionTypes as $type ) {
2876 $this->mRestrictions
[$type] = array();
2877 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2880 $this->mCascadeRestriction
= false;
2882 # Backwards-compatibility: also load the restrictions from the page record (old format).
2884 if ( $oldFashionedRestrictions === null ) {
2885 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2886 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2889 if ( $oldFashionedRestrictions != '' ) {
2891 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2892 $temp = explode( '=', trim( $restrict ) );
2893 if ( count( $temp ) == 1 ) {
2894 // old old format should be treated as edit/move restriction
2895 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2896 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2898 $restriction = trim( $temp[1] );
2899 if ( $restriction != '' ) { //some old entries are empty
2900 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2905 $this->mOldRestrictions
= true;
2909 if ( count( $rows ) ) {
2910 # Current system - load second to make them override.
2911 $now = wfTimestampNow();
2912 $purgeExpired = false;
2914 # Cycle through all the restrictions.
2915 foreach ( $rows as $row ) {
2917 // Don't take care of restrictions types that aren't allowed
2918 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2922 // This code should be refactored, now that it's being used more generally,
2923 // But I don't really see any harm in leaving it in Block for now -werdna
2924 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2926 // Only apply the restrictions if they haven't expired!
2927 if ( !$expiry ||
$expiry > $now ) {
2928 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2929 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2931 $this->mCascadeRestriction |
= $row->pr_cascade
;
2933 // Trigger a lazy purge of expired restrictions
2934 $purgeExpired = true;
2938 if ( $purgeExpired ) {
2939 Title
::purgeExpiredRestrictions();
2943 $this->mRestrictionsLoaded
= true;
2947 * Load restrictions from the page_restrictions table
2949 * @param string $oldFashionedRestrictions Comma-separated list of page
2950 * restrictions from page table (pre 1.10)
2952 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2954 if ( !$this->mRestrictionsLoaded
) {
2955 if ( $this->exists() ) {
2956 $dbr = wfGetDB( DB_SLAVE
);
2958 $res = $dbr->select(
2959 'page_restrictions',
2960 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2961 array( 'pr_page' => $this->getArticleID() ),
2965 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2967 $title_protection = $this->getTitleProtection();
2969 if ( $title_protection ) {
2970 $now = wfTimestampNow();
2971 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2973 if ( !$expiry ||
$expiry > $now ) {
2974 // Apply the restrictions
2975 $this->mRestrictionsExpiry
['create'] = $expiry;
2976 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2977 } else { // Get rid of the old restrictions
2978 Title
::purgeExpiredRestrictions();
2979 $this->mTitleProtection
= false;
2982 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2984 $this->mRestrictionsLoaded
= true;
2990 * Flush the protection cache in this object and force reload from the database.
2991 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2993 public function flushRestrictions() {
2994 $this->mRestrictionsLoaded
= false;
2995 $this->mTitleProtection
= null;
2999 * Purge expired restrictions from the page_restrictions table
3001 static function purgeExpiredRestrictions() {
3002 if ( wfReadOnly() ) {
3006 $method = __METHOD__
;
3007 $dbw = wfGetDB( DB_MASTER
);
3008 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3010 'page_restrictions',
3011 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3016 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3023 * Does this have subpages? (Warning, usually requires an extra DB query.)
3027 public function hasSubpages() {
3028 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3033 # We dynamically add a member variable for the purpose of this method
3034 # alone to cache the result. There's no point in having it hanging
3035 # around uninitialized in every Title object; therefore we only add it
3036 # if needed and don't declare it statically.
3037 if ( $this->mHasSubpages
=== null ) {
3038 $this->mHasSubpages
= false;
3039 $subpages = $this->getSubpages( 1 );
3040 if ( $subpages instanceof TitleArray
) {
3041 $this->mHasSubpages
= (bool)$subpages->count();
3045 return $this->mHasSubpages
;
3049 * Get all subpages of this page.
3051 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3052 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3053 * doesn't allow subpages
3055 public function getSubpages( $limit = -1 ) {
3056 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3060 $dbr = wfGetDB( DB_SLAVE
);
3061 $conds['page_namespace'] = $this->getNamespace();
3062 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3064 if ( $limit > -1 ) {
3065 $options['LIMIT'] = $limit;
3067 $this->mSubpages
= TitleArray
::newFromResult(
3068 $dbr->select( 'page',
3069 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3075 return $this->mSubpages
;
3079 * Is there a version of this page in the deletion archive?
3081 * @return int The number of archived revisions
3083 public function isDeleted() {
3084 if ( $this->getNamespace() < 0 ) {
3087 $dbr = wfGetDB( DB_SLAVE
);
3089 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3090 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3093 if ( $this->getNamespace() == NS_FILE
) {
3094 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3095 array( 'fa_name' => $this->getDBkey() ),
3104 * Is there a version of this page in the deletion archive?
3108 public function isDeletedQuick() {
3109 if ( $this->getNamespace() < 0 ) {
3112 $dbr = wfGetDB( DB_SLAVE
);
3113 $deleted = (bool)$dbr->selectField( 'archive', '1',
3114 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3117 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3118 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3119 array( 'fa_name' => $this->getDBkey() ),
3127 * Get the article ID for this Title from the link cache,
3128 * adding it if necessary
3130 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3132 * @return int The ID
3134 public function getArticleID( $flags = 0 ) {
3135 if ( $this->getNamespace() < 0 ) {
3136 $this->mArticleID
= 0;
3137 return $this->mArticleID
;
3139 $linkCache = LinkCache
::singleton();
3140 if ( $flags & self
::GAID_FOR_UPDATE
) {
3141 $oldUpdate = $linkCache->forUpdate( true );
3142 $linkCache->clearLink( $this );
3143 $this->mArticleID
= $linkCache->addLinkObj( $this );
3144 $linkCache->forUpdate( $oldUpdate );
3146 if ( -1 == $this->mArticleID
) {
3147 $this->mArticleID
= $linkCache->addLinkObj( $this );
3150 return $this->mArticleID
;
3154 * Is this an article that is a redirect page?
3155 * Uses link cache, adding it if necessary
3157 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3160 public function isRedirect( $flags = 0 ) {
3161 if ( !is_null( $this->mRedirect
) ) {
3162 return $this->mRedirect
;
3164 # Calling getArticleID() loads the field from cache as needed
3165 if ( !$this->getArticleID( $flags ) ) {
3166 $this->mRedirect
= false;
3167 return $this->mRedirect
;
3170 $linkCache = LinkCache
::singleton();
3171 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3172 if ( $cached === null ) {
3173 # Trust LinkCache's state over our own
3174 # LinkCache is telling us that the page doesn't exist, despite there being cached
3175 # data relating to an existing page in $this->mArticleID. Updaters should clear
3176 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3177 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3178 # LinkCache to refresh its data from the master.
3179 $this->mRedirect
= false;
3180 return $this->mRedirect
;
3183 $this->mRedirect
= (bool)$cached;
3185 return $this->mRedirect
;
3189 * What is the length of this page?
3190 * Uses link cache, adding it if necessary
3192 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3195 public function getLength( $flags = 0 ) {
3196 if ( $this->mLength
!= -1 ) {
3197 return $this->mLength
;
3199 # Calling getArticleID() loads the field from cache as needed
3200 if ( !$this->getArticleID( $flags ) ) {
3202 return $this->mLength
;
3204 $linkCache = LinkCache
::singleton();
3205 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3206 if ( $cached === null ) {
3207 # Trust LinkCache's state over our own, as for isRedirect()
3209 return $this->mLength
;
3212 $this->mLength
= intval( $cached );
3214 return $this->mLength
;
3218 * What is the page_latest field for this page?
3220 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3221 * @return int Int or 0 if the page doesn't exist
3223 public function getLatestRevID( $flags = 0 ) {
3224 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3225 return intval( $this->mLatestID
);
3227 # Calling getArticleID() loads the field from cache as needed
3228 if ( !$this->getArticleID( $flags ) ) {
3229 $this->mLatestID
= 0;
3230 return $this->mLatestID
;
3232 $linkCache = LinkCache
::singleton();
3233 $linkCache->addLinkObj( $this );
3234 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3235 if ( $cached === null ) {
3236 # Trust LinkCache's state over our own, as for isRedirect()
3237 $this->mLatestID
= 0;
3238 return $this->mLatestID
;
3241 $this->mLatestID
= intval( $cached );
3243 return $this->mLatestID
;
3247 * This clears some fields in this object, and clears any associated
3248 * keys in the "bad links" section of the link cache.
3250 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3251 * loading of the new page_id. It's also called from
3252 * WikiPage::doDeleteArticleReal()
3254 * @param int $newid The new Article ID
3256 public function resetArticleID( $newid ) {
3257 $linkCache = LinkCache
::singleton();
3258 $linkCache->clearLink( $this );
3260 if ( $newid === false ) {
3261 $this->mArticleID
= -1;
3263 $this->mArticleID
= intval( $newid );
3265 $this->mRestrictionsLoaded
= false;
3266 $this->mRestrictions
= array();
3267 $this->mRedirect
= null;
3268 $this->mLength
= -1;
3269 $this->mLatestID
= false;
3270 $this->mContentModel
= false;
3271 $this->mEstimateRevisions
= null;
3272 $this->mPageLanguage
= false;
3273 $this->mDbPageLanguage
= null;
3277 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3279 * @param string $text Containing title to capitalize
3280 * @param int $ns Namespace index, defaults to NS_MAIN
3281 * @return string Containing capitalized title
3283 public static function capitalize( $text, $ns = NS_MAIN
) {
3286 if ( MWNamespace
::isCapitalized( $ns ) ) {
3287 return $wgContLang->ucfirst( $text );
3294 * Secure and split - main initialisation function for this object
3296 * Assumes that mDbkeyform has been set, and is urldecoded
3297 * and uses underscores, but not otherwise munged. This function
3298 * removes illegal characters, splits off the interwiki and
3299 * namespace prefixes, sets the other forms, and canonicalizes
3302 * @return bool True on success
3304 private function secureAndSplit() {
3306 $this->mInterwiki
= '';
3307 $this->mFragment
= '';
3308 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3310 $dbkey = $this->mDbkeyform
;
3313 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3314 // the parsing code with Title, while avoiding massive refactoring.
3315 // @todo: get rid of secureAndSplit, refactor parsing code.
3316 $parser = self
::getTitleParser();
3317 $parts = $parser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3318 } catch ( MalformedTitleException
$ex ) {
3323 $this->setFragment( '#' . $parts['fragment'] );
3324 $this->mInterwiki
= $parts['interwiki'];
3325 $this->mLocalInterwiki
= $parts['local_interwiki'];
3326 $this->mNamespace
= $parts['namespace'];
3327 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3329 $this->mDbkeyform
= $parts['dbkey'];
3330 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3331 $this->mTextform
= str_replace( '_', ' ', $this->mDbkeyform
);
3333 # We already know that some pages won't be in the database!
3334 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3335 $this->mArticleID
= 0;
3342 * Get an array of Title objects linking to this Title
3343 * Also stores the IDs in the link cache.
3345 * WARNING: do not use this function on arbitrary user-supplied titles!
3346 * On heavily-used templates it will max out the memory.
3348 * @param array $options May be FOR UPDATE
3349 * @param string $table Table name
3350 * @param string $prefix Fields prefix
3351 * @return Title[] Array of Title objects linking here
3353 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3354 if ( count( $options ) > 0 ) {
3355 $db = wfGetDB( DB_MASTER
);
3357 $db = wfGetDB( DB_SLAVE
);
3361 array( 'page', $table ),
3362 self
::getSelectFields(),
3364 "{$prefix}_from=page_id",
3365 "{$prefix}_namespace" => $this->getNamespace(),
3366 "{$prefix}_title" => $this->getDBkey() ),
3372 if ( $res->numRows() ) {
3373 $linkCache = LinkCache
::singleton();
3374 foreach ( $res as $row ) {
3375 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3377 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3378 $retVal[] = $titleObj;
3386 * Get an array of Title objects using this Title as a template
3387 * Also stores the IDs in the link cache.
3389 * WARNING: do not use this function on arbitrary user-supplied titles!
3390 * On heavily-used templates it will max out the memory.
3392 * @param array $options May be FOR UPDATE
3393 * @return Title[] Array of Title the Title objects linking here
3395 public function getTemplateLinksTo( $options = array() ) {
3396 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3400 * Get an array of Title objects linked from this Title
3401 * Also stores the IDs in the link cache.
3403 * WARNING: do not use this function on arbitrary user-supplied titles!
3404 * On heavily-used templates it will max out the memory.
3406 * @param array $options May be FOR UPDATE
3407 * @param string $table Table name
3408 * @param string $prefix Fields prefix
3409 * @return array Array of Title objects linking here
3411 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3412 global $wgContentHandlerUseDB;
3414 $id = $this->getArticleID();
3416 # If the page doesn't exist; there can't be any link from this page
3421 if ( count( $options ) > 0 ) {
3422 $db = wfGetDB( DB_MASTER
);
3424 $db = wfGetDB( DB_SLAVE
);
3427 $namespaceFiled = "{$prefix}_namespace";
3428 $titleField = "{$prefix}_title";
3439 if ( $wgContentHandlerUseDB ) {
3440 $fields[] = 'page_content_model';
3444 array( $table, 'page' ),
3446 array( "{$prefix}_from" => $id ),
3449 array( 'page' => array(
3451 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3456 if ( $res->numRows() ) {
3457 $linkCache = LinkCache
::singleton();
3458 foreach ( $res as $row ) {
3459 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3461 if ( $row->page_id
) {
3462 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3464 $linkCache->addBadLinkObj( $titleObj );
3466 $retVal[] = $titleObj;
3474 * Get an array of Title objects used on this Title as a template
3475 * Also stores the IDs in the link cache.
3477 * WARNING: do not use this function on arbitrary user-supplied titles!
3478 * On heavily-used templates it will max out the memory.
3480 * @param array $options May be FOR UPDATE
3481 * @return Title[] Array of Title the Title objects used here
3483 public function getTemplateLinksFrom( $options = array() ) {
3484 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3488 * Get an array of Title objects referring to non-existent articles linked
3491 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3492 * should use redirect table in this case).
3493 * @return Title[] Array of Title the Title objects
3495 public function getBrokenLinksFrom() {
3496 if ( $this->getArticleID() == 0 ) {
3497 # All links from article ID 0 are false positives
3501 $dbr = wfGetDB( DB_SLAVE
);
3502 $res = $dbr->select(
3503 array( 'page', 'pagelinks' ),
3504 array( 'pl_namespace', 'pl_title' ),
3506 'pl_from' => $this->getArticleID(),
3507 'page_namespace IS NULL'
3509 __METHOD__
, array(),
3513 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3519 foreach ( $res as $row ) {
3520 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3526 * Get a list of URLs to purge from the Squid cache when this
3529 * @return string[] Array of String the URLs
3531 public function getSquidURLs() {
3533 $this->getInternalURL(),
3534 $this->getInternalURL( 'action=history' )
3537 $pageLang = $this->getPageLanguage();
3538 if ( $pageLang->hasVariants() ) {
3539 $variants = $pageLang->getVariants();
3540 foreach ( $variants as $vCode ) {
3541 $urls[] = $this->getInternalURL( '', $vCode );
3545 // If we are looking at a css/js user subpage, purge the action=raw.
3546 if ( $this->isJsSubpage() ) {
3547 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3548 } elseif ( $this->isCssSubpage() ) {
3549 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3552 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3557 * Purge all applicable Squid URLs
3559 public function purgeSquid() {
3561 if ( $wgUseSquid ) {
3562 $urls = $this->getSquidURLs();
3563 $u = new SquidUpdate( $urls );
3569 * Move this page without authentication
3571 * @param Title $nt The new page Title
3572 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3574 public function moveNoAuth( &$nt ) {
3575 return $this->moveTo( $nt, false );
3579 * Check whether a given move operation would be valid.
3580 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3582 * @param Title $nt The new title
3583 * @param bool $auth Indicates whether $wgUser's permissions
3585 * @param string $reason Is the log summary of the move, used for spam checking
3586 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3588 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3589 global $wgUser, $wgContentHandlerUseDB;
3593 // Normally we'd add this to $errors, but we'll get
3594 // lots of syntax errors if $nt is not an object
3595 return array( array( 'badtitletext' ) );
3597 if ( $this->equals( $nt ) ) {
3598 $errors[] = array( 'selfmove' );
3600 if ( !$this->isMovable() ) {
3601 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3603 if ( $nt->isExternal() ) {
3604 $errors[] = array( 'immobile-target-namespace-iw' );
3606 if ( !$nt->isMovable() ) {
3607 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3610 $oldid = $this->getArticleID();
3611 $newid = $nt->getArticleID();
3613 if ( strlen( $nt->getDBkey() ) < 1 ) {
3614 $errors[] = array( 'articleexists' );
3617 ( $this->getDBkey() == '' ) ||
3619 ( $nt->getDBkey() == '' )
3621 $errors[] = array( 'badarticleerror' );
3624 // Content model checks
3625 if ( !$wgContentHandlerUseDB &&
3626 $this->getContentModel() !== $nt->getContentModel() ) {
3627 // can't move a page if that would change the page's content model
3630 ContentHandler
::getLocalizedName( $this->getContentModel() ),
3631 ContentHandler
::getLocalizedName( $nt->getContentModel() )
3635 // Image-specific checks
3636 if ( $this->getNamespace() == NS_FILE
) {
3637 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3640 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3641 $errors[] = array( 'nonfile-cannot-move-to-file' );
3645 $errors = wfMergeErrorArrays( $errors,
3646 $this->getUserPermissionsErrors( 'move', $wgUser ),
3647 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3648 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3649 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3652 $match = EditPage
::matchSummarySpamRegex( $reason );
3653 if ( $match !== false ) {
3654 // This is kind of lame, won't display nice
3655 $errors[] = array( 'spamprotectiontext' );
3659 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3660 $errors[] = array( 'hookaborted', $err );
3663 # The move is allowed only if (1) the target doesn't exist, or
3664 # (2) the target is a redirect to the source, and has no history
3665 # (so we can undo bad moves right after they're done).
3667 if ( 0 != $newid ) { # Target exists; check for validity
3668 if ( !$this->isValidMoveTarget( $nt ) ) {
3669 $errors[] = array( 'articleexists' );
3672 $tp = $nt->getTitleProtection();
3673 $right = $tp['pt_create_perm'];
3674 if ( $right == 'sysop' ) {
3675 $right = 'editprotected'; // B/C
3677 if ( $right == 'autoconfirmed' ) {
3678 $right = 'editsemiprotected'; // B/C
3680 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3681 $errors[] = array( 'cantmove-titleprotected' );
3684 if ( empty( $errors ) ) {
3691 * Check if the requested move target is a valid file move target
3692 * @param Title $nt Target title
3693 * @return array List of errors
3695 protected function validateFileMoveOperation( $nt ) {
3700 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3702 $file = wfLocalFile( $this );
3703 if ( $file->exists() ) {
3704 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3705 $errors[] = array( 'imageinvalidfilename' );
3707 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3708 $errors[] = array( 'imagetypemismatch' );
3712 if ( $nt->getNamespace() != NS_FILE
) {
3713 $errors[] = array( 'imagenocrossnamespace' );
3714 // From here we want to do checks on a file object, so if we can't
3715 // create one, we must return.
3719 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3721 $destFile = wfLocalFile( $nt );
3722 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3723 $errors[] = array( 'file-exists-sharedrepo' );
3730 * Move a title to a new location
3732 * @param Title $nt The new title
3733 * @param bool $auth Indicates whether $wgUser's permissions
3735 * @param string $reason The reason for the move
3736 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3737 * Ignored if the user doesn't have the suppressredirect right.
3738 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3740 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3742 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3743 if ( is_array( $err ) ) {
3744 // Auto-block user's IP if the account was "hard" blocked
3745 $wgUser->spreadAnyEditBlock();
3748 // Check suppressredirect permission
3749 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3750 $createRedirect = true;
3753 wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) );
3755 // If it is a file, move it first.
3756 // It is done before all other moving stuff is done because it's hard to revert.
3757 $dbw = wfGetDB( DB_MASTER
);
3758 if ( $this->getNamespace() == NS_FILE
) {
3759 $file = wfLocalFile( $this );
3760 if ( $file->exists() ) {
3761 $status = $file->move( $nt );
3762 if ( !$status->isOk() ) {
3763 return $status->getErrorsArray();
3766 // Clear RepoGroup process cache
3767 RepoGroup
::singleton()->clearCache( $this );
3768 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3771 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3772 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3773 $protected = $this->isProtected();
3775 // Do the actual move
3776 $this->moveToInternal( $nt, $reason, $createRedirect );
3778 // Refresh the sortkey for this row. Be careful to avoid resetting
3779 // cl_timestamp, which may disturb time-based lists on some sites.
3780 $prefixes = $dbw->select(
3782 array( 'cl_sortkey_prefix', 'cl_to' ),
3783 array( 'cl_from' => $pageid ),
3786 foreach ( $prefixes as $prefixRow ) {
3787 $prefix = $prefixRow->cl_sortkey_prefix
;
3788 $catTo = $prefixRow->cl_to
;
3789 $dbw->update( 'categorylinks',
3791 'cl_sortkey' => Collation
::singleton()->getSortKey(
3792 $nt->getCategorySortkey( $prefix ) ),
3793 'cl_timestamp=cl_timestamp' ),
3795 'cl_from' => $pageid,
3796 'cl_to' => $catTo ),
3801 $redirid = $this->getArticleID();
3804 # Protect the redirect title as the title used to be...
3805 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3807 'pr_page' => $redirid,
3808 'pr_type' => 'pr_type',
3809 'pr_level' => 'pr_level',
3810 'pr_cascade' => 'pr_cascade',
3811 'pr_user' => 'pr_user',
3812 'pr_expiry' => 'pr_expiry'
3814 array( 'pr_page' => $pageid ),
3818 # Update the protection log
3819 $log = new LogPage( 'protect' );
3820 $comment = wfMessage(
3822 $this->getPrefixedText(),
3823 $nt->getPrefixedText()
3824 )->inContentLanguage()->text();
3826 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3828 // @todo FIXME: $params?
3829 $logId = $log->addEntry(
3833 array( $this->getPrefixedText() ),
3837 // reread inserted pr_ids for log relation
3838 $insertedPrIds = $dbw->select(
3839 'page_restrictions',
3841 array( 'pr_page' => $redirid ),
3844 $logRelationsValues = array();
3845 foreach ( $insertedPrIds as $prid ) {
3846 $logRelationsValues[] = $prid->pr_id
;
3848 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
3851 // Update *_from_namespace fields as needed
3852 if ( $this->getNamespace() != $nt->getNamespace() ) {
3853 $dbw->update( 'pagelinks',
3854 array( 'pl_from_namespace' => $nt->getNamespace() ),
3855 array( 'pl_from' => $pageid ),
3858 $dbw->update( 'templatelinks',
3859 array( 'tl_from_namespace' => $nt->getNamespace() ),
3860 array( 'tl_from' => $pageid ),
3863 $dbw->update( 'imagelinks',
3864 array( 'il_from_namespace' => $nt->getNamespace() ),
3865 array( 'il_from' => $pageid ),
3871 $oldtitle = $this->getDBkey();
3872 $newtitle = $nt->getDBkey();
3873 $oldsnamespace = MWNamespace
::getSubject( $this->getNamespace() );
3874 $newsnamespace = MWNamespace
::getSubject( $nt->getNamespace() );
3875 if ( $oldsnamespace != $newsnamespace ||
$oldtitle != $newtitle ) {
3876 WatchedItem
::duplicateEntries( $this, $nt );
3879 $dbw->commit( __METHOD__
);
3881 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid, $reason ) );
3886 * Move page to a title which is either a redirect to the
3887 * source page or nonexistent
3889 * @param Title $nt The page to move to, which should be a redirect or nonexistent
3890 * @param string $reason The reason for the move
3891 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3892 * if the user has the suppressredirect right
3893 * @throws MWException
3895 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3896 global $wgUser, $wgContLang;
3898 if ( $nt->exists() ) {
3899 $moveOverRedirect = true;
3900 $logType = 'move_redir';
3902 $moveOverRedirect = false;
3906 if ( $createRedirect ) {
3907 if ( $this->getNamespace() == NS_CATEGORY
3908 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
3910 $redirectContent = new WikitextContent(
3911 wfMessage( 'category-move-redirect-override' )
3912 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
3914 $contentHandler = ContentHandler
::getForTitle( $this );
3915 $redirectContent = $contentHandler->makeRedirectContent( $nt,
3916 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
3919 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3921 $redirectContent = null;
3924 $logEntry = new ManualLogEntry( 'move', $logType );
3925 $logEntry->setPerformer( $wgUser );
3926 $logEntry->setTarget( $this );
3927 $logEntry->setComment( $reason );
3928 $logEntry->setParameters( array(
3929 '4::target' => $nt->getPrefixedText(),
3930 '5::noredir' => $redirectContent ?
'0': '1',
3933 $formatter = LogFormatter
::newFromEntry( $logEntry );
3934 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3935 $comment = $formatter->getPlainActionText();
3937 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3939 # Truncate for whole multibyte characters.
3940 $comment = $wgContLang->truncate( $comment, 255 );
3942 $oldid = $this->getArticleID();
3944 $dbw = wfGetDB( DB_MASTER
);
3946 $newpage = WikiPage
::factory( $nt );
3948 if ( $moveOverRedirect ) {
3949 $newid = $nt->getArticleID();
3950 $newcontent = $newpage->getContent();
3952 # Delete the old redirect. We don't save it to history since
3953 # by definition if we've got here it's rather uninteresting.
3954 # We have to remove it so that the next step doesn't trigger
3955 # a conflict on the unique namespace+title index...
3956 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3958 $newpage->doDeleteUpdates( $newid, $newcontent );
3961 # Save a null revision in the page's history notifying of the move
3962 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $wgUser );
3963 if ( !is_object( $nullRevision ) ) {
3964 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3967 $nullRevision->insertOn( $dbw );
3969 # Change the name of the target page:
3970 $dbw->update( 'page',
3972 'page_namespace' => $nt->getNamespace(),
3973 'page_title' => $nt->getDBkey(),
3975 /* WHERE */ array( 'page_id' => $oldid ),
3979 // clean up the old title before reset article id - bug 45348
3980 if ( !$redirectContent ) {
3981 WikiPage
::onArticleDelete( $this );
3984 $this->resetArticleID( 0 ); // 0 == non existing
3985 $nt->resetArticleID( $oldid );
3986 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // bug 46397
3988 $newpage->updateRevisionOn( $dbw, $nullRevision );
3990 wfRunHooks( 'NewRevisionFromEditComplete',
3991 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3993 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3995 if ( !$moveOverRedirect ) {
3996 WikiPage
::onArticleCreate( $nt );
3999 # Recreate the redirect, this time in the other direction.
4000 if ( $redirectContent ) {
4001 $redirectArticle = WikiPage
::factory( $this );
4002 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // bug 46397
4003 $newid = $redirectArticle->insertOn( $dbw );
4004 if ( $newid ) { // sanity
4005 $this->resetArticleID( $newid );
4006 $redirectRevision = new Revision( array(
4007 'title' => $this, // for determining the default content model
4009 'user_text' => $wgUser->getName(),
4010 'user' => $wgUser->getId(),
4011 'comment' => $comment,
4012 'content' => $redirectContent ) );
4013 $redirectRevision->insertOn( $dbw );
4014 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
4016 wfRunHooks( 'NewRevisionFromEditComplete',
4017 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
4019 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
4024 $logid = $logEntry->insert();
4025 $logEntry->publish( $logid );
4029 * Move this page's subpages to be subpages of $nt
4031 * @param Title $nt Move target
4032 * @param bool $auth Whether $wgUser's permissions should be checked
4033 * @param string $reason The reason for the move
4034 * @param bool $createRedirect Whether to create redirects from the old subpages to
4035 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4036 * @return array Array with old page titles as keys, and strings (new page titles) or
4037 * arrays (errors) as values, or an error array with numeric indices if no pages
4040 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
4041 global $wgMaximumMovedPages;
4042 // Check permissions
4043 if ( !$this->userCan( 'move-subpages' ) ) {
4044 return array( 'cant-move-subpages' );
4046 // Do the source and target namespaces support subpages?
4047 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4048 return array( 'namespace-nosubpages',
4049 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
4051 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4052 return array( 'namespace-nosubpages',
4053 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
4056 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4059 foreach ( $subpages as $oldSubpage ) {
4061 if ( $count > $wgMaximumMovedPages ) {
4062 $retval[$oldSubpage->getPrefixedText()] =
4063 array( 'movepage-max-pages',
4064 $wgMaximumMovedPages );
4068 // We don't know whether this function was called before
4069 // or after moving the root page, so check both
4071 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4072 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4074 // When moving a page to a subpage of itself,
4075 // don't move it twice
4078 $newPageName = preg_replace(
4079 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4080 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
4081 $oldSubpage->getDBkey() );
4082 if ( $oldSubpage->isTalkPage() ) {
4083 $newNs = $nt->getTalkPage()->getNamespace();
4085 $newNs = $nt->getSubjectPage()->getNamespace();
4087 # Bug 14385: we need makeTitleSafe because the new page names may
4088 # be longer than 255 characters.
4089 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
4091 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
4092 if ( $success === true ) {
4093 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4095 $retval[$oldSubpage->getPrefixedText()] = $success;
4102 * Checks if this page is just a one-rev redirect.
4103 * Adds lock, so don't use just for light purposes.
4107 public function isSingleRevRedirect() {
4108 global $wgContentHandlerUseDB;
4110 $dbw = wfGetDB( DB_MASTER
);
4113 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
4114 if ( $wgContentHandlerUseDB ) {
4115 $fields[] = 'page_content_model';
4118 $row = $dbw->selectRow( 'page',
4122 array( 'FOR UPDATE' )
4124 # Cache some fields we may want
4125 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4126 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4127 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4128 $this->mContentModel
= $row && isset( $row->page_content_model
)
4129 ?
strval( $row->page_content_model
)
4132 if ( !$this->mRedirect
) {
4135 # Does the article have a history?
4136 $row = $dbw->selectField( array( 'page', 'revision' ),
4138 array( 'page_namespace' => $this->getNamespace(),
4139 'page_title' => $this->getDBkey(),
4141 'page_latest != rev_id'
4144 array( 'FOR UPDATE' )
4146 # Return true if there was no history
4147 return ( $row === false );
4151 * Checks if $this can be moved to a given Title
4152 * - Selects for update, so don't call it unless you mean business
4154 * @param Title $nt The new title to check
4157 public function isValidMoveTarget( $nt ) {
4158 # Is it an existing file?
4159 if ( $nt->getNamespace() == NS_FILE
) {
4160 $file = wfLocalFile( $nt );
4161 if ( $file->exists() ) {
4162 wfDebug( __METHOD__
. ": file exists\n" );
4166 # Is it a redirect with no history?
4167 if ( !$nt->isSingleRevRedirect() ) {
4168 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4171 # Get the article text
4172 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4173 if ( !is_object( $rev ) ) {
4176 $content = $rev->getContent();
4177 # Does the redirect point to the source?
4178 # Or is it a broken self-redirect, usually caused by namespace collisions?
4179 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4181 if ( $redirTitle ) {
4182 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4183 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4184 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4190 # Fail safe (not a redirect after all. strange.)
4191 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4192 " is a redirect, but it doesn't contain a valid redirect.\n" );
4198 * Get categories to which this Title belongs and return an array of
4199 * categories' names.
4201 * @return array Array of parents in the form:
4202 * $parent => $currentarticle
4204 public function getParentCategories() {
4209 $titleKey = $this->getArticleID();
4211 if ( $titleKey === 0 ) {
4215 $dbr = wfGetDB( DB_SLAVE
);
4217 $res = $dbr->select(
4220 array( 'cl_from' => $titleKey ),
4224 if ( $res->numRows() > 0 ) {
4225 foreach ( $res as $row ) {
4226 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4227 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4234 * Get a tree of parent categories
4236 * @param array $children Array with the children in the keys, to check for circular refs
4237 * @return array Tree of parent categories
4239 public function getParentCategoryTree( $children = array() ) {
4241 $parents = $this->getParentCategories();
4244 foreach ( $parents as $parent => $current ) {
4245 if ( array_key_exists( $parent, $children ) ) {
4246 # Circular reference
4247 $stack[$parent] = array();
4249 $nt = Title
::newFromText( $parent );
4251 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
4261 * Get an associative array for selecting this title from
4264 * @return array Array suitable for the $where parameter of DB::select()
4266 public function pageCond() {
4267 if ( $this->mArticleID
> 0 ) {
4268 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4269 return array( 'page_id' => $this->mArticleID
);
4271 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4276 * Get the revision ID of the previous revision
4278 * @param int $revId Revision ID. Get the revision that was before this one.
4279 * @param int $flags Title::GAID_FOR_UPDATE
4280 * @return int|bool Old revision ID, or false if none exists
4282 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4283 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4284 $revId = $db->selectField( 'revision', 'rev_id',
4286 'rev_page' => $this->getArticleID( $flags ),
4287 'rev_id < ' . intval( $revId )
4290 array( 'ORDER BY' => 'rev_id DESC' )
4293 if ( $revId === false ) {
4296 return intval( $revId );
4301 * Get the revision ID of the next revision
4303 * @param int $revId Revision ID. Get the revision that was after this one.
4304 * @param int $flags Title::GAID_FOR_UPDATE
4305 * @return int|bool Next revision ID, or false if none exists
4307 public function getNextRevisionID( $revId, $flags = 0 ) {
4308 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4309 $revId = $db->selectField( 'revision', 'rev_id',
4311 'rev_page' => $this->getArticleID( $flags ),
4312 'rev_id > ' . intval( $revId )
4315 array( 'ORDER BY' => 'rev_id' )
4318 if ( $revId === false ) {
4321 return intval( $revId );
4326 * Get the first revision of the page
4328 * @param int $flags Title::GAID_FOR_UPDATE
4329 * @return Revision|null If page doesn't exist
4331 public function getFirstRevision( $flags = 0 ) {
4332 $pageId = $this->getArticleID( $flags );
4334 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4335 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4336 array( 'rev_page' => $pageId ),
4338 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4341 return new Revision( $row );
4348 * Get the oldest revision timestamp of this page
4350 * @param int $flags Title::GAID_FOR_UPDATE
4351 * @return string MW timestamp
4353 public function getEarliestRevTime( $flags = 0 ) {
4354 $rev = $this->getFirstRevision( $flags );
4355 return $rev ?
$rev->getTimestamp() : null;
4359 * Check if this is a new page
4363 public function isNewPage() {
4364 $dbr = wfGetDB( DB_SLAVE
);
4365 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4369 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4373 public function isBigDeletion() {
4374 global $wgDeleteRevisionsLimit;
4376 if ( !$wgDeleteRevisionsLimit ) {
4380 $revCount = $this->estimateRevisionCount();
4381 return $revCount > $wgDeleteRevisionsLimit;
4385 * Get the approximate revision count of this page.
4389 public function estimateRevisionCount() {
4390 if ( !$this->exists() ) {
4394 if ( $this->mEstimateRevisions
=== null ) {
4395 $dbr = wfGetDB( DB_SLAVE
);
4396 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4397 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4400 return $this->mEstimateRevisions
;
4404 * Get the number of revisions between the given revision.
4405 * Used for diffs and other things that really need it.
4407 * @param int|Revision $old Old revision or rev ID (first before range)
4408 * @param int|Revision $new New revision or rev ID (first after range)
4409 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4410 * @return int Number of revisions between these revisions.
4412 public function countRevisionsBetween( $old, $new, $max = null ) {
4413 if ( !( $old instanceof Revision
) ) {
4414 $old = Revision
::newFromTitle( $this, (int)$old );
4416 if ( !( $new instanceof Revision
) ) {
4417 $new = Revision
::newFromTitle( $this, (int)$new );
4419 if ( !$old ||
!$new ) {
4420 return 0; // nothing to compare
4422 $dbr = wfGetDB( DB_SLAVE
);
4424 'rev_page' => $this->getArticleID(),
4425 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4426 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4428 if ( $max !== null ) {
4429 $res = $dbr->select( 'revision', '1',
4432 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4434 return $res->numRows();
4436 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4441 * Get the authors between the given revisions or revision IDs.
4442 * Used for diffs and other things that really need it.
4446 * @param int|Revision $old Old revision or rev ID (first before range by default)
4447 * @param int|Revision $new New revision or rev ID (first after range by default)
4448 * @param int $limit Maximum number of authors
4449 * @param string|array $options (Optional): Single option, or an array of options:
4450 * 'include_old' Include $old in the range; $new is excluded.
4451 * 'include_new' Include $new in the range; $old is excluded.
4452 * 'include_both' Include both $old and $new in the range.
4453 * Unknown option values are ignored.
4454 * @return array|null Names of revision authors in the range; null if not both revisions exist
4456 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4457 if ( !( $old instanceof Revision
) ) {
4458 $old = Revision
::newFromTitle( $this, (int)$old );
4460 if ( !( $new instanceof Revision
) ) {
4461 $new = Revision
::newFromTitle( $this, (int)$new );
4463 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4464 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4465 // in the sanity check below?
4466 if ( !$old ||
!$new ) {
4467 return null; // nothing to compare
4472 $options = (array)$options;
4473 if ( in_array( 'include_old', $options ) ) {
4476 if ( in_array( 'include_new', $options ) ) {
4479 if ( in_array( 'include_both', $options ) ) {
4483 // No DB query needed if $old and $new are the same or successive revisions:
4484 if ( $old->getId() === $new->getId() ) {
4485 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
array() : array( $old->getRawUserText() );
4486 } elseif ( $old->getId() === $new->getParentId() ) {
4487 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4488 $authors[] = $old->getRawUserText();
4489 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4490 $authors[] = $new->getRawUserText();
4492 } elseif ( $old_cmp === '>=' ) {
4493 $authors[] = $old->getRawUserText();
4494 } elseif ( $new_cmp === '<=' ) {
4495 $authors[] = $new->getRawUserText();
4499 $dbr = wfGetDB( DB_SLAVE
);
4500 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4502 'rev_page' => $this->getArticleID(),
4503 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4504 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4506 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4508 foreach ( $res as $row ) {
4509 $authors[] = $row->rev_user_text
;
4515 * Get the number of authors between the given revisions or revision IDs.
4516 * Used for diffs and other things that really need it.
4518 * @param int|Revision $old Old revision or rev ID (first before range by default)
4519 * @param int|Revision $new New revision or rev ID (first after range by default)
4520 * @param int $limit Maximum number of authors
4521 * @param string|array $options (Optional): Single option, or an array of options:
4522 * 'include_old' Include $old in the range; $new is excluded.
4523 * 'include_new' Include $new in the range; $old is excluded.
4524 * 'include_both' Include both $old and $new in the range.
4525 * Unknown option values are ignored.
4526 * @return int Number of revision authors in the range; zero if not both revisions exist
4528 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4529 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4530 return $authors ?
count( $authors ) : 0;
4534 * Compare with another title.
4536 * @param Title $title
4539 public function equals( Title
$title ) {
4540 // Note: === is necessary for proper matching of number-like titles.
4541 return $this->getInterwiki() === $title->getInterwiki()
4542 && $this->getNamespace() == $title->getNamespace()
4543 && $this->getDBkey() === $title->getDBkey();
4547 * Check if this title is a subpage of another title
4549 * @param Title $title
4552 public function isSubpageOf( Title
$title ) {
4553 return $this->getInterwiki() === $title->getInterwiki()
4554 && $this->getNamespace() == $title->getNamespace()
4555 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4559 * Check if page exists. For historical reasons, this function simply
4560 * checks for the existence of the title in the page table, and will
4561 * thus return false for interwiki links, special pages and the like.
4562 * If you want to know if a title can be meaningfully viewed, you should
4563 * probably call the isKnown() method instead.
4567 public function exists() {
4568 return $this->getArticleID() != 0;
4572 * Should links to this title be shown as potentially viewable (i.e. as
4573 * "bluelinks"), even if there's no record by this title in the page
4576 * This function is semi-deprecated for public use, as well as somewhat
4577 * misleadingly named. You probably just want to call isKnown(), which
4578 * calls this function internally.
4580 * (ISSUE: Most of these checks are cheap, but the file existence check
4581 * can potentially be quite expensive. Including it here fixes a lot of
4582 * existing code, but we might want to add an optional parameter to skip
4583 * it and any other expensive checks.)
4587 public function isAlwaysKnown() {
4591 * Allows overriding default behavior for determining if a page exists.
4592 * If $isKnown is kept as null, regular checks happen. If it's
4593 * a boolean, this value is returned by the isKnown method.
4597 * @param Title $title
4598 * @param bool|null $isKnown
4600 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4602 if ( !is_null( $isKnown ) ) {
4606 if ( $this->isExternal() ) {
4607 return true; // any interwiki link might be viewable, for all we know
4610 switch ( $this->mNamespace
) {
4613 // file exists, possibly in a foreign repo
4614 return (bool)wfFindFile( $this );
4616 // valid special page
4617 return SpecialPageFactory
::exists( $this->getDBkey() );
4619 // selflink, possibly with fragment
4620 return $this->mDbkeyform
== '';
4622 // known system message
4623 return $this->hasSourceText() !== false;
4630 * Does this title refer to a page that can (or might) be meaningfully
4631 * viewed? In particular, this function may be used to determine if
4632 * links to the title should be rendered as "bluelinks" (as opposed to
4633 * "redlinks" to non-existent pages).
4634 * Adding something else to this function will cause inconsistency
4635 * since LinkHolderArray calls isAlwaysKnown() and does its own
4636 * page existence check.
4640 public function isKnown() {
4641 return $this->isAlwaysKnown() ||
$this->exists();
4645 * Does this page have source text?
4649 public function hasSourceText() {
4650 if ( $this->exists() ) {
4654 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4655 // If the page doesn't exist but is a known system message, default
4656 // message content will be displayed, same for language subpages-
4657 // Use always content language to avoid loading hundreds of languages
4658 // to get the link color.
4660 list( $name, ) = MessageCache
::singleton()->figureMessage(
4661 $wgContLang->lcfirst( $this->getText() )
4663 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4664 return $message->exists();
4671 * Get the default message text or false if the message doesn't exist
4673 * @return string|bool
4675 public function getDefaultMessageText() {
4678 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4682 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4683 $wgContLang->lcfirst( $this->getText() )
4685 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4687 if ( $message->exists() ) {
4688 return $message->plain();
4695 * Updates page_touched for this page; called from LinksUpdate.php
4697 * @return bool True if the update succeeded
4699 public function invalidateCache() {
4700 if ( wfReadOnly() ) {
4704 if ( $this->mArticleID
=== 0 ) {
4705 return true; // avoid gap locking if we know it's not there
4708 $method = __METHOD__
;
4709 $dbw = wfGetDB( DB_MASTER
);
4710 $conds = $this->pageCond();
4711 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4714 array( 'page_touched' => $dbw->timestamp() ),
4724 * Update page_touched timestamps and send squid purge messages for
4725 * pages linking to this title. May be sent to the job queue depending
4726 * on the number of links. Typically called on create and delete.
4728 public function touchLinks() {
4729 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4732 if ( $this->getNamespace() == NS_CATEGORY
) {
4733 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4739 * Get the last touched timestamp
4741 * @param DatabaseBase $db Optional db
4742 * @return string Last-touched timestamp
4744 public function getTouched( $db = null ) {
4745 if ( $db === null ) {
4746 $db = wfGetDB( DB_SLAVE
);
4748 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4753 * Get the timestamp when this page was updated since the user last saw it.
4756 * @return string|null
4758 public function getNotificationTimestamp( $user = null ) {
4759 global $wgUser, $wgShowUpdatedMarker;
4760 // Assume current user if none given
4764 // Check cache first
4765 $uid = $user->getId();
4766 // avoid isset here, as it'll return false for null entries
4767 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4768 return $this->mNotificationTimestamp
[$uid];
4770 if ( !$uid ||
!$wgShowUpdatedMarker ||
!$user->isAllowed( 'viewmywatchlist' ) ) {
4771 $this->mNotificationTimestamp
[$uid] = false;
4772 return $this->mNotificationTimestamp
[$uid];
4774 // Don't cache too much!
4775 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4776 $this->mNotificationTimestamp
= array();
4778 $dbr = wfGetDB( DB_SLAVE
);
4779 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4780 'wl_notificationtimestamp',
4782 'wl_user' => $user->getId(),
4783 'wl_namespace' => $this->getNamespace(),
4784 'wl_title' => $this->getDBkey(),
4788 return $this->mNotificationTimestamp
[$uid];
4792 * Generate strings used for xml 'id' names in monobook tabs
4794 * @param string $prepend Defaults to 'nstab-'
4795 * @return string XML 'id' name
4797 public function getNamespaceKey( $prepend = 'nstab-' ) {
4799 // Gets the subject namespace if this title
4800 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4801 // Checks if canonical namespace name exists for namespace
4802 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4803 // Uses canonical namespace name
4804 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4806 // Uses text of namespace
4807 $namespaceKey = $this->getSubjectNsText();
4809 // Makes namespace key lowercase
4810 $namespaceKey = $wgContLang->lc( $namespaceKey );
4812 if ( $namespaceKey == '' ) {
4813 $namespaceKey = 'main';
4815 // Changes file to image for backwards compatibility
4816 if ( $namespaceKey == 'file' ) {
4817 $namespaceKey = 'image';
4819 return $prepend . $namespaceKey;
4823 * Get all extant redirects to this Title
4825 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4826 * @return Title[] Array of Title redirects to this title
4828 public function getRedirectsHere( $ns = null ) {
4831 $dbr = wfGetDB( DB_SLAVE
);
4833 'rd_namespace' => $this->getNamespace(),
4834 'rd_title' => $this->getDBkey(),
4837 if ( $this->isExternal() ) {
4838 $where['rd_interwiki'] = $this->getInterwiki();
4840 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4842 if ( !is_null( $ns ) ) {
4843 $where['page_namespace'] = $ns;
4846 $res = $dbr->select(
4847 array( 'redirect', 'page' ),
4848 array( 'page_namespace', 'page_title' ),
4853 foreach ( $res as $row ) {
4854 $redirs[] = self
::newFromRow( $row );
4860 * Check if this Title is a valid redirect target
4864 public function isValidRedirectTarget() {
4865 global $wgInvalidRedirectTargets;
4867 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4868 if ( $this->isSpecial( 'Userlogout' ) ) {
4872 foreach ( $wgInvalidRedirectTargets as $target ) {
4873 if ( $this->isSpecial( $target ) ) {
4882 * Get a backlink cache object
4884 * @return BacklinkCache
4886 public function getBacklinkCache() {
4887 return BacklinkCache
::get( $this );
4891 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4895 public function canUseNoindex() {
4896 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4898 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4899 ?
$wgContentNamespaces
4900 : $wgExemptFromUserRobotsControl;
4902 return !in_array( $this->mNamespace
, $bannedNamespaces );
4907 * Returns the raw sort key to be used for categories, with the specified
4908 * prefix. This will be fed to Collation::getSortKey() to get a
4909 * binary sortkey that can be used for actual sorting.
4911 * @param string $prefix The prefix to be used, specified using
4912 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4916 public function getCategorySortkey( $prefix = '' ) {
4917 $unprefixed = $this->getText();
4919 // Anything that uses this hook should only depend
4920 // on the Title object passed in, and should probably
4921 // tell the users to run updateCollations.php --force
4922 // in order to re-sort existing category relations.
4923 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4924 if ( $prefix !== '' ) {
4925 # Separate with a line feed, so the unprefixed part is only used as
4926 # a tiebreaker when two pages have the exact same prefix.
4927 # In UCA, tab is the only character that can sort above LF
4928 # so we strip both of them from the original prefix.
4929 $prefix = strtr( $prefix, "\n\t", ' ' );
4930 return "$prefix\n$unprefixed";
4936 * Get the language in which the content of this page is written in
4937 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4938 * e.g. $wgLang (such as special pages, which are in the user language).
4943 public function getPageLanguage() {
4944 global $wgLang, $wgLanguageCode;
4945 wfProfileIn( __METHOD__
);
4946 if ( $this->isSpecialPage() ) {
4947 // special pages are in the user language
4948 wfProfileOut( __METHOD__
);
4952 // Checking if DB language is set
4953 if ( $this->mDbPageLanguage
) {
4954 wfProfileOut( __METHOD__
);
4955 return wfGetLangObj( $this->mDbPageLanguage
);
4958 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4959 // Note that this may depend on user settings, so the cache should
4960 // be only per-request.
4961 // NOTE: ContentHandler::getPageLanguage() may need to load the
4962 // content to determine the page language!
4963 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4965 $contentHandler = ContentHandler
::getForTitle( $this );
4966 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4967 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4969 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4972 wfProfileOut( __METHOD__
);
4977 * Get the language in which the content of this page is written when
4978 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4979 * e.g. $wgLang (such as special pages, which are in the user language).
4984 public function getPageViewLanguage() {
4987 if ( $this->isSpecialPage() ) {
4988 // If the user chooses a variant, the content is actually
4989 // in a language whose code is the variant code.
4990 $variant = $wgLang->getPreferredVariant();
4991 if ( $wgLang->getCode() !== $variant ) {
4992 return Language
::factory( $variant );
4998 // @note Can't be cached persistently, depends on user settings.
4999 // @note ContentHandler::getPageViewLanguage() may need to load the
5000 // content to determine the page language!
5001 $contentHandler = ContentHandler
::getForTitle( $this );
5002 $pageLang = $contentHandler->getPageViewLanguage( $this );
5007 * Get a list of rendered edit notices for this page.
5009 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5010 * they will already be wrapped in paragraphs.
5013 * @param int $oldid Revision ID that's being edited
5016 public function getEditNotices( $oldid = 0 ) {
5019 # Optional notices on a per-namespace and per-page basis
5020 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5021 $editnotice_ns_message = wfMessage( $editnotice_ns );
5022 if ( $editnotice_ns_message->exists() ) {
5023 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
5025 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5026 $parts = explode( '/', $this->getDBkey() );
5027 $editnotice_base = $editnotice_ns;
5028 while ( count( $parts ) > 0 ) {
5029 $editnotice_base .= '-' . array_shift( $parts );
5030 $editnotice_base_msg = wfMessage( $editnotice_base );
5031 if ( $editnotice_base_msg->exists() ) {
5032 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
5036 # Even if there are no subpages in namespace, we still don't want / in MW ns.
5037 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
5038 $editnoticeMsg = wfMessage( $editnoticeText );
5039 if ( $editnoticeMsg->exists() ) {
5040 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
5044 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );