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 string Title fragment (i.e. the bit after the #) */
78 public $mFragment = '';
80 /** @var int Article ID, fetched from the link cache on demand */
81 public $mArticleID = -1;
83 /** @var bool|int ID of most recent revision */
84 protected $mLatestID = false;
87 * @var bool|string ID of the page's content model, i.e. one of the
88 * CONTENT_MODEL_XXX constants
90 public $mContentModel = false;
92 /** @var int Estimated number of revisions; null of not loaded */
93 private $mEstimateRevisions;
95 /** @var array Array of groups allowed to edit this article */
96 public $mRestrictions = array();
99 protected $mOldRestrictions = false;
101 /** @var bool Cascade restrictions on this page to included templates and images? */
102 public $mCascadeRestriction;
104 /** Caching the results of getCascadeProtectionSources */
105 public $mCascadingRestrictions;
107 /** @var array When do the restrictions on this page expire? */
108 protected $mRestrictionsExpiry = array();
110 /** @var bool Are cascading restrictions in effect on this page? */
111 protected $mHasCascadingRestrictions;
113 /** @var array Where are the cascading restrictions coming from on this page? */
114 public $mCascadeSources;
116 /** @var bool Boolean for initialisation on demand */
117 public $mRestrictionsLoaded = false;
119 /** @var string Text form including namespace/interwiki, initialised on demand */
120 protected $mPrefixedText = null;
122 /** @var mixed Cached value for getTitleProtection (create protection) */
123 public $mTitleProtection;
126 * @var int Namespace index when there is no namespace. Don't change the
127 * following default, NS_MAIN is hardcoded in several places. See bug 696.
128 * Zero except in {{transclusion}} tags.
130 public $mDefaultNamespace = NS_MAIN
;
133 * @var bool Is $wgUser watching this page? null if unfilled, accessed
134 * through userIsWatching()
136 protected $mWatched = null;
138 /** @var int The page length, 0 for special pages */
139 protected $mLength = -1;
141 /** @var null Is the article at this title a redirect? */
142 public $mRedirect = null;
144 /** @var array Associative array of user ID -> timestamp/false */
145 private $mNotificationTimestamp = array();
147 /** @var bool Whether a page has any subpages */
148 private $mHasSubpages;
150 /** @var bool The (string) language code of the page's language and content code. */
151 private $mPageLanguage = false;
153 /** @var string The page language code from the database */
154 private $mDbPageLanguage = null;
156 /** @var TitleValue A corresponding TitleValue object */
157 private $mTitleValue = null;
161 * B/C kludge: provide a TitleParser for use by Title.
162 * Ideally, Title would have no methods that need this.
163 * Avoid usage of this singleton by using TitleValue
164 * and the associated services when possible.
166 * @return TitleParser
168 private static function getTitleParser() {
169 global $wgContLang, $wgLocalInterwikis;
171 static $titleCodec = null;
172 static $titleCodecFingerprint = null;
174 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
175 // make sure we are using the right one. To detect changes over the course
176 // of a request, we remember a fingerprint of the config used to create the
177 // codec singleton, and re-create it if the fingerprint doesn't match.
178 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
180 if ( $fingerprint !== $titleCodecFingerprint ) {
184 if ( !$titleCodec ) {
185 $titleCodec = new MediaWikiTitleCodec(
187 GenderCache
::singleton(),
190 $titleCodecFingerprint = $fingerprint;
197 * B/C kludge: provide a TitleParser for use by Title.
198 * Ideally, Title would have no methods that need this.
199 * Avoid usage of this singleton by using TitleValue
200 * and the associated services when possible.
202 * @return TitleFormatter
204 private static function getTitleFormatter() {
205 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
206 // which implements TitleFormatter.
207 return self
::getTitleParser();
210 function __construct() {
214 * Create a new Title from a prefixed DB key
216 * @param string $key The database key, which has underscores
217 * instead of spaces, possibly including namespace and
219 * @return Title|null Title, or null on an error
221 public static function newFromDBkey( $key ) {
223 $t->mDbkeyform
= $key;
224 if ( $t->secureAndSplit() ) {
232 * Create a new Title from a TitleValue
234 * @param TitleValue $titleValue Assumed to be safe.
238 public static function newFromTitleValue( TitleValue
$titleValue ) {
239 return self
::makeTitle(
240 $titleValue->getNamespace(),
241 $titleValue->getText(),
242 $titleValue->getFragment() );
246 * Create a new Title from text, such as what one would find in a link. De-
247 * codes any HTML entities in the text.
249 * @param string $text The link text; spaces, prefixes, and an
250 * initial ':' indicating the main namespace are accepted.
251 * @param int $defaultNamespace The namespace to use if none is specified
252 * by a prefix. If you want to force a specific namespace even if
253 * $text might begin with a namespace prefix, use makeTitle() or
255 * @throws MWException
256 * @return Title|null Title or null on an error.
258 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
259 if ( is_object( $text ) ) {
260 throw new MWException( 'Title::newFromText given an object' );
263 $cache = self
::getTitleCache();
266 * Wiki pages often contain multiple links to the same page.
267 * Title normalization and parsing can become expensive on
268 * pages with many links, so we can save a little time by
271 * In theory these are value objects and won't get changed...
273 if ( $defaultNamespace == NS_MAIN
&& $cache->has( $text ) ) {
274 return $cache->get( $text );
277 # Convert things like é ā or 〗 into normalized (bug 14952) text
278 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
281 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
282 $t->mDefaultNamespace
= intval( $defaultNamespace );
284 if ( $t->secureAndSplit() ) {
285 if ( $defaultNamespace == NS_MAIN
) {
286 $cache->set( $text, $t );
295 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
297 * Example of wrong and broken code:
298 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
300 * Example of right code:
301 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
303 * Create a new Title from URL-encoded text. Ensures that
304 * the given title's length does not exceed the maximum.
306 * @param string $url The title, as might be taken from a URL
307 * @return Title|null The new object, or null on an error
309 public static function newFromURL( $url ) {
312 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
313 # but some URLs used it as a space replacement and they still come
314 # from some external search tools.
315 if ( strpos( self
::legalChars(), '+' ) === false ) {
316 $url = str_replace( '+', ' ', $url );
319 $t->mDbkeyform
= str_replace( ' ', '_', $url );
320 if ( $t->secureAndSplit() ) {
328 * @return MapCacheLRU
330 private static function getTitleCache() {
331 if ( self
::$titleCache == null ) {
332 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
334 return self
::$titleCache;
338 * Returns a list of fields that are to be selected for initializing Title
339 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
340 * whether to include page_content_model.
344 protected static function getSelectFields() {
345 global $wgContentHandlerUseDB;
348 'page_namespace', 'page_title', 'page_id',
349 'page_len', 'page_is_redirect', 'page_latest',
352 if ( $wgContentHandlerUseDB ) {
353 $fields[] = 'page_content_model';
360 * Create a new Title from an article ID
362 * @param int $id The page_id corresponding to the Title to create
363 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
364 * @return Title|null The new object, or null on an error
366 public static function newFromID( $id, $flags = 0 ) {
367 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
368 $row = $db->selectRow(
370 self
::getSelectFields(),
371 array( 'page_id' => $id ),
374 if ( $row !== false ) {
375 $title = Title
::newFromRow( $row );
383 * Make an array of titles from an array of IDs
385 * @param int[] $ids Array of IDs
386 * @return Title[] Array of Titles
388 public static function newFromIDs( $ids ) {
389 if ( !count( $ids ) ) {
392 $dbr = wfGetDB( DB_SLAVE
);
396 self
::getSelectFields(),
397 array( 'page_id' => $ids ),
402 foreach ( $res as $row ) {
403 $titles[] = Title
::newFromRow( $row );
409 * Make a Title object from a DB row
411 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
412 * @return Title Corresponding Title
414 public static function newFromRow( $row ) {
415 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
416 $t->loadFromRow( $row );
421 * Load Title object fields from a DB row.
422 * If false is given, the title will be treated as non-existing.
424 * @param stdClass|bool $row Database row
426 public function loadFromRow( $row ) {
427 if ( $row ) { // page found
428 if ( isset( $row->page_id
) ) {
429 $this->mArticleID
= (int)$row->page_id
;
431 if ( isset( $row->page_len
) ) {
432 $this->mLength
= (int)$row->page_len
;
434 if ( isset( $row->page_is_redirect
) ) {
435 $this->mRedirect
= (bool)$row->page_is_redirect
;
437 if ( isset( $row->page_latest
) ) {
438 $this->mLatestID
= (int)$row->page_latest
;
440 if ( isset( $row->page_content_model
) ) {
441 $this->mContentModel
= strval( $row->page_content_model
);
443 $this->mContentModel
= false; # initialized lazily in getContentModel()
445 if ( isset( $row->page_lang
) ) {
446 $this->mDbPageLanguage
= (string)$row->page_lang
;
448 } else { // page not found
449 $this->mArticleID
= 0;
451 $this->mRedirect
= false;
452 $this->mLatestID
= 0;
453 $this->mContentModel
= false; # initialized lazily in getContentModel()
458 * Create a new Title from a namespace index and a DB key.
459 * It's assumed that $ns and $title are *valid*, for instance when
460 * they came directly from the database or a special page name.
461 * For convenience, spaces are converted to underscores so that
462 * eg user_text fields can be used directly.
464 * @param int $ns The namespace of the article
465 * @param string $title The unprefixed database key form
466 * @param string $fragment The link fragment (after the "#")
467 * @param string $interwiki The interwiki prefix
468 * @return Title The new object
470 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
472 $t->mInterwiki
= $interwiki;
473 $t->mFragment
= $fragment;
474 $t->mNamespace
= $ns = intval( $ns );
475 $t->mDbkeyform
= str_replace( ' ', '_', $title );
476 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
477 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
478 $t->mTextform
= str_replace( '_', ' ', $title );
479 $t->mContentModel
= false; # initialized lazily in getContentModel()
484 * Create a new Title from a namespace index and a DB key.
485 * The parameters will be checked for validity, which is a bit slower
486 * than makeTitle() but safer for user-provided data.
488 * @param int $ns The namespace of the article
489 * @param string $title Database key form
490 * @param string $fragment The link fragment (after the "#")
491 * @param string $interwiki Interwiki prefix
492 * @return Title The new object, or null on an error
494 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
495 if ( !MWNamespace
::exists( $ns ) ) {
500 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
501 if ( $t->secureAndSplit() ) {
509 * Create a new Title for the Main Page
511 * @return Title The new object
513 public static function newMainPage() {
514 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
515 // Don't give fatal errors if the message is broken
517 $title = Title
::newFromText( 'Main Page' );
523 * Extract a redirect destination from a string and return the
524 * Title, or null if the text doesn't contain a valid redirect
525 * This will only return the very next target, useful for
526 * the redirect table and other checks that don't need full recursion
528 * @param string $text Text with possible redirect
529 * @return Title The corresponding Title
530 * @deprecated since 1.21, use Content::getRedirectTarget instead.
532 public static function newFromRedirect( $text ) {
533 ContentHandler
::deprecated( __METHOD__
, '1.21' );
535 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
536 return $content->getRedirectTarget();
540 * Extract a redirect destination from a string and return the
541 * Title, or null if the text doesn't contain a valid redirect
542 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
543 * in order to provide (hopefully) the Title of the final destination instead of another redirect
545 * @param string $text Text with possible redirect
547 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
549 public static function newFromRedirectRecurse( $text ) {
550 ContentHandler
::deprecated( __METHOD__
, '1.21' );
552 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
553 return $content->getUltimateRedirectTarget();
557 * Extract a redirect destination from a string and return an
558 * array of Titles, or null if the text doesn't contain a valid redirect
559 * The last element in the array is the final destination after all redirects
560 * have been resolved (up to $wgMaxRedirects times)
562 * @param string $text Text with possible redirect
563 * @return Title[] Array of Titles, with the destination last
564 * @deprecated since 1.21, use Content::getRedirectChain instead.
566 public static function newFromRedirectArray( $text ) {
567 ContentHandler
::deprecated( __METHOD__
, '1.21' );
569 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
570 return $content->getRedirectChain();
574 * Get the prefixed DB key associated with an ID
576 * @param int $id The page_id of the article
577 * @return Title|null An object representing the article, or null if no such article was found
579 public static function nameOf( $id ) {
580 $dbr = wfGetDB( DB_SLAVE
);
582 $s = $dbr->selectRow(
584 array( 'page_namespace', 'page_title' ),
585 array( 'page_id' => $id ),
588 if ( $s === false ) {
592 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
597 * Get a regex character class describing the legal characters in a link
599 * @return string The list of characters, not delimited
601 public static function legalChars() {
602 global $wgLegalTitleChars;
603 return $wgLegalTitleChars;
607 * Returns a simple regex that will match on characters and sequences invalid in titles.
608 * Note that this doesn't pick up many things that could be wrong with titles, but that
609 * replacing this regex with something valid will make many titles valid.
611 * @todo: move this into MediaWikiTitleCodec
613 * @return string Regex string
615 static function getTitleInvalidRegex() {
616 static $rxTc = false;
618 # Matching titles will be held as illegal.
620 # Any character not allowed is forbidden...
621 '[^' . self
::legalChars() . ']' .
622 # URL percent encoding sequences interfere with the ability
623 # to round-trip titles -- you can't link to them consistently.
625 # XML/HTML character references produce similar issues.
626 '|&[A-Za-z0-9\x80-\xff]+;' .
628 '|&#x[0-9A-Fa-f]+;' .
636 * Utility method for converting a character sequence from bytes to Unicode.
638 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
639 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
641 * @param string $byteClass
644 public static function convertByteClassToUnicodeClass( $byteClass ) {
645 $length = strlen( $byteClass );
647 $x0 = $x1 = $x2 = '';
649 $d0 = $d1 = $d2 = '';
650 // Decoded integer codepoints
651 $ord0 = $ord1 = $ord2 = 0;
653 $r0 = $r1 = $r2 = '';
657 $allowUnicode = false;
658 for ( $pos = 0; $pos < $length; $pos++
) {
659 // Shift the queues down
668 // Load the current input token and decoded values
669 $inChar = $byteClass[$pos];
670 if ( $inChar == '\\' ) {
671 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
672 $x0 = $inChar . $m[0];
673 $d0 = chr( hexdec( $m[1] ) );
674 $pos +
= strlen( $m[0] );
675 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
676 $x0 = $inChar . $m[0];
677 $d0 = chr( octdec( $m[0] ) );
678 $pos +
= strlen( $m[0] );
679 } elseif ( $pos +
1 >= $length ) {
682 $d0 = $byteClass[$pos +
1];
690 // Load the current re-encoded value
691 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
692 $r0 = sprintf( '\x%02x', $ord0 );
693 } elseif ( $ord0 >= 0x80 ) {
694 // Allow unicode if a single high-bit character appears
695 $r0 = sprintf( '\x%02x', $ord0 );
696 $allowUnicode = true;
697 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
703 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
705 if ( $ord2 > $ord0 ) {
707 } elseif ( $ord0 >= 0x80 ) {
709 $allowUnicode = true;
710 if ( $ord2 < 0x80 ) {
711 // Keep the non-unicode section of the range
718 // Reset state to the initial value
719 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
720 } elseif ( $ord2 < 0x80 ) {
725 if ( $ord1 < 0x80 ) {
728 if ( $ord0 < 0x80 ) {
731 if ( $allowUnicode ) {
732 $out .= '\u0080-\uFFFF';
738 * Make a prefixed DB key from a DB key and a namespace index
740 * @param int $ns Numerical representation of the namespace
741 * @param string $title The DB key form the title
742 * @param string $fragment The link fragment (after the "#")
743 * @param string $interwiki The interwiki prefix
744 * @return string The prefixed form of the title
746 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
749 $namespace = $wgContLang->getNsText( $ns );
750 $name = $namespace == '' ?
$title : "$namespace:$title";
751 if ( strval( $interwiki ) != '' ) {
752 $name = "$interwiki:$name";
754 if ( strval( $fragment ) != '' ) {
755 $name .= '#' . $fragment;
761 * Escape a text fragment, say from a link, for a URL
763 * @param string $fragment Containing a URL or link fragment (after the "#")
764 * @return string Escaped string
766 static function escapeFragmentForURL( $fragment ) {
767 # Note that we don't urlencode the fragment. urlencoded Unicode
768 # fragments appear not to work in IE (at least up to 7) or in at least
769 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
770 # to care if they aren't encoded.
771 return Sanitizer
::escapeId( $fragment, 'noninitial' );
775 * Callback for usort() to do title sorts by (namespace, title)
780 * @return int Result of string comparison, or namespace comparison
782 public static function compare( $a, $b ) {
783 if ( $a->getNamespace() == $b->getNamespace() ) {
784 return strcmp( $a->getText(), $b->getText() );
786 return $a->getNamespace() - $b->getNamespace();
791 * Determine whether the object refers to a page within
794 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
796 public function isLocal() {
797 if ( $this->isExternal() ) {
798 $iw = Interwiki
::fetch( $this->mInterwiki
);
800 return $iw->isLocal();
807 * Is this Title interwiki?
811 public function isExternal() {
812 return $this->mInterwiki
!== '';
816 * Get the interwiki prefix
818 * Use Title::isExternal to check if a interwiki is set
820 * @return string Interwiki prefix
822 public function getInterwiki() {
823 return $this->mInterwiki
;
827 * Determine whether the object refers to a page within
828 * this project and is transcludable.
830 * @return bool True if this is transcludable
832 public function isTrans() {
833 if ( !$this->isExternal() ) {
837 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
841 * Returns the DB name of the distant wiki which owns the object.
843 * @return string The DB name
845 public function getTransWikiID() {
846 if ( !$this->isExternal() ) {
850 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
854 * Get a TitleValue object representing this Title.
856 * @note: Not all valid Titles have a corresponding valid TitleValue
857 * (e.g. TitleValues cannot represent page-local links that have a
858 * fragment but no title text).
860 * @return TitleValue|null
862 public function getTitleValue() {
863 if ( $this->mTitleValue
=== null ) {
865 $this->mTitleValue
= new TitleValue(
866 $this->getNamespace(),
868 $this->getFragment() );
869 } catch ( InvalidArgumentException
$ex ) {
870 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
871 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
875 return $this->mTitleValue
;
879 * Get the text form (spaces not underscores) of the main part
881 * @return string Main part of the title
883 public function getText() {
884 return $this->mTextform
;
888 * Get the URL-encoded form of the main part
890 * @return string Main part of the title, URL-encoded
892 public function getPartialURL() {
893 return $this->mUrlform
;
897 * Get the main part with underscores
899 * @return string Main part of the title, with underscores
901 public function getDBkey() {
902 return $this->mDbkeyform
;
906 * Get the DB key with the initial letter case as specified by the user
908 * @return string DB key
910 function getUserCaseDBKey() {
911 if ( !is_null( $this->mUserCaseDBKey
) ) {
912 return $this->mUserCaseDBKey
;
914 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
915 return $this->mDbkeyform
;
920 * Get the namespace index, i.e. one of the NS_xxxx constants.
922 * @return int Namespace index
924 public function getNamespace() {
925 return $this->mNamespace
;
929 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
931 * @throws MWException
932 * @return string Content model id
934 public function getContentModel() {
935 if ( !$this->mContentModel
) {
936 $linkCache = LinkCache
::singleton();
937 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
940 if ( !$this->mContentModel
) {
941 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
944 if ( !$this->mContentModel
) {
945 throw new MWException( 'Failed to determine content model!' );
948 return $this->mContentModel
;
952 * Convenience method for checking a title's content model name
954 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
955 * @return bool True if $this->getContentModel() == $id
957 public function hasContentModel( $id ) {
958 return $this->getContentModel() == $id;
962 * Get the namespace text
964 * @return string Namespace text
966 public function getNsText() {
967 if ( $this->isExternal() ) {
968 // This probably shouldn't even happen. ohh man, oh yuck.
969 // But for interwiki transclusion it sometimes does.
970 // Shit. Shit shit shit.
972 // Use the canonical namespaces if possible to try to
973 // resolve a foreign namespace.
974 if ( MWNamespace
::exists( $this->mNamespace
) ) {
975 return MWNamespace
::getCanonicalName( $this->mNamespace
);
980 $formatter = $this->getTitleFormatter();
981 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
982 } catch ( InvalidArgumentException
$ex ) {
983 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
989 * Get the namespace text of the subject (rather than talk) page
991 * @return string Namespace text
993 public function getSubjectNsText() {
995 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
999 * Get the namespace text of the talk page
1001 * @return string Namespace text
1003 public function getTalkNsText() {
1005 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1009 * Could this title have a corresponding talk page?
1013 public function canTalk() {
1014 return MWNamespace
::canTalk( $this->mNamespace
);
1018 * Is this in a namespace that allows actual pages?
1021 * @internal note -- uses hardcoded namespace index instead of constants
1023 public function canExist() {
1024 return $this->mNamespace
>= NS_MAIN
;
1028 * Can this title be added to a user's watchlist?
1032 public function isWatchable() {
1033 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1037 * Returns true if this is a special page.
1041 public function isSpecialPage() {
1042 return $this->getNamespace() == NS_SPECIAL
;
1046 * Returns true if this title resolves to the named special page
1048 * @param string $name The special page name
1051 public function isSpecial( $name ) {
1052 if ( $this->isSpecialPage() ) {
1053 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1054 if ( $name == $thisName ) {
1062 * If the Title refers to a special page alias which is not the local default, resolve
1063 * the alias, and localise the name as necessary. Otherwise, return $this
1067 public function fixSpecialName() {
1068 if ( $this->isSpecialPage() ) {
1069 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1070 if ( $canonicalName ) {
1071 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1072 if ( $localName != $this->mDbkeyform
) {
1073 return Title
::makeTitle( NS_SPECIAL
, $localName );
1081 * Returns true if the title is inside the specified namespace.
1083 * Please make use of this instead of comparing to getNamespace()
1084 * This function is much more resistant to changes we may make
1085 * to namespaces than code that makes direct comparisons.
1086 * @param int $ns The namespace
1090 public function inNamespace( $ns ) {
1091 return MWNamespace
::equals( $this->getNamespace(), $ns );
1095 * Returns true if the title is inside one of the specified namespaces.
1097 * @param ...$namespaces The namespaces to check for
1101 public function inNamespaces( /* ... */ ) {
1102 $namespaces = func_get_args();
1103 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1104 $namespaces = $namespaces[0];
1107 foreach ( $namespaces as $ns ) {
1108 if ( $this->inNamespace( $ns ) ) {
1117 * Returns true if the title has the same subject namespace as the
1118 * namespace specified.
1119 * For example this method will take NS_USER and return true if namespace
1120 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1121 * as their subject namespace.
1123 * This is MUCH simpler than individually testing for equivalence
1124 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1129 public function hasSubjectNamespace( $ns ) {
1130 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1134 * Is this Title in a namespace which contains content?
1135 * In other words, is this a content page, for the purposes of calculating
1140 public function isContentPage() {
1141 return MWNamespace
::isContent( $this->getNamespace() );
1145 * Would anybody with sufficient privileges be able to move this page?
1146 * Some pages just aren't movable.
1150 public function isMovable() {
1151 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1152 // Interwiki title or immovable namespace. Hooks don't get to override here
1157 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1162 * Is this the mainpage?
1163 * @note Title::newFromText seems to be sufficiently optimized by the title
1164 * cache that we don't need to over-optimize by doing direct comparisons and
1165 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1166 * ends up reporting something differently than $title->isMainPage();
1171 public function isMainPage() {
1172 return $this->equals( Title
::newMainPage() );
1176 * Is this a subpage?
1180 public function isSubpage() {
1181 return MWNamespace
::hasSubpages( $this->mNamespace
)
1182 ?
strpos( $this->getText(), '/' ) !== false
1187 * Is this a conversion table for the LanguageConverter?
1191 public function isConversionTable() {
1192 // @todo ConversionTable should become a separate content model.
1194 return $this->getNamespace() == NS_MEDIAWIKI
&&
1195 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1199 * Does that page contain wikitext, or it is JS, CSS or whatever?
1203 public function isWikitextPage() {
1204 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1208 * Could this page contain custom CSS or JavaScript for the global UI.
1209 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1210 * or CONTENT_MODEL_JAVASCRIPT.
1212 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1215 * Note that this method should not return true for pages that contain and
1216 * show "inactive" CSS or JS.
1220 public function isCssOrJsPage() {
1221 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1222 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1223 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1225 # @note This hook is also called in ContentHandler::getDefaultModel.
1226 # It's called here again to make sure hook functions can force this
1227 # method to return true even outside the mediawiki namespace.
1229 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1231 return $isCssOrJsPage;
1235 * Is this a .css or .js subpage of a user page?
1238 public function isCssJsSubpage() {
1239 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1240 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1241 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1245 * Trim down a .css or .js subpage title to get the corresponding skin name
1247 * @return string Containing skin name from .css or .js subpage title
1249 public function getSkinFromCssJsSubpage() {
1250 $subpage = explode( '/', $this->mTextform
);
1251 $subpage = $subpage[count( $subpage ) - 1];
1252 $lastdot = strrpos( $subpage, '.' );
1253 if ( $lastdot === false ) {
1254 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1256 return substr( $subpage, 0, $lastdot );
1260 * Is this a .css subpage of a user page?
1264 public function isCssSubpage() {
1265 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1266 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1270 * Is this a .js subpage of a user page?
1274 public function isJsSubpage() {
1275 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1276 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1280 * Is this a talk page of some sort?
1284 public function isTalkPage() {
1285 return MWNamespace
::isTalk( $this->getNamespace() );
1289 * Get a Title object associated with the talk page of this article
1291 * @return Title The object for the talk page
1293 public function getTalkPage() {
1294 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1298 * Get a title object associated with the subject page of this
1301 * @return Title The object for the subject page
1303 public function getSubjectPage() {
1304 // Is this the same title?
1305 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1306 if ( $this->getNamespace() == $subjectNS ) {
1309 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1313 * Get the default namespace index, for when there is no namespace
1315 * @return int Default namespace index
1317 public function getDefaultNamespace() {
1318 return $this->mDefaultNamespace
;
1322 * Get the Title fragment (i.e.\ the bit after the #) in text form
1324 * Use Title::hasFragment to check for a fragment
1326 * @return string Title fragment
1328 public function getFragment() {
1329 return $this->mFragment
;
1333 * Check if a Title fragment is set
1338 public function hasFragment() {
1339 return $this->mFragment
!== '';
1343 * Get the fragment in URL form, including the "#" character if there is one
1344 * @return string Fragment in URL form
1346 public function getFragmentForURL() {
1347 if ( !$this->hasFragment() ) {
1350 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1355 * Set the fragment for this title. Removes the first character from the
1356 * specified fragment before setting, so it assumes you're passing it with
1359 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1360 * Still in active use privately.
1362 * @param string $fragment Text
1364 public function setFragment( $fragment ) {
1365 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1369 * Prefix some arbitrary text with the namespace or interwiki prefix
1372 * @param string $name The text
1373 * @return string The prefixed text
1375 private function prefix( $name ) {
1377 if ( $this->isExternal() ) {
1378 $p = $this->mInterwiki
. ':';
1381 if ( 0 != $this->mNamespace
) {
1382 $p .= $this->getNsText() . ':';
1388 * Get the prefixed database key form
1390 * @return string The prefixed title, with underscores and
1391 * any interwiki and namespace prefixes
1393 public function getPrefixedDBkey() {
1394 $s = $this->prefix( $this->mDbkeyform
);
1395 $s = str_replace( ' ', '_', $s );
1400 * Get the prefixed title with spaces.
1401 * This is the form usually used for display
1403 * @return string The prefixed title, with spaces
1405 public function getPrefixedText() {
1406 if ( $this->mPrefixedText
=== null ) {
1407 $s = $this->prefix( $this->mTextform
);
1408 $s = str_replace( '_', ' ', $s );
1409 $this->mPrefixedText
= $s;
1411 return $this->mPrefixedText
;
1415 * Return a string representation of this title
1417 * @return string Representation of this title
1419 public function __toString() {
1420 return $this->getPrefixedText();
1424 * Get the prefixed title with spaces, plus any fragment
1425 * (part beginning with '#')
1427 * @return string The prefixed title, with spaces and the fragment, including '#'
1429 public function getFullText() {
1430 $text = $this->getPrefixedText();
1431 if ( $this->hasFragment() ) {
1432 $text .= '#' . $this->getFragment();
1438 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1442 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1446 * @return string Root name
1449 public function getRootText() {
1450 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1451 return $this->getText();
1454 return strtok( $this->getText(), '/' );
1458 * Get the root page name title, i.e. the leftmost part before any slashes
1462 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1463 * # returns: Title{User:Foo}
1466 * @return Title Root title
1469 public function getRootTitle() {
1470 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1474 * Get the base page name without a namespace, i.e. the part before the subpage name
1478 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1479 * # returns: 'Foo/Bar'
1482 * @return string Base name
1484 public function getBaseText() {
1485 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1486 return $this->getText();
1489 $parts = explode( '/', $this->getText() );
1490 # Don't discard the real title if there's no subpage involved
1491 if ( count( $parts ) > 1 ) {
1492 unset( $parts[count( $parts ) - 1] );
1494 return implode( '/', $parts );
1498 * Get the base page name title, i.e. the part before the subpage name
1502 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1503 * # returns: Title{User:Foo/Bar}
1506 * @return Title Base title
1509 public function getBaseTitle() {
1510 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1514 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1518 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1522 * @return string Subpage name
1524 public function getSubpageText() {
1525 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1526 return $this->mTextform
;
1528 $parts = explode( '/', $this->mTextform
);
1529 return $parts[count( $parts ) - 1];
1533 * Get the title for a subpage of the current page
1537 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1538 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1541 * @param string $text The subpage name to add to the title
1542 * @return Title Subpage title
1545 public function getSubpage( $text ) {
1546 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1550 * Get the HTML-escaped displayable text form.
1551 * Used for the title field in <a> tags.
1553 * @return string The text, including any prefixes
1554 * @deprecated since 1.19
1556 public function getEscapedText() {
1557 wfDeprecated( __METHOD__
, '1.19' );
1558 return htmlspecialchars( $this->getPrefixedText() );
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::newFromText to produce a Title object.
1660 * @param string|array $query an optional query string,
1661 * not used for interwiki links. Can be specified as an associative array as well,
1662 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1663 * Some query patterns will trigger various shorturl path replacements.
1664 * @param array $query2 An optional secondary query array. This one MUST
1665 * be an array. If a string is passed it will be interpreted as a deprecated
1666 * variant argument and urlencoded into a variant= argument.
1667 * This second query argument will be added to the $query
1668 * The second parameter is deprecated since 1.19. Pass it as a key,value
1669 * pair in the first parameter array instead.
1671 * @return string String of the URL.
1673 public function getLocalURL( $query = '', $query2 = false ) {
1674 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1676 $query = self
::fixUrlQueryArgs( $query, $query2 );
1678 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1680 $namespace = $this->getNsText();
1681 if ( $namespace != '' ) {
1682 # Can this actually happen? Interwikis shouldn't be parsed.
1683 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1686 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1687 $url = wfAppendQuery( $url, $query );
1689 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1690 if ( $query == '' ) {
1691 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1692 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1694 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1698 if ( !empty( $wgActionPaths )
1699 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1701 $action = urldecode( $matches[2] );
1702 if ( isset( $wgActionPaths[$action] ) ) {
1703 $query = $matches[1];
1704 if ( isset( $matches[4] ) ) {
1705 $query .= $matches[4];
1707 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1708 if ( $query != '' ) {
1709 $url = wfAppendQuery( $url, $query );
1715 && $wgVariantArticlePath
1716 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1717 && $this->getPageLanguage()->hasVariants()
1718 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1720 $variant = urldecode( $matches[1] );
1721 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1722 // Only do the variant replacement if the given variant is a valid
1723 // variant for the page's language.
1724 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1725 $url = str_replace( '$1', $dbkey, $url );
1729 if ( $url === false ) {
1730 if ( $query == '-' ) {
1733 $url = "{$wgScript}?title={$dbkey}&{$query}";
1737 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1739 // @todo FIXME: This causes breakage in various places when we
1740 // actually expected a local URL and end up with dupe prefixes.
1741 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1742 $url = $wgServer . $url;
1745 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1750 * Get a URL that's the simplest URL that will be valid to link, locally,
1751 * to the current Title. It includes the fragment, but does not include
1752 * the server unless action=render is used (or the link is external). If
1753 * there's a fragment but the prefixed text is empty, we just return a link
1756 * The result obviously should not be URL-escaped, but does need to be
1757 * HTML-escaped if it's being output in HTML.
1759 * @param array $query
1760 * @param bool $query2
1761 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1762 * @see self::getLocalURL for the arguments.
1763 * @return string The URL
1765 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1766 wfProfileIn( __METHOD__
);
1767 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1768 $ret = $this->getFullURL( $query, $query2, $proto );
1769 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1770 $ret = $this->getFragmentForURL();
1772 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1774 wfProfileOut( __METHOD__
);
1779 * Get an HTML-escaped version of the URL form, suitable for
1780 * using in a link, without a server name or fragment
1782 * @see self::getLocalURL for the arguments.
1783 * @param string $query
1784 * @param bool|string $query2
1785 * @return string The URL
1786 * @deprecated since 1.19
1788 public function escapeLocalURL( $query = '', $query2 = false ) {
1789 wfDeprecated( __METHOD__
, '1.19' );
1790 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1794 * Get an HTML-escaped version of the URL form, suitable for
1795 * using in a link, including the server name and fragment
1797 * @see self::getLocalURL for the arguments.
1798 * @return string The URL
1799 * @deprecated since 1.19
1801 public function escapeFullURL( $query = '', $query2 = false ) {
1802 wfDeprecated( __METHOD__
, '1.19' );
1803 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1807 * Get the URL form for an internal link.
1808 * - Used in various Squid-related code, in case we have a different
1809 * internal hostname for the server from the exposed one.
1811 * This uses $wgInternalServer to qualify the path, or $wgServer
1812 * if $wgInternalServer is not set. If the server variable used is
1813 * protocol-relative, the URL will be expanded to http://
1815 * @see self::getLocalURL for the arguments.
1816 * @return string The URL
1818 public function getInternalURL( $query = '', $query2 = false ) {
1819 global $wgInternalServer, $wgServer;
1820 $query = self
::fixUrlQueryArgs( $query, $query2 );
1821 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1822 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1823 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1828 * Get the URL for a canonical link, for use in things like IRC and
1829 * e-mail notifications. Uses $wgCanonicalServer and the
1830 * GetCanonicalURL hook.
1832 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1834 * @see self::getLocalURL for the arguments.
1835 * @return string The URL
1838 public function getCanonicalURL( $query = '', $query2 = false ) {
1839 $query = self
::fixUrlQueryArgs( $query, $query2 );
1840 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1841 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1846 * Get the edit URL for this Title
1848 * @return string The URL, or a null string if this is an interwiki link
1850 public function getEditURL() {
1851 if ( $this->isExternal() ) {
1854 $s = $this->getLocalURL( 'action=edit' );
1860 * Is $wgUser watching this page?
1862 * @deprecated since 1.20; use User::isWatched() instead.
1865 public function userIsWatching() {
1868 if ( is_null( $this->mWatched
) ) {
1869 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1870 $this->mWatched
= false;
1872 $this->mWatched
= $wgUser->isWatched( $this );
1875 return $this->mWatched
;
1879 * Can $wgUser read this page?
1881 * @deprecated since 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1884 public function userCanRead() {
1885 wfDeprecated( __METHOD__
, '1.19' );
1886 return $this->userCan( 'read' );
1890 * Can $user perform $action on this page?
1891 * This skips potentially expensive cascading permission checks
1892 * as well as avoids expensive error formatting
1894 * Suitable for use for nonessential UI controls in common cases, but
1895 * _not_ for functional access control.
1897 * May provide false positives, but should never provide a false negative.
1899 * @param string $action Action that permission needs to be checked for
1900 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1903 public function quickUserCan( $action, $user = null ) {
1904 return $this->userCan( $action, $user, false );
1908 * Can $user perform $action on this page?
1910 * @param string $action Action that permission needs to be checked for
1911 * @param User $user User to check (since 1.19); $wgUser will be used if not
1913 * @param bool $doExpensiveQueries Set this to false to avoid doing
1914 * unnecessary queries.
1917 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1918 if ( !$user instanceof User
) {
1923 return !count( $this->getUserPermissionsErrorsInternal(
1924 $action, $user, $doExpensiveQueries, true ) );
1928 * Can $user perform $action on this page?
1930 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1932 * @param string $action action that permission needs to be checked for
1933 * @param User $user User to check
1934 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1935 * queries by skipping checks for cascading protections and user blocks.
1936 * @param array $ignoreErrors of Strings Set this to a list of message keys
1937 * whose corresponding errors may be ignored.
1938 * @return array Array of arguments to wfMessage to explain permissions problems.
1940 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1941 $ignoreErrors = array()
1943 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1945 // Remove the errors being ignored.
1946 foreach ( $errors as $index => $error ) {
1947 $error_key = is_array( $error ) ?
$error[0] : $error;
1949 if ( in_array( $error_key, $ignoreErrors ) ) {
1950 unset( $errors[$index] );
1958 * Permissions checks that fail most often, and which are easiest to test.
1960 * @param string $action the action to check
1961 * @param User $user User to check
1962 * @param array $errors List of current errors
1963 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1964 * @param bool $short Short circuit on first error
1966 * @return array List of errors
1968 private function checkQuickPermissions( $action, $user, $errors,
1969 $doExpensiveQueries, $short
1971 if ( !wfRunHooks( 'TitleQuickPermissions',
1972 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1977 if ( $action == 'create' ) {
1979 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1980 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1982 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1984 } elseif ( $action == 'move' ) {
1985 if ( !$user->isAllowed( 'move-rootuserpages' )
1986 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1987 // Show user page-specific message only if the user can move other pages
1988 $errors[] = array( 'cant-move-user-page' );
1991 // Check if user is allowed to move files if it's a file
1992 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1993 $errors[] = array( 'movenotallowedfile' );
1996 // Check if user is allowed to move category pages if it's a category page
1997 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1998 $errors[] = array( 'cant-move-category-page' );
2001 if ( !$user->isAllowed( 'move' ) ) {
2002 // User can't move anything
2003 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2004 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2005 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2006 // custom message if logged-in users without any special rights can move
2007 $errors[] = array( 'movenologintext' );
2009 $errors[] = array( 'movenotallowed' );
2012 } elseif ( $action == 'move-target' ) {
2013 if ( !$user->isAllowed( 'move' ) ) {
2014 // User can't move anything
2015 $errors[] = array( 'movenotallowed' );
2016 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2017 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2018 // Show user page-specific message only if the user can move other pages
2019 $errors[] = array( 'cant-move-to-user-page' );
2020 } elseif ( !$user->isAllowed( 'move-categorypages' )
2021 && $this->mNamespace
== NS_CATEGORY
) {
2022 // Show category page-specific message only if the user can move other pages
2023 $errors[] = array( 'cant-move-to-category-page' );
2025 } elseif ( !$user->isAllowed( $action ) ) {
2026 $errors[] = $this->missingPermissionError( $action, $short );
2033 * Add the resulting error code to the errors array
2035 * @param array $errors List of current errors
2036 * @param array $result Result of errors
2038 * @return array List of errors
2040 private function resultToError( $errors, $result ) {
2041 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2042 // A single array representing an error
2043 $errors[] = $result;
2044 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2045 // A nested array representing multiple errors
2046 $errors = array_merge( $errors, $result );
2047 } elseif ( $result !== '' && is_string( $result ) ) {
2048 // A string representing a message-id
2049 $errors[] = array( $result );
2050 } elseif ( $result === false ) {
2051 // a generic "We don't want them to do that"
2052 $errors[] = array( 'badaccess-group0' );
2058 * Check various permission hooks
2060 * @param string $action The action to check
2061 * @param User $user User to check
2062 * @param array $errors List of current errors
2063 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2064 * @param bool $short Short circuit on first error
2066 * @return array List of errors
2068 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2069 // Use getUserPermissionsErrors instead
2071 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2072 return $result ?
array() : array( array( 'badaccess-group0' ) );
2074 // Check getUserPermissionsErrors hook
2075 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2076 $errors = $this->resultToError( $errors, $result );
2078 // Check getUserPermissionsErrorsExpensive hook
2081 && !( $short && count( $errors ) > 0 )
2082 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2084 $errors = $this->resultToError( $errors, $result );
2091 * Check permissions on special pages & namespaces
2093 * @param string $action The action to check
2094 * @param User $user User to check
2095 * @param array $errors List of current errors
2096 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2097 * @param bool $short Short circuit on first error
2099 * @return array List of errors
2101 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2102 $doExpensiveQueries, $short
2104 # Only 'createaccount' can be performed on special pages,
2105 # which don't actually exist in the DB.
2106 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2107 $errors[] = array( 'ns-specialprotected' );
2110 # Check $wgNamespaceProtection for restricted namespaces
2111 if ( $this->isNamespaceProtected( $user ) ) {
2112 $ns = $this->mNamespace
== NS_MAIN ?
2113 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2114 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2115 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
2122 * Check CSS/JS sub-page permissions
2124 * @param string $action The action to check
2125 * @param User $user User to check
2126 * @param array $errors List of current errors
2127 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2128 * @param bool $short Short circuit on first error
2130 * @return array List of errors
2132 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2133 # Protect css/js subpages of user pages
2134 # XXX: this might be better using restrictions
2135 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2136 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2137 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2138 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2139 $errors[] = array( 'mycustomcssprotected' );
2140 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2141 $errors[] = array( 'mycustomjsprotected' );
2144 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2145 $errors[] = array( 'customcssprotected' );
2146 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2147 $errors[] = array( 'customjsprotected' );
2156 * Check against page_restrictions table requirements on this
2157 * page. The user must possess all required rights for this
2160 * @param string $action The action to check
2161 * @param User $user User to check
2162 * @param array $errors List of current errors
2163 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2164 * @param bool $short Short circuit on first error
2166 * @return array List of errors
2168 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2169 foreach ( $this->getRestrictions( $action ) as $right ) {
2170 // Backwards compatibility, rewrite sysop -> editprotected
2171 if ( $right == 'sysop' ) {
2172 $right = 'editprotected';
2174 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2175 if ( $right == 'autoconfirmed' ) {
2176 $right = 'editsemiprotected';
2178 if ( $right == '' ) {
2181 if ( !$user->isAllowed( $right ) ) {
2182 $errors[] = array( 'protectedpagetext', $right );
2183 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2184 $errors[] = array( 'protectedpagetext', 'protect' );
2192 * Check restrictions on cascading pages.
2194 * @param string $action The action to check
2195 * @param User $user User to check
2196 * @param array $errors List of current errors
2197 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2198 * @param bool $short Short circuit on first error
2200 * @return array List of errors
2202 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2203 $doExpensiveQueries, $short
2205 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2206 # We /could/ use the protection level on the source page, but it's
2207 # fairly ugly as we have to establish a precedence hierarchy for pages
2208 # included by multiple cascade-protected pages. So just restrict
2209 # it to people with 'protect' permission, as they could remove the
2210 # protection anyway.
2211 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2212 # Cascading protection depends on more than this page...
2213 # Several cascading protected pages may include this page...
2214 # Check each cascading level
2215 # This is only for protection restrictions, not for all actions
2216 if ( isset( $restrictions[$action] ) ) {
2217 foreach ( $restrictions[$action] as $right ) {
2218 // Backwards compatibility, rewrite sysop -> editprotected
2219 if ( $right == 'sysop' ) {
2220 $right = 'editprotected';
2222 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2223 if ( $right == 'autoconfirmed' ) {
2224 $right = 'editsemiprotected';
2226 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2228 foreach ( $cascadingSources as $page ) {
2229 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2231 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
2241 * Check action permissions not already checked in checkQuickPermissions
2243 * @param string $action The action to check
2244 * @param User $user User to check
2245 * @param array $errors List of current errors
2246 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2247 * @param bool $short Short circuit on first error
2249 * @return array List of errors
2251 private function checkActionPermissions( $action, $user, $errors,
2252 $doExpensiveQueries, $short
2254 global $wgDeleteRevisionsLimit, $wgLang;
2256 if ( $action == 'protect' ) {
2257 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2258 $user, $doExpensiveQueries, true ) )
2260 // If they can't edit, they shouldn't protect.
2261 $errors[] = array( 'protect-cantedit' );
2263 } elseif ( $action == 'create' ) {
2264 $title_protection = $this->getTitleProtection();
2265 if ( $title_protection ) {
2266 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
2267 $title_protection['pt_create_perm'] = 'editprotected'; // B/C
2269 if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) {
2270 $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C
2272 if ( $title_protection['pt_create_perm'] == ''
2273 ||
!$user->isAllowed( $title_protection['pt_create_perm'] )
2277 User
::whoIs( $title_protection['pt_user'] ),
2278 $title_protection['pt_reason']
2282 } elseif ( $action == 'move' ) {
2283 // Check for immobile pages
2284 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2285 // Specific message for this case
2286 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2287 } elseif ( !$this->isMovable() ) {
2288 // Less specific message for rarer cases
2289 $errors[] = array( 'immobile-source-page' );
2291 } elseif ( $action == 'move-target' ) {
2292 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2293 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2294 } elseif ( !$this->isMovable() ) {
2295 $errors[] = array( 'immobile-target-page' );
2297 } elseif ( $action == 'delete' ) {
2298 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2299 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2301 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2308 * Check that the user isn't blocked from editing.
2310 * @param string $action The action to check
2311 * @param User $user User to check
2312 * @param array $errors List of current errors
2313 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2314 * @param bool $short Short circuit on first error
2316 * @return array List of errors
2318 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2319 // Account creation blocks handled at userlogin.
2320 // Unblocking handled in SpecialUnblock
2321 if ( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2325 global $wgEmailConfirmToEdit;
2327 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2328 $errors[] = array( 'confirmedittext' );
2331 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2332 // Don't block the user from editing their own talk page unless they've been
2333 // explicitly blocked from that too.
2334 } elseif ( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2335 // @todo FIXME: Pass the relevant context into this function.
2336 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2343 * Check that the user is allowed to read this page.
2345 * @param string $action The action to check
2346 * @param User $user User to check
2347 * @param array $errors List of current errors
2348 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2349 * @param bool $short Short circuit on first error
2351 * @return array List of errors
2353 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2354 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2356 $whitelisted = false;
2357 if ( User
::isEveryoneAllowed( 'read' ) ) {
2358 # Shortcut for public wikis, allows skipping quite a bit of code
2359 $whitelisted = true;
2360 } elseif ( $user->isAllowed( 'read' ) ) {
2361 # If the user is allowed to read pages, he is allowed to read all pages
2362 $whitelisted = true;
2363 } elseif ( $this->isSpecial( 'Userlogin' )
2364 ||
$this->isSpecial( 'ChangePassword' )
2365 ||
$this->isSpecial( 'PasswordReset' )
2367 # Always grant access to the login page.
2368 # Even anons need to be able to log in.
2369 $whitelisted = true;
2370 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2371 # Time to check the whitelist
2372 # Only do these checks is there's something to check against
2373 $name = $this->getPrefixedText();
2374 $dbName = $this->getPrefixedDBkey();
2376 // Check for explicit whitelisting with and without underscores
2377 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2378 $whitelisted = true;
2379 } elseif ( $this->getNamespace() == NS_MAIN
) {
2380 # Old settings might have the title prefixed with
2381 # a colon for main-namespace pages
2382 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2383 $whitelisted = true;
2385 } elseif ( $this->isSpecialPage() ) {
2386 # If it's a special page, ditch the subpage bit and check again
2387 $name = $this->getDBkey();
2388 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2390 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2391 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2392 $whitelisted = true;
2398 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2399 $name = $this->getPrefixedText();
2400 // Check for regex whitelisting
2401 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2402 if ( preg_match( $listItem, $name ) ) {
2403 $whitelisted = true;
2409 if ( !$whitelisted ) {
2410 # If the title is not whitelisted, give extensions a chance to do so...
2411 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2412 if ( !$whitelisted ) {
2413 $errors[] = $this->missingPermissionError( $action, $short );
2421 * Get a description array when the user doesn't have the right to perform
2422 * $action (i.e. when User::isAllowed() returns false)
2424 * @param string $action The action to check
2425 * @param bool $short Short circuit on first error
2426 * @return array List of errors
2428 private function missingPermissionError( $action, $short ) {
2429 // We avoid expensive display logic for quickUserCan's and such
2431 return array( 'badaccess-group0' );
2434 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2435 User
::getGroupsWithPermission( $action ) );
2437 if ( count( $groups ) ) {
2441 $wgLang->commaList( $groups ),
2445 return array( 'badaccess-group0' );
2450 * Can $user perform $action on this page? This is an internal function,
2451 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2452 * checks on wfReadOnly() and blocks)
2454 * @param string $action Action that permission needs to be checked for
2455 * @param User $user User to check
2456 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2457 * @param bool $short Set this to true to stop after the first permission error.
2458 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2460 protected function getUserPermissionsErrorsInternal( $action, $user,
2461 $doExpensiveQueries = true, $short = false
2463 wfProfileIn( __METHOD__
);
2465 # Read has special handling
2466 if ( $action == 'read' ) {
2468 'checkPermissionHooks',
2469 'checkReadPermissions',
2473 'checkQuickPermissions',
2474 'checkPermissionHooks',
2475 'checkSpecialsAndNSPermissions',
2476 'checkCSSandJSPermissions',
2477 'checkPageRestrictions',
2478 'checkCascadingSourcesRestrictions',
2479 'checkActionPermissions',
2485 while ( count( $checks ) > 0 &&
2486 !( $short && count( $errors ) > 0 ) ) {
2487 $method = array_shift( $checks );
2488 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2491 wfProfileOut( __METHOD__
);
2496 * Get a filtered list of all restriction types supported by this wiki.
2497 * @param bool $exists True to get all restriction types that apply to
2498 * titles that do exist, False for all restriction types that apply to
2499 * titles that do not exist
2502 public static function getFilteredRestrictionTypes( $exists = true ) {
2503 global $wgRestrictionTypes;
2504 $types = $wgRestrictionTypes;
2506 # Remove the create restriction for existing titles
2507 $types = array_diff( $types, array( 'create' ) );
2509 # Only the create and upload restrictions apply to non-existing titles
2510 $types = array_intersect( $types, array( 'create', 'upload' ) );
2516 * Returns restriction types for the current Title
2518 * @return array Applicable restriction types
2520 public function getRestrictionTypes() {
2521 if ( $this->isSpecialPage() ) {
2525 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2527 if ( $this->getNamespace() != NS_FILE
) {
2528 # Remove the upload restriction for non-file titles
2529 $types = array_diff( $types, array( 'upload' ) );
2532 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2534 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2535 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2541 * Is this title subject to title protection?
2542 * Title protection is the one applied against creation of such title.
2544 * @return array|bool An associative array representing any existent title
2545 * protection, or false if there's none.
2547 private function getTitleProtection() {
2548 // Can't protect pages in special namespaces
2549 if ( $this->getNamespace() < 0 ) {
2553 // Can't protect pages that exist.
2554 if ( $this->exists() ) {
2558 if ( $this->mTitleProtection
=== null ) {
2559 $dbr = wfGetDB( DB_SLAVE
);
2560 $res = $dbr->select(
2562 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2563 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2567 // fetchRow returns false if there are no rows.
2568 $this->mTitleProtection
= $dbr->fetchRow( $res );
2570 return $this->mTitleProtection
;
2574 * Remove any title protection due to page existing
2576 public function deleteTitleProtection() {
2577 $dbw = wfGetDB( DB_MASTER
);
2581 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2584 $this->mTitleProtection
= false;
2588 * Is this page "semi-protected" - the *only* protection levels are listed
2589 * in $wgSemiprotectedRestrictionLevels?
2591 * @param string $action Action to check (default: edit)
2594 public function isSemiProtected( $action = 'edit' ) {
2595 global $wgSemiprotectedRestrictionLevels;
2597 $restrictions = $this->getRestrictions( $action );
2598 $semi = $wgSemiprotectedRestrictionLevels;
2599 if ( !$restrictions ||
!$semi ) {
2600 // Not protected, or all protection is full protection
2604 // Remap autoconfirmed to editsemiprotected for BC
2605 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2606 $semi[$key] = 'editsemiprotected';
2608 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2609 $restrictions[$key] = 'editsemiprotected';
2612 return !array_diff( $restrictions, $semi );
2616 * Does the title correspond to a protected article?
2618 * @param string $action the action the page is protected from,
2619 * by default checks all actions.
2622 public function isProtected( $action = '' ) {
2623 global $wgRestrictionLevels;
2625 $restrictionTypes = $this->getRestrictionTypes();
2627 # Special pages have inherent protection
2628 if ( $this->isSpecialPage() ) {
2632 # Check regular protection levels
2633 foreach ( $restrictionTypes as $type ) {
2634 if ( $action == $type ||
$action == '' ) {
2635 $r = $this->getRestrictions( $type );
2636 foreach ( $wgRestrictionLevels as $level ) {
2637 if ( in_array( $level, $r ) && $level != '' ) {
2648 * Determines if $user is unable to edit this page because it has been protected
2649 * by $wgNamespaceProtection.
2651 * @param User $user User object to check permissions
2654 public function isNamespaceProtected( User
$user ) {
2655 global $wgNamespaceProtection;
2657 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2658 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2659 if ( $right != '' && !$user->isAllowed( $right ) ) {
2668 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2670 * @return bool If the page is subject to cascading restrictions.
2672 public function isCascadeProtected() {
2673 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2674 return ( $sources > 0 );
2678 * Determines whether cascading protection sources have already been loaded from
2681 * @param bool $getPages True to check if the pages are loaded, or false to check
2682 * if the status is loaded.
2683 * @return bool Whether or not the specified information has been loaded
2686 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2687 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2691 * Cascading protection: Get the source of any cascading restrictions on this page.
2693 * @param bool $getPages Whether or not to retrieve the actual pages
2694 * that the restrictions have come from and the actual restrictions
2696 * @return array Two elements: First is an array of Title objects of the
2697 * pages from which cascading restrictions have come, false for
2698 * none, or true if such restrictions exist but $getPages was not
2699 * set. Second is an array like that returned by
2700 * Title::getAllRestrictions(), or an empty array if $getPages is
2703 public function getCascadeProtectionSources( $getPages = true ) {
2705 $pagerestrictions = array();
2707 if ( $this->mCascadeSources
!== null && $getPages ) {
2708 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2709 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2710 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2713 wfProfileIn( __METHOD__
);
2715 $dbr = wfGetDB( DB_SLAVE
);
2717 if ( $this->getNamespace() == NS_FILE
) {
2718 $tables = array( 'imagelinks', 'page_restrictions' );
2719 $where_clauses = array(
2720 'il_to' => $this->getDBkey(),
2725 $tables = array( 'templatelinks', 'page_restrictions' );
2726 $where_clauses = array(
2727 'tl_namespace' => $this->getNamespace(),
2728 'tl_title' => $this->getDBkey(),
2735 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2736 'pr_expiry', 'pr_type', 'pr_level' );
2737 $where_clauses[] = 'page_id=pr_page';
2740 $cols = array( 'pr_expiry' );
2743 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2745 $sources = $getPages ?
array() : false;
2746 $now = wfTimestampNow();
2747 $purgeExpired = false;
2749 foreach ( $res as $row ) {
2750 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2751 if ( $expiry > $now ) {
2753 $page_id = $row->pr_page
;
2754 $page_ns = $row->page_namespace
;
2755 $page_title = $row->page_title
;
2756 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2757 # Add groups needed for each restriction type if its not already there
2758 # Make sure this restriction type still exists
2760 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2761 $pagerestrictions[$row->pr_type
] = array();
2765 isset( $pagerestrictions[$row->pr_type
] )
2766 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2768 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2774 // Trigger lazy purge of expired restrictions from the db
2775 $purgeExpired = true;
2778 if ( $purgeExpired ) {
2779 Title
::purgeExpiredRestrictions();
2783 $this->mCascadeSources
= $sources;
2784 $this->mCascadingRestrictions
= $pagerestrictions;
2786 $this->mHasCascadingRestrictions
= $sources;
2789 wfProfileOut( __METHOD__
);
2790 return array( $sources, $pagerestrictions );
2794 * Accessor for mRestrictionsLoaded
2796 * @return bool Whether or not the page's restrictions have already been
2797 * loaded from the database
2800 public function areRestrictionsLoaded() {
2801 return $this->mRestrictionsLoaded
;
2805 * Accessor/initialisation for mRestrictions
2807 * @param string $action Action that permission needs to be checked for
2808 * @return array Restriction levels needed to take the action. All levels
2811 public function getRestrictions( $action ) {
2812 if ( !$this->mRestrictionsLoaded
) {
2813 $this->loadRestrictions();
2815 return isset( $this->mRestrictions
[$action] )
2816 ?
$this->mRestrictions
[$action]
2821 * Accessor/initialisation for mRestrictions
2823 * @return array Keys are actions, values are arrays as returned by
2824 * Title::getRestrictions()
2827 public function getAllRestrictions() {
2828 if ( !$this->mRestrictionsLoaded
) {
2829 $this->loadRestrictions();
2831 return $this->mRestrictions
;
2835 * Get the expiry time for the restriction against a given action
2837 * @param string $action
2838 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2839 * or not protected at all, or false if the action is not recognised.
2841 public function getRestrictionExpiry( $action ) {
2842 if ( !$this->mRestrictionsLoaded
) {
2843 $this->loadRestrictions();
2845 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2849 * Returns cascading restrictions for the current article
2853 function areRestrictionsCascading() {
2854 if ( !$this->mRestrictionsLoaded
) {
2855 $this->loadRestrictions();
2858 return $this->mCascadeRestriction
;
2862 * Loads a string into mRestrictions array
2864 * @param ResultWrapper $res Resource restrictions as an SQL result.
2865 * @param string $oldFashionedRestrictions Comma-separated list of page
2866 * restrictions from page table (pre 1.10)
2868 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2871 foreach ( $res as $row ) {
2875 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2879 * Compiles list of active page restrictions from both page table (pre 1.10)
2880 * and page_restrictions table for this existing page.
2881 * Public for usage by LiquidThreads.
2883 * @param array $rows Array of db result objects
2884 * @param string $oldFashionedRestrictions Comma-separated list of page
2885 * restrictions from page table (pre 1.10)
2887 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2889 $dbr = wfGetDB( DB_SLAVE
);
2891 $restrictionTypes = $this->getRestrictionTypes();
2893 foreach ( $restrictionTypes as $type ) {
2894 $this->mRestrictions
[$type] = array();
2895 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2898 $this->mCascadeRestriction
= false;
2900 # Backwards-compatibility: also load the restrictions from the page record (old format).
2902 if ( $oldFashionedRestrictions === null ) {
2903 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2904 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2907 if ( $oldFashionedRestrictions != '' ) {
2909 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2910 $temp = explode( '=', trim( $restrict ) );
2911 if ( count( $temp ) == 1 ) {
2912 // old old format should be treated as edit/move restriction
2913 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2914 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2916 $restriction = trim( $temp[1] );
2917 if ( $restriction != '' ) { //some old entries are empty
2918 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2923 $this->mOldRestrictions
= true;
2927 if ( count( $rows ) ) {
2928 # Current system - load second to make them override.
2929 $now = wfTimestampNow();
2930 $purgeExpired = false;
2932 # Cycle through all the restrictions.
2933 foreach ( $rows as $row ) {
2935 // Don't take care of restrictions types that aren't allowed
2936 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2940 // This code should be refactored, now that it's being used more generally,
2941 // But I don't really see any harm in leaving it in Block for now -werdna
2942 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2944 // Only apply the restrictions if they haven't expired!
2945 if ( !$expiry ||
$expiry > $now ) {
2946 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2947 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2949 $this->mCascadeRestriction |
= $row->pr_cascade
;
2951 // Trigger a lazy purge of expired restrictions
2952 $purgeExpired = true;
2956 if ( $purgeExpired ) {
2957 Title
::purgeExpiredRestrictions();
2961 $this->mRestrictionsLoaded
= true;
2965 * Load restrictions from the page_restrictions table
2967 * @param string $oldFashionedRestrictions Comma-separated list of page
2968 * restrictions from page table (pre 1.10)
2970 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2972 if ( !$this->mRestrictionsLoaded
) {
2973 if ( $this->exists() ) {
2974 $dbr = wfGetDB( DB_SLAVE
);
2976 $res = $dbr->select(
2977 'page_restrictions',
2978 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2979 array( 'pr_page' => $this->getArticleID() ),
2983 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2985 $title_protection = $this->getTitleProtection();
2987 if ( $title_protection ) {
2988 $now = wfTimestampNow();
2989 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2991 if ( !$expiry ||
$expiry > $now ) {
2992 // Apply the restrictions
2993 $this->mRestrictionsExpiry
['create'] = $expiry;
2994 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2995 } else { // Get rid of the old restrictions
2996 Title
::purgeExpiredRestrictions();
2997 $this->mTitleProtection
= false;
3000 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
3002 $this->mRestrictionsLoaded
= true;
3008 * Flush the protection cache in this object and force reload from the database.
3009 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3011 public function flushRestrictions() {
3012 $this->mRestrictionsLoaded
= false;
3013 $this->mTitleProtection
= null;
3017 * Purge expired restrictions from the page_restrictions table
3019 static function purgeExpiredRestrictions() {
3020 if ( wfReadOnly() ) {
3024 $method = __METHOD__
;
3025 $dbw = wfGetDB( DB_MASTER
);
3026 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
3028 'page_restrictions',
3029 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3034 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3041 * Does this have subpages? (Warning, usually requires an extra DB query.)
3045 public function hasSubpages() {
3046 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3051 # We dynamically add a member variable for the purpose of this method
3052 # alone to cache the result. There's no point in having it hanging
3053 # around uninitialized in every Title object; therefore we only add it
3054 # if needed and don't declare it statically.
3055 if ( $this->mHasSubpages
=== null ) {
3056 $this->mHasSubpages
= false;
3057 $subpages = $this->getSubpages( 1 );
3058 if ( $subpages instanceof TitleArray
) {
3059 $this->mHasSubpages
= (bool)$subpages->count();
3063 return $this->mHasSubpages
;
3067 * Get all subpages of this page.
3069 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3070 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3071 * doesn't allow subpages
3073 public function getSubpages( $limit = -1 ) {
3074 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3078 $dbr = wfGetDB( DB_SLAVE
);
3079 $conds['page_namespace'] = $this->getNamespace();
3080 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3082 if ( $limit > -1 ) {
3083 $options['LIMIT'] = $limit;
3085 $this->mSubpages
= TitleArray
::newFromResult(
3086 $dbr->select( 'page',
3087 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3093 return $this->mSubpages
;
3097 * Is there a version of this page in the deletion archive?
3099 * @return int The number of archived revisions
3101 public function isDeleted() {
3102 if ( $this->getNamespace() < 0 ) {
3105 $dbr = wfGetDB( DB_SLAVE
);
3107 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3108 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3111 if ( $this->getNamespace() == NS_FILE
) {
3112 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3113 array( 'fa_name' => $this->getDBkey() ),
3122 * Is there a version of this page in the deletion archive?
3126 public function isDeletedQuick() {
3127 if ( $this->getNamespace() < 0 ) {
3130 $dbr = wfGetDB( DB_SLAVE
);
3131 $deleted = (bool)$dbr->selectField( 'archive', '1',
3132 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3135 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3136 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3137 array( 'fa_name' => $this->getDBkey() ),
3145 * Get the article ID for this Title from the link cache,
3146 * adding it if necessary
3148 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3150 * @return int The ID
3152 public function getArticleID( $flags = 0 ) {
3153 if ( $this->getNamespace() < 0 ) {
3154 $this->mArticleID
= 0;
3155 return $this->mArticleID
;
3157 $linkCache = LinkCache
::singleton();
3158 if ( $flags & self
::GAID_FOR_UPDATE
) {
3159 $oldUpdate = $linkCache->forUpdate( true );
3160 $linkCache->clearLink( $this );
3161 $this->mArticleID
= $linkCache->addLinkObj( $this );
3162 $linkCache->forUpdate( $oldUpdate );
3164 if ( -1 == $this->mArticleID
) {
3165 $this->mArticleID
= $linkCache->addLinkObj( $this );
3168 return $this->mArticleID
;
3172 * Is this an article that is a redirect page?
3173 * Uses link cache, adding it if necessary
3175 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3178 public function isRedirect( $flags = 0 ) {
3179 if ( !is_null( $this->mRedirect
) ) {
3180 return $this->mRedirect
;
3182 # Calling getArticleID() loads the field from cache as needed
3183 if ( !$this->getArticleID( $flags ) ) {
3184 $this->mRedirect
= false;
3185 return $this->mRedirect
;
3188 $linkCache = LinkCache
::singleton();
3189 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3190 if ( $cached === null ) {
3191 # Trust LinkCache's state over our own
3192 # LinkCache is telling us that the page doesn't exist, despite there being cached
3193 # data relating to an existing page in $this->mArticleID. Updaters should clear
3194 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3195 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3196 # LinkCache to refresh its data from the master.
3197 $this->mRedirect
= false;
3198 return $this->mRedirect
;
3201 $this->mRedirect
= (bool)$cached;
3203 return $this->mRedirect
;
3207 * What is the length of this page?
3208 * Uses link cache, adding it if necessary
3210 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3213 public function getLength( $flags = 0 ) {
3214 if ( $this->mLength
!= -1 ) {
3215 return $this->mLength
;
3217 # Calling getArticleID() loads the field from cache as needed
3218 if ( !$this->getArticleID( $flags ) ) {
3220 return $this->mLength
;
3222 $linkCache = LinkCache
::singleton();
3223 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3224 if ( $cached === null ) {
3225 # Trust LinkCache's state over our own, as for isRedirect()
3227 return $this->mLength
;
3230 $this->mLength
= intval( $cached );
3232 return $this->mLength
;
3236 * What is the page_latest field for this page?
3238 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3239 * @return int Int or 0 if the page doesn't exist
3241 public function getLatestRevID( $flags = 0 ) {
3242 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3243 return intval( $this->mLatestID
);
3245 # Calling getArticleID() loads the field from cache as needed
3246 if ( !$this->getArticleID( $flags ) ) {
3247 $this->mLatestID
= 0;
3248 return $this->mLatestID
;
3250 $linkCache = LinkCache
::singleton();
3251 $linkCache->addLinkObj( $this );
3252 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3253 if ( $cached === null ) {
3254 # Trust LinkCache's state over our own, as for isRedirect()
3255 $this->mLatestID
= 0;
3256 return $this->mLatestID
;
3259 $this->mLatestID
= intval( $cached );
3261 return $this->mLatestID
;
3265 * This clears some fields in this object, and clears any associated
3266 * keys in the "bad links" section of the link cache.
3268 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3269 * loading of the new page_id. It's also called from
3270 * WikiPage::doDeleteArticleReal()
3272 * @param int $newid The new Article ID
3274 public function resetArticleID( $newid ) {
3275 $linkCache = LinkCache
::singleton();
3276 $linkCache->clearLink( $this );
3278 if ( $newid === false ) {
3279 $this->mArticleID
= -1;
3281 $this->mArticleID
= intval( $newid );
3283 $this->mRestrictionsLoaded
= false;
3284 $this->mRestrictions
= array();
3285 $this->mRedirect
= null;
3286 $this->mLength
= -1;
3287 $this->mLatestID
= false;
3288 $this->mContentModel
= false;
3289 $this->mEstimateRevisions
= null;
3290 $this->mPageLanguage
= false;
3291 $this->mDbPageLanguage
= null;
3295 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3297 * @param string $text Containing title to capitalize
3298 * @param int $ns Namespace index, defaults to NS_MAIN
3299 * @return string Containing capitalized title
3301 public static function capitalize( $text, $ns = NS_MAIN
) {
3304 if ( MWNamespace
::isCapitalized( $ns ) ) {
3305 return $wgContLang->ucfirst( $text );
3312 * Secure and split - main initialisation function for this object
3314 * Assumes that mDbkeyform has been set, and is urldecoded
3315 * and uses underscores, but not otherwise munged. This function
3316 * removes illegal characters, splits off the interwiki and
3317 * namespace prefixes, sets the other forms, and canonicalizes
3320 * @return bool True on success
3322 private function secureAndSplit() {
3324 $this->mInterwiki
= '';
3325 $this->mFragment
= '';
3326 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3328 $dbkey = $this->mDbkeyform
;
3331 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3332 // the parsing code with Title, while avoiding massive refactoring.
3333 // @todo: get rid of secureAndSplit, refactor parsing code.
3334 $parser = $this->getTitleParser();
3335 $parts = $parser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3336 } catch ( MalformedTitleException
$ex ) {
3341 $this->setFragment( '#' . $parts['fragment'] );
3342 $this->mInterwiki
= $parts['interwiki'];
3343 $this->mNamespace
= $parts['namespace'];
3344 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3346 $this->mDbkeyform
= $parts['dbkey'];
3347 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3348 $this->mTextform
= str_replace( '_', ' ', $this->mDbkeyform
);
3350 # We already know that some pages won't be in the database!
3351 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3352 $this->mArticleID
= 0;
3359 * Get an array of Title objects linking to this Title
3360 * Also stores the IDs in the link cache.
3362 * WARNING: do not use this function on arbitrary user-supplied titles!
3363 * On heavily-used templates it will max out the memory.
3365 * @param array $options May be FOR UPDATE
3366 * @param string $table Table name
3367 * @param string $prefix Fields prefix
3368 * @return Title[] Array of Title objects linking here
3370 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3371 if ( count( $options ) > 0 ) {
3372 $db = wfGetDB( DB_MASTER
);
3374 $db = wfGetDB( DB_SLAVE
);
3378 array( 'page', $table ),
3379 self
::getSelectFields(),
3381 "{$prefix}_from=page_id",
3382 "{$prefix}_namespace" => $this->getNamespace(),
3383 "{$prefix}_title" => $this->getDBkey() ),
3389 if ( $res->numRows() ) {
3390 $linkCache = LinkCache
::singleton();
3391 foreach ( $res as $row ) {
3392 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3394 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3395 $retVal[] = $titleObj;
3403 * Get an array of Title objects using this Title as a template
3404 * Also stores the IDs in the link cache.
3406 * WARNING: do not use this function on arbitrary user-supplied titles!
3407 * On heavily-used templates it will max out the memory.
3409 * @param array $options May be FOR UPDATE
3410 * @return Title[] Array of Title the Title objects linking here
3412 public function getTemplateLinksTo( $options = array() ) {
3413 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3417 * Get an array of Title objects linked from this Title
3418 * Also stores the IDs in the link cache.
3420 * WARNING: do not use this function on arbitrary user-supplied titles!
3421 * On heavily-used templates it will max out the memory.
3423 * @param array $options May be FOR UPDATE
3424 * @param string $table Table name
3425 * @param string $prefix Fields prefix
3426 * @return array Array of Title objects linking here
3428 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3429 global $wgContentHandlerUseDB;
3431 $id = $this->getArticleID();
3433 # If the page doesn't exist; there can't be any link from this page
3438 if ( count( $options ) > 0 ) {
3439 $db = wfGetDB( DB_MASTER
);
3441 $db = wfGetDB( DB_SLAVE
);
3444 $namespaceFiled = "{$prefix}_namespace";
3445 $titleField = "{$prefix}_title";
3456 if ( $wgContentHandlerUseDB ) {
3457 $fields[] = 'page_content_model';
3461 array( $table, 'page' ),
3463 array( "{$prefix}_from" => $id ),
3466 array( 'page' => array(
3468 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3473 if ( $res->numRows() ) {
3474 $linkCache = LinkCache
::singleton();
3475 foreach ( $res as $row ) {
3476 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3478 if ( $row->page_id
) {
3479 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3481 $linkCache->addBadLinkObj( $titleObj );
3483 $retVal[] = $titleObj;
3491 * Get an array of Title objects used on this Title as a template
3492 * Also stores the IDs in the link cache.
3494 * WARNING: do not use this function on arbitrary user-supplied titles!
3495 * On heavily-used templates it will max out the memory.
3497 * @param array $options May be FOR UPDATE
3498 * @return Title[] Array of Title the Title objects used here
3500 public function getTemplateLinksFrom( $options = array() ) {
3501 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3505 * Get an array of Title objects referring to non-existent articles linked
3508 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3509 * should use redirect table in this case).
3510 * @return Title[] Array of Title the Title objects
3512 public function getBrokenLinksFrom() {
3513 if ( $this->getArticleID() == 0 ) {
3514 # All links from article ID 0 are false positives
3518 $dbr = wfGetDB( DB_SLAVE
);
3519 $res = $dbr->select(
3520 array( 'page', 'pagelinks' ),
3521 array( 'pl_namespace', 'pl_title' ),
3523 'pl_from' => $this->getArticleID(),
3524 'page_namespace IS NULL'
3526 __METHOD__
, array(),
3530 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3536 foreach ( $res as $row ) {
3537 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3543 * Get a list of URLs to purge from the Squid cache when this
3546 * @return string[] Array of String the URLs
3548 public function getSquidURLs() {
3550 $this->getInternalURL(),
3551 $this->getInternalURL( 'action=history' )
3554 $pageLang = $this->getPageLanguage();
3555 if ( $pageLang->hasVariants() ) {
3556 $variants = $pageLang->getVariants();
3557 foreach ( $variants as $vCode ) {
3558 $urls[] = $this->getInternalURL( '', $vCode );
3562 // If we are looking at a css/js user subpage, purge the action=raw.
3563 if ( $this->isJsSubpage() ) {
3564 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3565 } elseif ( $this->isCssSubpage() ) {
3566 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3569 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3574 * Purge all applicable Squid URLs
3576 public function purgeSquid() {
3578 if ( $wgUseSquid ) {
3579 $urls = $this->getSquidURLs();
3580 $u = new SquidUpdate( $urls );
3586 * Move this page without authentication
3588 * @param Title $nt The new page Title
3589 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3591 public function moveNoAuth( &$nt ) {
3592 return $this->moveTo( $nt, false );
3596 * Check whether a given move operation would be valid.
3597 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3599 * @param Title $nt The new title
3600 * @param bool $auth Indicates whether $wgUser's permissions
3602 * @param string $reason Is the log summary of the move, used for spam checking
3603 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3605 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3606 global $wgUser, $wgContentHandlerUseDB;
3610 // Normally we'd add this to $errors, but we'll get
3611 // lots of syntax errors if $nt is not an object
3612 return array( array( 'badtitletext' ) );
3614 if ( $this->equals( $nt ) ) {
3615 $errors[] = array( 'selfmove' );
3617 if ( !$this->isMovable() ) {
3618 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3620 if ( $nt->isExternal() ) {
3621 $errors[] = array( 'immobile-target-namespace-iw' );
3623 if ( !$nt->isMovable() ) {
3624 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3627 $oldid = $this->getArticleID();
3628 $newid = $nt->getArticleID();
3630 if ( strlen( $nt->getDBkey() ) < 1 ) {
3631 $errors[] = array( 'articleexists' );
3634 ( $this->getDBkey() == '' ) ||
3636 ( $nt->getDBkey() == '' )
3638 $errors[] = array( 'badarticleerror' );
3641 // Content model checks
3642 if ( !$wgContentHandlerUseDB &&
3643 $this->getContentModel() !== $nt->getContentModel() ) {
3644 // can't move a page if that would change the page's content model
3647 ContentHandler
::getLocalizedName( $this->getContentModel() ),
3648 ContentHandler
::getLocalizedName( $nt->getContentModel() )
3652 // Image-specific checks
3653 if ( $this->getNamespace() == NS_FILE
) {
3654 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3657 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3658 $errors[] = array( 'nonfile-cannot-move-to-file' );
3662 $errors = wfMergeErrorArrays( $errors,
3663 $this->getUserPermissionsErrors( 'move', $wgUser ),
3664 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3665 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3666 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3669 $match = EditPage
::matchSummarySpamRegex( $reason );
3670 if ( $match !== false ) {
3671 // This is kind of lame, won't display nice
3672 $errors[] = array( 'spamprotectiontext' );
3676 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3677 $errors[] = array( 'hookaborted', $err );
3680 # The move is allowed only if (1) the target doesn't exist, or
3681 # (2) the target is a redirect to the source, and has no history
3682 # (so we can undo bad moves right after they're done).
3684 if ( 0 != $newid ) { # Target exists; check for validity
3685 if ( !$this->isValidMoveTarget( $nt ) ) {
3686 $errors[] = array( 'articleexists' );
3689 $tp = $nt->getTitleProtection();
3690 $right = $tp['pt_create_perm'];
3691 if ( $right == 'sysop' ) {
3692 $right = 'editprotected'; // B/C
3694 if ( $right == 'autoconfirmed' ) {
3695 $right = 'editsemiprotected'; // B/C
3697 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3698 $errors[] = array( 'cantmove-titleprotected' );
3701 if ( empty( $errors ) ) {
3708 * Check if the requested move target is a valid file move target
3709 * @param Title $nt Target title
3710 * @return array List of errors
3712 protected function validateFileMoveOperation( $nt ) {
3717 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3719 $file = wfLocalFile( $this );
3720 if ( $file->exists() ) {
3721 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3722 $errors[] = array( 'imageinvalidfilename' );
3724 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3725 $errors[] = array( 'imagetypemismatch' );
3729 if ( $nt->getNamespace() != NS_FILE
) {
3730 $errors[] = array( 'imagenocrossnamespace' );
3731 // From here we want to do checks on a file object, so if we can't
3732 // create one, we must return.
3736 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3738 $destFile = wfLocalFile( $nt );
3739 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3740 $errors[] = array( 'file-exists-sharedrepo' );
3747 * Move a title to a new location
3749 * @param Title $nt The new title
3750 * @param bool $auth Indicates whether $wgUser's permissions
3752 * @param string $reason The reason for the move
3753 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3754 * Ignored if the user doesn't have the suppressredirect right.
3755 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3757 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3759 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3760 if ( is_array( $err ) ) {
3761 // Auto-block user's IP if the account was "hard" blocked
3762 $wgUser->spreadAnyEditBlock();
3765 // Check suppressredirect permission
3766 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3767 $createRedirect = true;
3770 wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) );
3772 // If it is a file, move it first.
3773 // It is done before all other moving stuff is done because it's hard to revert.
3774 $dbw = wfGetDB( DB_MASTER
);
3775 if ( $this->getNamespace() == NS_FILE
) {
3776 $file = wfLocalFile( $this );
3777 if ( $file->exists() ) {
3778 $status = $file->move( $nt );
3779 if ( !$status->isOk() ) {
3780 return $status->getErrorsArray();
3783 // Clear RepoGroup process cache
3784 RepoGroup
::singleton()->clearCache( $this );
3785 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3788 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3789 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3790 $protected = $this->isProtected();
3792 // Do the actual move
3793 $this->moveToInternal( $nt, $reason, $createRedirect );
3795 // Refresh the sortkey for this row. Be careful to avoid resetting
3796 // cl_timestamp, which may disturb time-based lists on some sites.
3797 $prefixes = $dbw->select(
3799 array( 'cl_sortkey_prefix', 'cl_to' ),
3800 array( 'cl_from' => $pageid ),
3803 foreach ( $prefixes as $prefixRow ) {
3804 $prefix = $prefixRow->cl_sortkey_prefix
;
3805 $catTo = $prefixRow->cl_to
;
3806 $dbw->update( 'categorylinks',
3808 'cl_sortkey' => Collation
::singleton()->getSortKey(
3809 $nt->getCategorySortkey( $prefix ) ),
3810 'cl_timestamp=cl_timestamp' ),
3812 'cl_from' => $pageid,
3813 'cl_to' => $catTo ),
3818 $redirid = $this->getArticleID();
3821 # Protect the redirect title as the title used to be...
3822 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3824 'pr_page' => $redirid,
3825 'pr_type' => 'pr_type',
3826 'pr_level' => 'pr_level',
3827 'pr_cascade' => 'pr_cascade',
3828 'pr_user' => 'pr_user',
3829 'pr_expiry' => 'pr_expiry'
3831 array( 'pr_page' => $pageid ),
3835 # Update the protection log
3836 $log = new LogPage( 'protect' );
3837 $comment = wfMessage(
3839 $this->getPrefixedText(),
3840 $nt->getPrefixedText()
3841 )->inContentLanguage()->text();
3843 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3845 // @todo FIXME: $params?
3846 $logId = $log->addEntry(
3850 array( $this->getPrefixedText() ),
3854 // reread inserted pr_ids for log relation
3855 $insertedPrIds = $dbw->select(
3856 'page_restrictions',
3858 array( 'pr_page' => $redirid ),
3861 $logRelationsValues = array();
3862 foreach ( $insertedPrIds as $prid ) {
3863 $logRelationsValues[] = $prid->pr_id
;
3865 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
3869 $oldnamespace = MWNamespace
::getSubject( $this->getNamespace() );
3870 $newnamespace = MWNamespace
::getSubject( $nt->getNamespace() );
3871 $oldtitle = $this->getDBkey();
3872 $newtitle = $nt->getDBkey();
3874 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3875 WatchedItem
::duplicateEntries( $this, $nt );
3878 $dbw->commit( __METHOD__
);
3880 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid, $reason ) );
3885 * Move page to a title which is either a redirect to the
3886 * source page or nonexistent
3888 * @param Title $nt The page to move to, which should be a redirect or nonexistent
3889 * @param string $reason The reason for the move
3890 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3891 * if the user has the suppressredirect right
3892 * @throws MWException
3894 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3895 global $wgUser, $wgContLang;
3897 if ( $nt->exists() ) {
3898 $moveOverRedirect = true;
3899 $logType = 'move_redir';
3901 $moveOverRedirect = false;
3905 if ( $createRedirect ) {
3906 if ( $this->getNamespace() == NS_CATEGORY
3907 && !wfMessage( 'category-move-redirect-override' )->inContentLanguage()->isDisabled()
3909 $redirectContent = new WikitextContent(
3910 wfMessage( 'category-move-redirect-override' )
3911 ->params( $nt->getPrefixedText() )->inContentLanguage()->plain() );
3913 $contentHandler = ContentHandler
::getForTitle( $this );
3914 $redirectContent = $contentHandler->makeRedirectContent( $nt,
3915 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
3918 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3920 $redirectContent = null;
3923 $logEntry = new ManualLogEntry( 'move', $logType );
3924 $logEntry->setPerformer( $wgUser );
3925 $logEntry->setTarget( $this );
3926 $logEntry->setComment( $reason );
3927 $logEntry->setParameters( array(
3928 '4::target' => $nt->getPrefixedText(),
3929 '5::noredir' => $redirectContent ?
'0': '1',
3932 $formatter = LogFormatter
::newFromEntry( $logEntry );
3933 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3934 $comment = $formatter->getPlainActionText();
3936 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3938 # Truncate for whole multibyte characters.
3939 $comment = $wgContLang->truncate( $comment, 255 );
3941 $oldid = $this->getArticleID();
3943 $dbw = wfGetDB( DB_MASTER
);
3945 $newpage = WikiPage
::factory( $nt );
3947 if ( $moveOverRedirect ) {
3948 $newid = $nt->getArticleID();
3949 $newcontent = $newpage->getContent();
3951 # Delete the old redirect. We don't save it to history since
3952 # by definition if we've got here it's rather uninteresting.
3953 # We have to remove it so that the next step doesn't trigger
3954 # a conflict on the unique namespace+title index...
3955 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3957 $newpage->doDeleteUpdates( $newid, $newcontent );
3960 # Save a null revision in the page's history notifying of the move
3961 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true, $wgUser );
3962 if ( !is_object( $nullRevision ) ) {
3963 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3966 $nullRevision->insertOn( $dbw );
3968 # Change the name of the target page:
3969 $dbw->update( 'page',
3971 'page_namespace' => $nt->getNamespace(),
3972 'page_title' => $nt->getDBkey(),
3974 /* WHERE */ array( 'page_id' => $oldid ),
3978 // clean up the old title before reset article id - bug 45348
3979 if ( !$redirectContent ) {
3980 WikiPage
::onArticleDelete( $this );
3983 $this->resetArticleID( 0 ); // 0 == non existing
3984 $nt->resetArticleID( $oldid );
3985 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // bug 46397
3987 $newpage->updateRevisionOn( $dbw, $nullRevision );
3989 wfRunHooks( 'NewRevisionFromEditComplete',
3990 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3992 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3994 if ( !$moveOverRedirect ) {
3995 WikiPage
::onArticleCreate( $nt );
3998 # Recreate the redirect, this time in the other direction.
3999 if ( $redirectContent ) {
4000 $redirectArticle = WikiPage
::factory( $this );
4001 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // bug 46397
4002 $newid = $redirectArticle->insertOn( $dbw );
4003 if ( $newid ) { // sanity
4004 $this->resetArticleID( $newid );
4005 $redirectRevision = new Revision( array(
4006 'title' => $this, // for determining the default content model
4008 'user_text' => $wgUser->getName(),
4009 'user' => $wgUser->getId(),
4010 'comment' => $comment,
4011 'content' => $redirectContent ) );
4012 $redirectRevision->insertOn( $dbw );
4013 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
4015 wfRunHooks( 'NewRevisionFromEditComplete',
4016 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
4018 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
4023 $logid = $logEntry->insert();
4024 $logEntry->publish( $logid );
4028 * Move this page's subpages to be subpages of $nt
4030 * @param Title $nt Move target
4031 * @param bool $auth Whether $wgUser's permissions should be checked
4032 * @param string $reason The reason for the move
4033 * @param bool $createRedirect Whether to create redirects from the old subpages to
4034 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4035 * @return array Array with old page titles as keys, and strings (new page titles) or
4036 * arrays (errors) as values, or an error array with numeric indices if no pages
4039 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
4040 global $wgMaximumMovedPages;
4041 // Check permissions
4042 if ( !$this->userCan( 'move-subpages' ) ) {
4043 return array( 'cant-move-subpages' );
4045 // Do the source and target namespaces support subpages?
4046 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4047 return array( 'namespace-nosubpages',
4048 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
4050 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4051 return array( 'namespace-nosubpages',
4052 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
4055 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4058 foreach ( $subpages as $oldSubpage ) {
4060 if ( $count > $wgMaximumMovedPages ) {
4061 $retval[$oldSubpage->getPrefixedText()] =
4062 array( 'movepage-max-pages',
4063 $wgMaximumMovedPages );
4067 // We don't know whether this function was called before
4068 // or after moving the root page, so check both
4070 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4071 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4073 // When moving a page to a subpage of itself,
4074 // don't move it twice
4077 $newPageName = preg_replace(
4078 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
4079 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
4080 $oldSubpage->getDBkey() );
4081 if ( $oldSubpage->isTalkPage() ) {
4082 $newNs = $nt->getTalkPage()->getNamespace();
4084 $newNs = $nt->getSubjectPage()->getNamespace();
4086 # Bug 14385: we need makeTitleSafe because the new page names may
4087 # be longer than 255 characters.
4088 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
4090 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
4091 if ( $success === true ) {
4092 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4094 $retval[$oldSubpage->getPrefixedText()] = $success;
4101 * Checks if this page is just a one-rev redirect.
4102 * Adds lock, so don't use just for light purposes.
4106 public function isSingleRevRedirect() {
4107 global $wgContentHandlerUseDB;
4109 $dbw = wfGetDB( DB_MASTER
);
4112 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
4113 if ( $wgContentHandlerUseDB ) {
4114 $fields[] = 'page_content_model';
4117 $row = $dbw->selectRow( 'page',
4121 array( 'FOR UPDATE' )
4123 # Cache some fields we may want
4124 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4125 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4126 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4127 $this->mContentModel
= $row && isset( $row->page_content_model
)
4128 ?
strval( $row->page_content_model
)
4131 if ( !$this->mRedirect
) {
4134 # Does the article have a history?
4135 $row = $dbw->selectField( array( 'page', 'revision' ),
4137 array( 'page_namespace' => $this->getNamespace(),
4138 'page_title' => $this->getDBkey(),
4140 'page_latest != rev_id'
4143 array( 'FOR UPDATE' )
4145 # Return true if there was no history
4146 return ( $row === false );
4150 * Checks if $this can be moved to a given Title
4151 * - Selects for update, so don't call it unless you mean business
4153 * @param Title $nt The new title to check
4156 public function isValidMoveTarget( $nt ) {
4157 # Is it an existing file?
4158 if ( $nt->getNamespace() == NS_FILE
) {
4159 $file = wfLocalFile( $nt );
4160 if ( $file->exists() ) {
4161 wfDebug( __METHOD__
. ": file exists\n" );
4165 # Is it a redirect with no history?
4166 if ( !$nt->isSingleRevRedirect() ) {
4167 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4170 # Get the article text
4171 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4172 if ( !is_object( $rev ) ) {
4175 $content = $rev->getContent();
4176 # Does the redirect point to the source?
4177 # Or is it a broken self-redirect, usually caused by namespace collisions?
4178 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4180 if ( $redirTitle ) {
4181 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4182 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4183 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4189 # Fail safe (not a redirect after all. strange.)
4190 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4191 " is a redirect, but it doesn't contain a valid redirect.\n" );
4197 * Get categories to which this Title belongs and return an array of
4198 * categories' names.
4200 * @return array Array of parents in the form:
4201 * $parent => $currentarticle
4203 public function getParentCategories() {
4208 $titleKey = $this->getArticleID();
4210 if ( $titleKey === 0 ) {
4214 $dbr = wfGetDB( DB_SLAVE
);
4216 $res = $dbr->select(
4219 array( 'cl_from' => $titleKey ),
4223 if ( $res->numRows() > 0 ) {
4224 foreach ( $res as $row ) {
4225 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4226 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4233 * Get a tree of parent categories
4235 * @param array $children Array with the children in the keys, to check for circular refs
4236 * @return array Tree of parent categories
4238 public function getParentCategoryTree( $children = array() ) {
4240 $parents = $this->getParentCategories();
4243 foreach ( $parents as $parent => $current ) {
4244 if ( array_key_exists( $parent, $children ) ) {
4245 # Circular reference
4246 $stack[$parent] = array();
4248 $nt = Title
::newFromText( $parent );
4250 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
4260 * Get an associative array for selecting this title from
4263 * @return array Array suitable for the $where parameter of DB::select()
4265 public function pageCond() {
4266 if ( $this->mArticleID
> 0 ) {
4267 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4268 return array( 'page_id' => $this->mArticleID
);
4270 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4275 * Get the revision ID of the previous revision
4277 * @param int $revId Revision ID. Get the revision that was before this one.
4278 * @param int $flags Title::GAID_FOR_UPDATE
4279 * @return int|bool Old revision ID, or false if none exists
4281 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4282 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4283 $revId = $db->selectField( 'revision', 'rev_id',
4285 'rev_page' => $this->getArticleID( $flags ),
4286 'rev_id < ' . intval( $revId )
4289 array( 'ORDER BY' => 'rev_id DESC' )
4292 if ( $revId === false ) {
4295 return intval( $revId );
4300 * Get the revision ID of the next revision
4302 * @param int $revId Revision ID. Get the revision that was after this one.
4303 * @param int $flags Title::GAID_FOR_UPDATE
4304 * @return int|bool Next revision ID, or false if none exists
4306 public function getNextRevisionID( $revId, $flags = 0 ) {
4307 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4308 $revId = $db->selectField( 'revision', 'rev_id',
4310 'rev_page' => $this->getArticleID( $flags ),
4311 'rev_id > ' . intval( $revId )
4314 array( 'ORDER BY' => 'rev_id' )
4317 if ( $revId === false ) {
4320 return intval( $revId );
4325 * Get the first revision of the page
4327 * @param int $flags Title::GAID_FOR_UPDATE
4328 * @return Revision|null If page doesn't exist
4330 public function getFirstRevision( $flags = 0 ) {
4331 $pageId = $this->getArticleID( $flags );
4333 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4334 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4335 array( 'rev_page' => $pageId ),
4337 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4340 return new Revision( $row );
4347 * Get the oldest revision timestamp of this page
4349 * @param int $flags Title::GAID_FOR_UPDATE
4350 * @return string MW timestamp
4352 public function getEarliestRevTime( $flags = 0 ) {
4353 $rev = $this->getFirstRevision( $flags );
4354 return $rev ?
$rev->getTimestamp() : null;
4358 * Check if this is a new page
4362 public function isNewPage() {
4363 $dbr = wfGetDB( DB_SLAVE
);
4364 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4368 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4372 public function isBigDeletion() {
4373 global $wgDeleteRevisionsLimit;
4375 if ( !$wgDeleteRevisionsLimit ) {
4379 $revCount = $this->estimateRevisionCount();
4380 return $revCount > $wgDeleteRevisionsLimit;
4384 * Get the approximate revision count of this page.
4388 public function estimateRevisionCount() {
4389 if ( !$this->exists() ) {
4393 if ( $this->mEstimateRevisions
=== null ) {
4394 $dbr = wfGetDB( DB_SLAVE
);
4395 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4396 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4399 return $this->mEstimateRevisions
;
4403 * Get the number of revisions between the given revision.
4404 * Used for diffs and other things that really need it.
4406 * @param int|Revision $old Old revision or rev ID (first before range)
4407 * @param int|Revision $new New revision or rev ID (first after range)
4408 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4409 * @return int Number of revisions between these revisions.
4411 public function countRevisionsBetween( $old, $new, $max = null ) {
4412 if ( !( $old instanceof Revision
) ) {
4413 $old = Revision
::newFromTitle( $this, (int)$old );
4415 if ( !( $new instanceof Revision
) ) {
4416 $new = Revision
::newFromTitle( $this, (int)$new );
4418 if ( !$old ||
!$new ) {
4419 return 0; // nothing to compare
4421 $dbr = wfGetDB( DB_SLAVE
);
4423 'rev_page' => $this->getArticleID(),
4424 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4425 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4427 if ( $max !== null ) {
4428 $res = $dbr->select( 'revision', '1',
4431 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4433 return $res->numRows();
4435 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4440 * Get the authors between the given revisions or revision IDs.
4441 * Used for diffs and other things that really need it.
4445 * @param int|Revision $old Old revision or rev ID (first before range by default)
4446 * @param int|Revision $new New revision or rev ID (first after range by default)
4447 * @param int $limit Maximum number of authors
4448 * @param string|array $options (Optional): Single option, or an array of options:
4449 * 'include_old' Include $old in the range; $new is excluded.
4450 * 'include_new' Include $new in the range; $old is excluded.
4451 * 'include_both' Include both $old and $new in the range.
4452 * Unknown option values are ignored.
4453 * @return array|null Names of revision authors in the range; null if not both revisions exist
4455 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4456 if ( !( $old instanceof Revision
) ) {
4457 $old = Revision
::newFromTitle( $this, (int)$old );
4459 if ( !( $new instanceof Revision
) ) {
4460 $new = Revision
::newFromTitle( $this, (int)$new );
4462 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4463 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4464 // in the sanity check below?
4465 if ( !$old ||
!$new ) {
4466 return null; // nothing to compare
4471 $options = (array)$options;
4472 if ( in_array( 'include_old', $options ) ) {
4475 if ( in_array( 'include_new', $options ) ) {
4478 if ( in_array( 'include_both', $options ) ) {
4482 // No DB query needed if $old and $new are the same or successive revisions:
4483 if ( $old->getId() === $new->getId() ) {
4484 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
array() : array( $old->getRawUserText() );
4485 } elseif ( $old->getId() === $new->getParentId() ) {
4486 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4487 $authors[] = $old->getRawUserText();
4488 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4489 $authors[] = $new->getRawUserText();
4491 } elseif ( $old_cmp === '>=' ) {
4492 $authors[] = $old->getRawUserText();
4493 } elseif ( $new_cmp === '<=' ) {
4494 $authors[] = $new->getRawUserText();
4498 $dbr = wfGetDB( DB_SLAVE
);
4499 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4501 'rev_page' => $this->getArticleID(),
4502 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4503 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4505 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4507 foreach ( $res as $row ) {
4508 $authors[] = $row->rev_user_text
;
4514 * Get the number of authors between the given revisions or revision IDs.
4515 * Used for diffs and other things that really need it.
4517 * @param int|Revision $old Old revision or rev ID (first before range by default)
4518 * @param int|Revision $new New revision or rev ID (first after range by default)
4519 * @param int $limit Maximum number of authors
4520 * @param string|array $options (Optional): Single option, or an array of options:
4521 * 'include_old' Include $old in the range; $new is excluded.
4522 * 'include_new' Include $new in the range; $old is excluded.
4523 * 'include_both' Include both $old and $new in the range.
4524 * Unknown option values are ignored.
4525 * @return int Number of revision authors in the range; zero if not both revisions exist
4527 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4528 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4529 return $authors ?
count( $authors ) : 0;
4533 * Compare with another title.
4535 * @param Title $title
4538 public function equals( Title
$title ) {
4539 // Note: === is necessary for proper matching of number-like titles.
4540 return $this->getInterwiki() === $title->getInterwiki()
4541 && $this->getNamespace() == $title->getNamespace()
4542 && $this->getDBkey() === $title->getDBkey();
4546 * Check if this title is a subpage of another title
4548 * @param Title $title
4551 public function isSubpageOf( Title
$title ) {
4552 return $this->getInterwiki() === $title->getInterwiki()
4553 && $this->getNamespace() == $title->getNamespace()
4554 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4558 * Check if page exists. For historical reasons, this function simply
4559 * checks for the existence of the title in the page table, and will
4560 * thus return false for interwiki links, special pages and the like.
4561 * If you want to know if a title can be meaningfully viewed, you should
4562 * probably call the isKnown() method instead.
4566 public function exists() {
4567 return $this->getArticleID() != 0;
4571 * Should links to this title be shown as potentially viewable (i.e. as
4572 * "bluelinks"), even if there's no record by this title in the page
4575 * This function is semi-deprecated for public use, as well as somewhat
4576 * misleadingly named. You probably just want to call isKnown(), which
4577 * calls this function internally.
4579 * (ISSUE: Most of these checks are cheap, but the file existence check
4580 * can potentially be quite expensive. Including it here fixes a lot of
4581 * existing code, but we might want to add an optional parameter to skip
4582 * it and any other expensive checks.)
4586 public function isAlwaysKnown() {
4590 * Allows overriding default behavior for determining if a page exists.
4591 * If $isKnown is kept as null, regular checks happen. If it's
4592 * a boolean, this value is returned by the isKnown method.
4596 * @param Title $title
4597 * @param bool|null $isKnown
4599 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4601 if ( !is_null( $isKnown ) ) {
4605 if ( $this->isExternal() ) {
4606 return true; // any interwiki link might be viewable, for all we know
4609 switch ( $this->mNamespace
) {
4612 // file exists, possibly in a foreign repo
4613 return (bool)wfFindFile( $this );
4615 // valid special page
4616 return SpecialPageFactory
::exists( $this->getDBkey() );
4618 // selflink, possibly with fragment
4619 return $this->mDbkeyform
== '';
4621 // known system message
4622 return $this->hasSourceText() !== false;
4629 * Does this title refer to a page that can (or might) be meaningfully
4630 * viewed? In particular, this function may be used to determine if
4631 * links to the title should be rendered as "bluelinks" (as opposed to
4632 * "redlinks" to non-existent pages).
4633 * Adding something else to this function will cause inconsistency
4634 * since LinkHolderArray calls isAlwaysKnown() and does its own
4635 * page existence check.
4639 public function isKnown() {
4640 return $this->isAlwaysKnown() ||
$this->exists();
4644 * Does this page have source text?
4648 public function hasSourceText() {
4649 if ( $this->exists() ) {
4653 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4654 // If the page doesn't exist but is a known system message, default
4655 // message content will be displayed, same for language subpages-
4656 // Use always content language to avoid loading hundreds of languages
4657 // to get the link color.
4659 list( $name, ) = MessageCache
::singleton()->figureMessage(
4660 $wgContLang->lcfirst( $this->getText() )
4662 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4663 return $message->exists();
4670 * Get the default message text or false if the message doesn't exist
4672 * @return string|bool
4674 public function getDefaultMessageText() {
4677 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4681 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4682 $wgContLang->lcfirst( $this->getText() )
4684 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4686 if ( $message->exists() ) {
4687 return $message->plain();
4694 * Updates page_touched for this page; called from LinksUpdate.php
4696 * @return bool True if the update succeeded
4698 public function invalidateCache() {
4699 if ( wfReadOnly() ) {
4703 if ( $this->mArticleID
=== 0 ) {
4704 return true; // avoid gap locking if we know it's not there
4707 $method = __METHOD__
;
4708 $dbw = wfGetDB( DB_MASTER
);
4709 $conds = $this->pageCond();
4710 $dbw->onTransactionIdle( function() use ( $dbw, $conds, $method ) {
4713 array( 'page_touched' => $dbw->timestamp() ),
4723 * Update page_touched timestamps and send squid purge messages for
4724 * pages linking to this title. May be sent to the job queue depending
4725 * on the number of links. Typically called on create and delete.
4727 public function touchLinks() {
4728 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4731 if ( $this->getNamespace() == NS_CATEGORY
) {
4732 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4738 * Get the last touched timestamp
4740 * @param DatabaseBase $db Optional db
4741 * @return string Last-touched timestamp
4743 public function getTouched( $db = null ) {
4744 if ( $db === null ) {
4745 $db = wfGetDB( DB_SLAVE
);
4747 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4752 * Get the timestamp when this page was updated since the user last saw it.
4755 * @return string|null
4757 public function getNotificationTimestamp( $user = null ) {
4758 global $wgUser, $wgShowUpdatedMarker;
4759 // Assume current user if none given
4763 // Check cache first
4764 $uid = $user->getId();
4765 // avoid isset here, as it'll return false for null entries
4766 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4767 return $this->mNotificationTimestamp
[$uid];
4769 if ( !$uid ||
!$wgShowUpdatedMarker ||
!$user->isAllowed( 'viewmywatchlist' ) ) {
4770 $this->mNotificationTimestamp
[$uid] = false;
4771 return $this->mNotificationTimestamp
[$uid];
4773 // Don't cache too much!
4774 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4775 $this->mNotificationTimestamp
= array();
4777 $dbr = wfGetDB( DB_SLAVE
);
4778 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4779 'wl_notificationtimestamp',
4781 'wl_user' => $user->getId(),
4782 'wl_namespace' => $this->getNamespace(),
4783 'wl_title' => $this->getDBkey(),
4787 return $this->mNotificationTimestamp
[$uid];
4791 * Generate strings used for xml 'id' names in monobook tabs
4793 * @param string $prepend Defaults to 'nstab-'
4794 * @return string XML 'id' name
4796 public function getNamespaceKey( $prepend = 'nstab-' ) {
4798 // Gets the subject namespace if this title
4799 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4800 // Checks if canonical namespace name exists for namespace
4801 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4802 // Uses canonical namespace name
4803 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4805 // Uses text of namespace
4806 $namespaceKey = $this->getSubjectNsText();
4808 // Makes namespace key lowercase
4809 $namespaceKey = $wgContLang->lc( $namespaceKey );
4811 if ( $namespaceKey == '' ) {
4812 $namespaceKey = 'main';
4814 // Changes file to image for backwards compatibility
4815 if ( $namespaceKey == 'file' ) {
4816 $namespaceKey = 'image';
4818 return $prepend . $namespaceKey;
4822 * Get all extant redirects to this Title
4824 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4825 * @return Title[] Array of Title redirects to this title
4827 public function getRedirectsHere( $ns = null ) {
4830 $dbr = wfGetDB( DB_SLAVE
);
4832 'rd_namespace' => $this->getNamespace(),
4833 'rd_title' => $this->getDBkey(),
4836 if ( $this->isExternal() ) {
4837 $where['rd_interwiki'] = $this->getInterwiki();
4839 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4841 if ( !is_null( $ns ) ) {
4842 $where['page_namespace'] = $ns;
4845 $res = $dbr->select(
4846 array( 'redirect', 'page' ),
4847 array( 'page_namespace', 'page_title' ),
4852 foreach ( $res as $row ) {
4853 $redirs[] = self
::newFromRow( $row );
4859 * Check if this Title is a valid redirect target
4863 public function isValidRedirectTarget() {
4864 global $wgInvalidRedirectTargets;
4866 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4867 if ( $this->isSpecial( 'Userlogout' ) ) {
4871 foreach ( $wgInvalidRedirectTargets as $target ) {
4872 if ( $this->isSpecial( $target ) ) {
4881 * Get a backlink cache object
4883 * @return BacklinkCache
4885 public function getBacklinkCache() {
4886 return BacklinkCache
::get( $this );
4890 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4894 public function canUseNoindex() {
4895 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4897 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4898 ?
$wgContentNamespaces
4899 : $wgExemptFromUserRobotsControl;
4901 return !in_array( $this->mNamespace
, $bannedNamespaces );
4906 * Returns the raw sort key to be used for categories, with the specified
4907 * prefix. This will be fed to Collation::getSortKey() to get a
4908 * binary sortkey that can be used for actual sorting.
4910 * @param string $prefix The prefix to be used, specified using
4911 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4915 public function getCategorySortkey( $prefix = '' ) {
4916 $unprefixed = $this->getText();
4918 // Anything that uses this hook should only depend
4919 // on the Title object passed in, and should probably
4920 // tell the users to run updateCollations.php --force
4921 // in order to re-sort existing category relations.
4922 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4923 if ( $prefix !== '' ) {
4924 # Separate with a line feed, so the unprefixed part is only used as
4925 # a tiebreaker when two pages have the exact same prefix.
4926 # In UCA, tab is the only character that can sort above LF
4927 # so we strip both of them from the original prefix.
4928 $prefix = strtr( $prefix, "\n\t", ' ' );
4929 return "$prefix\n$unprefixed";
4935 * Get the language in which the content of this page is written in
4936 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4937 * e.g. $wgLang (such as special pages, which are in the user language).
4942 public function getPageLanguage() {
4943 global $wgLang, $wgLanguageCode;
4944 wfProfileIn( __METHOD__
);
4945 if ( $this->isSpecialPage() ) {
4946 // special pages are in the user language
4947 wfProfileOut( __METHOD__
);
4951 // Checking if DB language is set
4952 if ( $this->mDbPageLanguage
) {
4953 wfProfileOut( __METHOD__
);
4954 return wfGetLangObj( $this->mDbPageLanguage
);
4957 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4958 // Note that this may depend on user settings, so the cache should
4959 // be only per-request.
4960 // NOTE: ContentHandler::getPageLanguage() may need to load the
4961 // content to determine the page language!
4962 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4964 $contentHandler = ContentHandler
::getForTitle( $this );
4965 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4966 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4968 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4971 wfProfileOut( __METHOD__
);
4976 * Get the language in which the content of this page is written when
4977 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4978 * e.g. $wgLang (such as special pages, which are in the user language).
4983 public function getPageViewLanguage() {
4986 if ( $this->isSpecialPage() ) {
4987 // If the user chooses a variant, the content is actually
4988 // in a language whose code is the variant code.
4989 $variant = $wgLang->getPreferredVariant();
4990 if ( $wgLang->getCode() !== $variant ) {
4991 return Language
::factory( $variant );
4997 // @note Can't be cached persistently, depends on user settings.
4998 // @note ContentHandler::getPageViewLanguage() may need to load the
4999 // content to determine the page language!
5000 $contentHandler = ContentHandler
::getForTitle( $this );
5001 $pageLang = $contentHandler->getPageViewLanguage( $this );
5006 * Get a list of rendered edit notices for this page.
5008 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5009 * they will already be wrapped in paragraphs.
5012 * @param int $oldid Revision ID that's being edited
5015 public function getEditNotices( $oldid = 0 ) {
5018 # Optional notices on a per-namespace and per-page basis
5019 $editnotice_ns = 'editnotice-' . $this->getNamespace();
5020 $editnotice_ns_message = wfMessage( $editnotice_ns );
5021 if ( $editnotice_ns_message->exists() ) {
5022 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
5024 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
5025 $parts = explode( '/', $this->getDBkey() );
5026 $editnotice_base = $editnotice_ns;
5027 while ( count( $parts ) > 0 ) {
5028 $editnotice_base .= '-' . array_shift( $parts );
5029 $editnotice_base_msg = wfMessage( $editnotice_base );
5030 if ( $editnotice_base_msg->exists() ) {
5031 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
5035 # Even if there are no subpages in namespace, we still don't want / in MW ns.
5036 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
5037 $editnoticeMsg = wfMessage( $editnoticeText );
5038 if ( $editnoticeMsg->exists() ) {
5039 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
5043 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );