Localisation updates for core and extension messages from translatewiki.net
[mediawiki.git] / includes / Title.php
blob64852284521d2feaf4aff261b92e8314e6a2f52b
1 <?php
2 /**
3 * See title.txt
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
31 class Title {
32 /** @name Static cache variables */
33 // @{
34 static private $titleCache = array();
35 // @}
37 /**
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX = 1000;
44 /**
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE = 1;
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
55 // @{
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
86 // @}
89 /**
90 * Constructor
92 /*protected*/ function __construct() { }
94 /**
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
103 $t = new Title();
104 $t->mDbkeyform = $key;
105 if ( $t->secureAndSplit() ) {
106 return $t;
107 } else {
108 return null;
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
121 * makeTitleSafe().
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
133 * caching them.
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
138 return Title::$titleCache[$text];
141 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
142 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
144 $t = new Title();
145 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace = $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN ) {
151 if ( $cachedcount >= self::CACHE_MAX ) {
152 # Avoid memory leaks on mass operations...
153 Title::$titleCache = array();
154 $cachedcount = 0;
156 $cachedcount++;
157 Title::$titleCache[$text] =& $t;
159 return $t;
160 } else {
161 $ret = null;
162 return $ret;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
183 $t = new Title();
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform = str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
194 return $t;
195 } else {
196 return null;
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
210 if ( $row !== false ) {
211 $title = Title::newFromRow( $row );
212 } else {
213 $title = null;
215 return $title;
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
226 return array();
228 $dbr = wfGetDB( DB_SLAVE );
230 $res = $dbr->select(
231 'page',
232 array(
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
237 __METHOD__
240 $titles = array();
241 foreach ( $res as $row ) {
242 $titles[] = Title::newFromRow( $row );
244 return $titles;
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self::makeTitle( $row->page_namespace, $row->page_title );
255 $t->loadFromRow( $row );
256 return $t;
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|bool database row
265 public function loadFromRow( $row ) {
266 if ( $row ) { // page found
267 if ( isset( $row->page_id ) )
268 $this->mArticleID = (int)$row->page_id;
269 if ( isset( $row->page_len ) )
270 $this->mLength = (int)$row->page_len;
271 if ( isset( $row->page_is_redirect ) )
272 $this->mRedirect = (bool)$row->page_is_redirect;
273 if ( isset( $row->page_latest ) )
274 $this->mLatestID = (int)$row->page_latest;
275 } else { // page not found
276 $this->mArticleID = 0;
277 $this->mLength = 0;
278 $this->mRedirect = false;
279 $this->mLatestID = 0;
284 * Create a new Title from a namespace index and a DB key.
285 * It's assumed that $ns and $title are *valid*, for instance when
286 * they came directly from the database or a special page name.
287 * For convenience, spaces are converted to underscores so that
288 * eg user_text fields can be used directly.
290 * @param $ns Int the namespace of the article
291 * @param $title String the unprefixed database key form
292 * @param $fragment String the link fragment (after the "#")
293 * @param $interwiki String the interwiki prefix
294 * @return Title the new object
296 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
297 $t = new Title();
298 $t->mInterwiki = $interwiki;
299 $t->mFragment = $fragment;
300 $t->mNamespace = $ns = intval( $ns );
301 $t->mDbkeyform = str_replace( ' ', '_', $title );
302 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
303 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
304 $t->mTextform = str_replace( '_', ' ', $title );
305 return $t;
309 * Create a new Title from a namespace index and a DB key.
310 * The parameters will be checked for validity, which is a bit slower
311 * than makeTitle() but safer for user-provided data.
313 * @param $ns Int the namespace of the article
314 * @param $title String database key form
315 * @param $fragment String the link fragment (after the "#")
316 * @param $interwiki String interwiki prefix
317 * @return Title the new object, or NULL on an error
319 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
320 $t = new Title();
321 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
322 if ( $t->secureAndSplit() ) {
323 return $t;
324 } else {
325 return null;
330 * Create a new Title for the Main Page
332 * @return Title the new object
334 public static function newMainPage() {
335 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
336 // Don't give fatal errors if the message is broken
337 if ( !$title ) {
338 $title = Title::newFromText( 'Main Page' );
340 return $title;
344 * Extract a redirect destination from a string and return the
345 * Title, or null if the text doesn't contain a valid redirect
346 * This will only return the very next target, useful for
347 * the redirect table and other checks that don't need full recursion
349 * @param $text String: Text with possible redirect
350 * @return Title: The corresponding Title
352 public static function newFromRedirect( $text ) {
353 return self::newFromRedirectInternal( $text );
357 * Extract a redirect destination from a string and return the
358 * Title, or null if the text doesn't contain a valid redirect
359 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
360 * in order to provide (hopefully) the Title of the final destination instead of another redirect
362 * @param $text String Text with possible redirect
363 * @return Title
365 public static function newFromRedirectRecurse( $text ) {
366 $titles = self::newFromRedirectArray( $text );
367 return $titles ? array_pop( $titles ) : null;
371 * Extract a redirect destination from a string and return an
372 * array of Titles, or null if the text doesn't contain a valid redirect
373 * The last element in the array is the final destination after all redirects
374 * have been resolved (up to $wgMaxRedirects times)
376 * @param $text String Text with possible redirect
377 * @return Array of Titles, with the destination last
379 public static function newFromRedirectArray( $text ) {
380 global $wgMaxRedirects;
381 $title = self::newFromRedirectInternal( $text );
382 if ( is_null( $title ) ) {
383 return null;
385 // recursive check to follow double redirects
386 $recurse = $wgMaxRedirects;
387 $titles = array( $title );
388 while ( --$recurse > 0 ) {
389 if ( $title->isRedirect() ) {
390 $page = WikiPage::factory( $title );
391 $newtitle = $page->getRedirectTarget();
392 } else {
393 break;
395 // Redirects to some special pages are not permitted
396 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
397 // the new title passes the checks, so make that our current title so that further recursion can be checked
398 $title = $newtitle;
399 $titles[] = $newtitle;
400 } else {
401 break;
404 return $titles;
408 * Really extract the redirect destination
409 * Do not call this function directly, use one of the newFromRedirect* functions above
411 * @param $text String Text with possible redirect
412 * @return Title
414 protected static function newFromRedirectInternal( $text ) {
415 global $wgMaxRedirects;
416 if ( $wgMaxRedirects < 1 ) {
417 //redirects are disabled, so quit early
418 return null;
420 $redir = MagicWord::get( 'redirect' );
421 $text = trim( $text );
422 if ( $redir->matchStartAndRemove( $text ) ) {
423 // Extract the first link and see if it's usable
424 // Ensure that it really does come directly after #REDIRECT
425 // Some older redirects included a colon, so don't freak about that!
426 $m = array();
427 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
428 // Strip preceding colon used to "escape" categories, etc.
429 // and URL-decode links
430 if ( strpos( $m[1], '%' ) !== false ) {
431 // Match behavior of inline link parsing here;
432 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
434 $title = Title::newFromText( $m[1] );
435 // If the title is a redirect to bad special pages or is invalid, return null
436 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
437 return null;
439 return $title;
442 return null;
446 * Get the prefixed DB key associated with an ID
448 * @param $id Int the page_id of the article
449 * @return Title an object representing the article, or NULL if no such article was found
451 public static function nameOf( $id ) {
452 $dbr = wfGetDB( DB_SLAVE );
454 $s = $dbr->selectRow(
455 'page',
456 array( 'page_namespace', 'page_title' ),
457 array( 'page_id' => $id ),
458 __METHOD__
460 if ( $s === false ) {
461 return null;
464 $n = self::makeName( $s->page_namespace, $s->page_title );
465 return $n;
469 * Get a regex character class describing the legal characters in a link
471 * @return String the list of characters, not delimited
473 public static function legalChars() {
474 global $wgLegalTitleChars;
475 return $wgLegalTitleChars;
479 * Returns a simple regex that will match on characters and sequences invalid in titles.
480 * Note that this doesn't pick up many things that could be wrong with titles, but that
481 * replacing this regex with something valid will make many titles valid.
483 * @return String regex string
485 static function getTitleInvalidRegex() {
486 static $rxTc = false;
487 if ( !$rxTc ) {
488 # Matching titles will be held as illegal.
489 $rxTc = '/' .
490 # Any character not allowed is forbidden...
491 '[^' . self::legalChars() . ']' .
492 # URL percent encoding sequences interfere with the ability
493 # to round-trip titles -- you can't link to them consistently.
494 '|%[0-9A-Fa-f]{2}' .
495 # XML/HTML character references produce similar issues.
496 '|&[A-Za-z0-9\x80-\xff]+;' .
497 '|&#[0-9]+;' .
498 '|&#x[0-9A-Fa-f]+;' .
499 '/S';
502 return $rxTc;
506 * Get a string representation of a title suitable for
507 * including in a search index
509 * @param $ns Int a namespace index
510 * @param $title String text-form main part
511 * @return String a stripped-down title string ready for the search index
513 public static function indexTitle( $ns, $title ) {
514 global $wgContLang;
516 $lc = SearchEngine::legalSearchChars() . '&#;';
517 $t = $wgContLang->normalizeForSearch( $title );
518 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
519 $t = $wgContLang->lc( $t );
521 # Handle 's, s'
522 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
523 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
525 $t = preg_replace( "/\\s+/", ' ', $t );
527 if ( $ns == NS_FILE ) {
528 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
530 return trim( $t );
534 * Make a prefixed DB key from a DB key and a namespace index
536 * @param $ns Int numerical representation of the namespace
537 * @param $title String the DB key form the title
538 * @param $fragment String The link fragment (after the "#")
539 * @param $interwiki String The interwiki prefix
540 * @return String the prefixed form of the title
542 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
543 global $wgContLang;
545 $namespace = $wgContLang->getNsText( $ns );
546 $name = $namespace == '' ? $title : "$namespace:$title";
547 if ( strval( $interwiki ) != '' ) {
548 $name = "$interwiki:$name";
550 if ( strval( $fragment ) != '' ) {
551 $name .= '#' . $fragment;
553 return $name;
557 * Escape a text fragment, say from a link, for a URL
559 * @param $fragment string containing a URL or link fragment (after the "#")
560 * @return String: escaped string
562 static function escapeFragmentForURL( $fragment ) {
563 # Note that we don't urlencode the fragment. urlencoded Unicode
564 # fragments appear not to work in IE (at least up to 7) or in at least
565 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
566 # to care if they aren't encoded.
567 return Sanitizer::escapeId( $fragment, 'noninitial' );
571 * Callback for usort() to do title sorts by (namespace, title)
573 * @param $a Title
574 * @param $b Title
576 * @return Integer: result of string comparison, or namespace comparison
578 public static function compare( $a, $b ) {
579 if ( $a->getNamespace() == $b->getNamespace() ) {
580 return strcmp( $a->getText(), $b->getText() );
581 } else {
582 return $a->getNamespace() - $b->getNamespace();
587 * Determine whether the object refers to a page within
588 * this project.
590 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
592 public function isLocal() {
593 if ( $this->mInterwiki != '' ) {
594 return Interwiki::fetch( $this->mInterwiki )->isLocal();
595 } else {
596 return true;
601 * Is this Title interwiki?
603 * @return Bool
605 public function isExternal() {
606 return ( $this->mInterwiki != '' );
610 * Get the interwiki prefix (or null string)
612 * @return String Interwiki prefix
614 public function getInterwiki() {
615 return $this->mInterwiki;
619 * Determine whether the object refers to a page within
620 * this project and is transcludable.
622 * @return Bool TRUE if this is transcludable
624 public function isTrans() {
625 if ( $this->mInterwiki == '' ) {
626 return false;
629 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
633 * Returns the DB name of the distant wiki which owns the object.
635 * @return String the DB name
637 public function getTransWikiID() {
638 if ( $this->mInterwiki == '' ) {
639 return false;
642 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
646 * Get the text form (spaces not underscores) of the main part
648 * @return String Main part of the title
650 public function getText() {
651 return $this->mTextform;
655 * Get the URL-encoded form of the main part
657 * @return String Main part of the title, URL-encoded
659 public function getPartialURL() {
660 return $this->mUrlform;
664 * Get the main part with underscores
666 * @return String: Main part of the title, with underscores
668 public function getDBkey() {
669 return $this->mDbkeyform;
673 * Get the DB key with the initial letter case as specified by the user
675 * @return String DB key
677 function getUserCaseDBKey() {
678 return $this->mUserCaseDBKey;
682 * Get the namespace index, i.e. one of the NS_xxxx constants.
684 * @return Integer: Namespace index
686 public function getNamespace() {
687 return $this->mNamespace;
691 * Get the namespace text
693 * @return String: Namespace text
695 public function getNsText() {
696 global $wgContLang;
698 if ( $this->mInterwiki != '' ) {
699 // This probably shouldn't even happen. ohh man, oh yuck.
700 // But for interwiki transclusion it sometimes does.
701 // Shit. Shit shit shit.
703 // Use the canonical namespaces if possible to try to
704 // resolve a foreign namespace.
705 if ( MWNamespace::exists( $this->mNamespace ) ) {
706 return MWNamespace::getCanonicalName( $this->mNamespace );
710 // Strip off subpages
711 $pagename = $this->getText();
712 if ( strpos( $pagename, '/' ) !== false ) {
713 list( $username , ) = explode( '/', $pagename, 2 );
714 } else {
715 $username = $pagename;
718 if ( $wgContLang->needsGenderDistinction() &&
719 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
720 $gender = GenderCache::singleton()->getGenderOf( $username, __METHOD__ );
721 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
724 return $wgContLang->getNsText( $this->mNamespace );
728 * Get the namespace text of the subject (rather than talk) page
730 * @return String Namespace text
732 public function getSubjectNsText() {
733 global $wgContLang;
734 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
738 * Get the namespace text of the talk page
740 * @return String Namespace text
742 public function getTalkNsText() {
743 global $wgContLang;
744 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
748 * Could this title have a corresponding talk page?
750 * @return Bool TRUE or FALSE
752 public function canTalk() {
753 return( MWNamespace::canTalk( $this->mNamespace ) );
757 * Is this in a namespace that allows actual pages?
759 * @return Bool
760 * @internal note -- uses hardcoded namespace index instead of constants
762 public function canExist() {
763 return $this->mNamespace >= NS_MAIN;
767 * Can this title be added to a user's watchlist?
769 * @return Bool TRUE or FALSE
771 public function isWatchable() {
772 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
776 * Returns true if this is a special page.
778 * @return boolean
780 public function isSpecialPage() {
781 return $this->getNamespace() == NS_SPECIAL;
785 * Returns true if this title resolves to the named special page
787 * @param $name String The special page name
788 * @return boolean
790 public function isSpecial( $name ) {
791 if ( $this->isSpecialPage() ) {
792 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
793 if ( $name == $thisName ) {
794 return true;
797 return false;
801 * If the Title refers to a special page alias which is not the local default, resolve
802 * the alias, and localise the name as necessary. Otherwise, return $this
804 * @return Title
806 public function fixSpecialName() {
807 if ( $this->isSpecialPage() ) {
808 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
809 if ( $canonicalName ) {
810 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
811 if ( $localName != $this->mDbkeyform ) {
812 return Title::makeTitle( NS_SPECIAL, $localName );
816 return $this;
820 * Returns true if the title is inside the specified namespace.
822 * Please make use of this instead of comparing to getNamespace()
823 * This function is much more resistant to changes we may make
824 * to namespaces than code that makes direct comparisons.
825 * @param $ns int The namespace
826 * @return bool
827 * @since 1.19
829 public function inNamespace( $ns ) {
830 return MWNamespace::equals( $this->getNamespace(), $ns );
834 * Returns true if the title is inside one of the specified namespaces.
836 * @param ...$namespaces The namespaces to check for
837 * @return bool
838 * @since 1.19
840 public function inNamespaces( /* ... */ ) {
841 $namespaces = func_get_args();
842 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
843 $namespaces = $namespaces[0];
846 foreach ( $namespaces as $ns ) {
847 if ( $this->inNamespace( $ns ) ) {
848 return true;
852 return false;
856 * Returns true if the title has the same subject namespace as the
857 * namespace specified.
858 * For example this method will take NS_USER and return true if namespace
859 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
860 * as their subject namespace.
862 * This is MUCH simpler than individually testing for equivilance
863 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
864 * @since 1.19
865 * @return bool
867 public function hasSubjectNamespace( $ns ) {
868 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
872 * Is this Title in a namespace which contains content?
873 * In other words, is this a content page, for the purposes of calculating
874 * statistics, etc?
876 * @return Boolean
878 public function isContentPage() {
879 return MWNamespace::isContent( $this->getNamespace() );
883 * Would anybody with sufficient privileges be able to move this page?
884 * Some pages just aren't movable.
886 * @return Bool TRUE or FALSE
888 public function isMovable() {
889 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->getInterwiki() != '' ) {
890 // Interwiki title or immovable namespace. Hooks don't get to override here
891 return false;
894 $result = true;
895 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
896 return $result;
900 * Is this the mainpage?
901 * @note Title::newFromText seams to be sufficiently optimized by the title
902 * cache that we don't need to over-optimize by doing direct comparisons and
903 * acidentally creating new bugs where $title->equals( Title::newFromText() )
904 * ends up reporting something differently than $title->isMainPage();
906 * @since 1.18
907 * @return Bool
909 public function isMainPage() {
910 return $this->equals( Title::newMainPage() );
914 * Is this a subpage?
916 * @return Bool
918 public function isSubpage() {
919 return MWNamespace::hasSubpages( $this->mNamespace )
920 ? strpos( $this->getText(), '/' ) !== false
921 : false;
925 * Is this a conversion table for the LanguageConverter?
927 * @return Bool
929 public function isConversionTable() {
930 return $this->getNamespace() == NS_MEDIAWIKI &&
931 strpos( $this->getText(), 'Conversiontable' ) !== false;
935 * Does that page contain wikitext, or it is JS, CSS or whatever?
937 * @return Bool
939 public function isWikitextPage() {
940 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
941 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
942 return $retval;
946 * Could this page contain custom CSS or JavaScript, based
947 * on the title?
949 * @return Bool
951 public function isCssOrJsPage() {
952 $retval = $this->mNamespace == NS_MEDIAWIKI
953 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
954 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
955 return $retval;
959 * Is this a .css or .js subpage of a user page?
960 * @return Bool
962 public function isCssJsSubpage() {
963 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
967 * Trim down a .css or .js subpage title to get the corresponding skin name
969 * @return string containing skin name from .css or .js subpage title
971 public function getSkinFromCssJsSubpage() {
972 $subpage = explode( '/', $this->mTextform );
973 $subpage = $subpage[ count( $subpage ) - 1 ];
974 $lastdot = strrpos( $subpage, '.' );
975 if ( $lastdot === false )
976 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
977 return substr( $subpage, 0, $lastdot );
981 * Is this a .css subpage of a user page?
983 * @return Bool
985 public function isCssSubpage() {
986 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
990 * Is this a .js subpage of a user page?
992 * @return Bool
994 public function isJsSubpage() {
995 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
999 * Is this a talk page of some sort?
1001 * @return Bool
1003 public function isTalkPage() {
1004 return MWNamespace::isTalk( $this->getNamespace() );
1008 * Get a Title object associated with the talk page of this article
1010 * @return Title the object for the talk page
1012 public function getTalkPage() {
1013 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1017 * Get a title object associated with the subject page of this
1018 * talk page
1020 * @return Title the object for the subject page
1022 public function getSubjectPage() {
1023 // Is this the same title?
1024 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1025 if ( $this->getNamespace() == $subjectNS ) {
1026 return $this;
1028 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1032 * Get the default namespace index, for when there is no namespace
1034 * @return Int Default namespace index
1036 public function getDefaultNamespace() {
1037 return $this->mDefaultNamespace;
1041 * Get title for search index
1043 * @return String a stripped-down title string ready for the
1044 * search index
1046 public function getIndexTitle() {
1047 return Title::indexTitle( $this->mNamespace, $this->mTextform );
1051 * Get the Title fragment (i.e.\ the bit after the #) in text form
1053 * @return String Title fragment
1055 public function getFragment() {
1056 return $this->mFragment;
1060 * Get the fragment in URL form, including the "#" character if there is one
1061 * @return String Fragment in URL form
1063 public function getFragmentForURL() {
1064 if ( $this->mFragment == '' ) {
1065 return '';
1066 } else {
1067 return '#' . Title::escapeFragmentForURL( $this->mFragment );
1072 * Set the fragment for this title. Removes the first character from the
1073 * specified fragment before setting, so it assumes you're passing it with
1074 * an initial "#".
1076 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1077 * Still in active use privately.
1079 * @param $fragment String text
1081 public function setFragment( $fragment ) {
1082 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1086 * Prefix some arbitrary text with the namespace or interwiki prefix
1087 * of this object
1089 * @param $name String the text
1090 * @return String the prefixed text
1091 * @private
1093 private function prefix( $name ) {
1094 $p = '';
1095 if ( $this->mInterwiki != '' ) {
1096 $p = $this->mInterwiki . ':';
1099 if ( 0 != $this->mNamespace ) {
1100 $p .= $this->getNsText() . ':';
1102 return $p . $name;
1106 * Get the prefixed database key form
1108 * @return String the prefixed title, with underscores and
1109 * any interwiki and namespace prefixes
1111 public function getPrefixedDBkey() {
1112 $s = $this->prefix( $this->mDbkeyform );
1113 $s = str_replace( ' ', '_', $s );
1114 return $s;
1118 * Get the prefixed title with spaces.
1119 * This is the form usually used for display
1121 * @return String the prefixed title, with spaces
1123 public function getPrefixedText() {
1124 // @todo FIXME: Bad usage of empty() ?
1125 if ( empty( $this->mPrefixedText ) ) {
1126 $s = $this->prefix( $this->mTextform );
1127 $s = str_replace( '_', ' ', $s );
1128 $this->mPrefixedText = $s;
1130 return $this->mPrefixedText;
1134 * Return a string representation of this title
1136 * @return String representation of this title
1138 public function __toString() {
1139 return $this->getPrefixedText();
1143 * Get the prefixed title with spaces, plus any fragment
1144 * (part beginning with '#')
1146 * @return String the prefixed title, with spaces and the fragment, including '#'
1148 public function getFullText() {
1149 $text = $this->getPrefixedText();
1150 if ( $this->mFragment != '' ) {
1151 $text .= '#' . $this->mFragment;
1153 return $text;
1157 * Get the base page name, i.e. the leftmost part before any slashes
1159 * @return String Base name
1161 public function getBaseText() {
1162 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1163 return $this->getText();
1166 $parts = explode( '/', $this->getText() );
1167 # Don't discard the real title if there's no subpage involved
1168 if ( count( $parts ) > 1 ) {
1169 unset( $parts[count( $parts ) - 1] );
1171 return implode( '/', $parts );
1175 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1177 * @return String Subpage name
1179 public function getSubpageText() {
1180 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1181 return( $this->mTextform );
1183 $parts = explode( '/', $this->mTextform );
1184 return( $parts[count( $parts ) - 1] );
1188 * Get the HTML-escaped displayable text form.
1189 * Used for the title field in <a> tags.
1191 * @return String the text, including any prefixes
1193 public function getEscapedText() {
1194 wfDeprecated( __METHOD__, '1.19' );
1195 return htmlspecialchars( $this->getPrefixedText() );
1199 * Get a URL-encoded form of the subpage text
1201 * @return String URL-encoded subpage name
1203 public function getSubpageUrlForm() {
1204 $text = $this->getSubpageText();
1205 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1206 return( $text );
1210 * Get a URL-encoded title (not an actual URL) including interwiki
1212 * @return String the URL-encoded form
1214 public function getPrefixedURL() {
1215 $s = $this->prefix( $this->mDbkeyform );
1216 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1217 return $s;
1221 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1222 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1223 * second argument named variant. This was deprecated in favor
1224 * of passing an array of option with a "variant" key
1225 * Once $query2 is removed for good, this helper can be dropped
1226 * andthe wfArrayToCGI moved to getLocalURL();
1228 * @since 1.19 (r105919)
1229 * @return String
1231 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1232 if( $query2 !== false ) {
1233 wfDeprecated( "Title::get{Canonical,Full,Link,Local} method called with a second parameter is deprecated. Add your parameter to an array passed as the first parameter.", "1.19" );
1235 if ( is_array( $query ) ) {
1236 $query = wfArrayToCGI( $query );
1238 if ( $query2 ) {
1239 if ( is_string( $query2 ) ) {
1240 // $query2 is a string, we will consider this to be
1241 // a deprecated $variant argument and add it to the query
1242 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1243 } else {
1244 $query2 = wfArrayToCGI( $query2 );
1246 // If we have $query content add a & to it first
1247 if ( $query ) {
1248 $query .= '&';
1250 // Now append the queries together
1251 $query .= $query2;
1253 return $query;
1257 * Get a real URL referring to this title, with interwiki link and
1258 * fragment
1260 * See getLocalURL for the arguments.
1262 * @see self::getLocalURL
1263 * @return String the URL
1265 public function getFullURL( $query = '', $query2 = false ) {
1266 $query = self::fixUrlQueryArgs( $query, $query2 );
1268 # Hand off all the decisions on urls to getLocalURL
1269 $url = $this->getLocalURL( $query );
1271 # Expand the url to make it a full url. Note that getLocalURL has the
1272 # potential to output full urls for a variety of reasons, so we use
1273 # wfExpandUrl instead of simply prepending $wgServer
1274 $url = wfExpandUrl( $url, PROTO_RELATIVE );
1276 # Finally, add the fragment.
1277 $url .= $this->getFragmentForURL();
1279 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1280 return $url;
1284 * Get a URL with no fragment or server name. If this page is generated
1285 * with action=render, $wgServer is prepended.
1288 * @param $query string|array an optional query string,
1289 * not used for interwiki links. Can be specified as an associative array as well,
1290 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1291 * Some query patterns will trigger various shorturl path replacements.
1292 * @param $query2 Mixed: An optional secondary query array. This one MUST
1293 * be an array. If a string is passed it will be interpreted as a deprecated
1294 * variant argument and urlencoded into a variant= argument.
1295 * This second query argument will be added to the $query
1296 * The second parameter is deprecated since 1.19. Pass it as a key,value
1297 * pair in the first parameter array instead.
1299 * @return String the URL
1301 public function getLocalURL( $query = '', $query2 = false ) {
1302 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1304 $query = self::fixUrlQueryArgs( $query, $query2 );
1306 $interwiki = Interwiki::fetch( $this->mInterwiki );
1307 if ( $interwiki ) {
1308 $namespace = $this->getNsText();
1309 if ( $namespace != '' ) {
1310 # Can this actually happen? Interwikis shouldn't be parsed.
1311 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1312 $namespace .= ':';
1314 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1315 $url = wfAppendQuery( $url, $query );
1316 } else {
1317 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1318 if ( $query == '' ) {
1319 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1320 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1321 } else {
1322 global $wgVariantArticlePath, $wgActionPaths;
1323 $url = false;
1324 $matches = array();
1326 if ( !empty( $wgActionPaths ) &&
1327 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1329 $action = urldecode( $matches[2] );
1330 if ( isset( $wgActionPaths[$action] ) ) {
1331 $query = $matches[1];
1332 if ( isset( $matches[4] ) ) {
1333 $query .= $matches[4];
1335 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1336 if ( $query != '' ) {
1337 $url = wfAppendQuery( $url, $query );
1342 if ( $url === false &&
1343 $wgVariantArticlePath &&
1344 $this->getPageLanguage()->hasVariants() &&
1345 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1347 $variant = urldecode( $matches[1] );
1348 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1349 // Only do the variant replacement if the given variant is a valid
1350 // variant for the page's language.
1351 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1352 $url = str_replace( '$1', $dbkey, $url );
1356 if ( $url === false ) {
1357 if ( $query == '-' ) {
1358 $query = '';
1360 $url = "{$wgScript}?title={$dbkey}&{$query}";
1364 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1366 // @todo FIXME: This causes breakage in various places when we
1367 // actually expected a local URL and end up with dupe prefixes.
1368 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1369 $url = $wgServer . $url;
1372 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1373 return $url;
1377 * Get a URL that's the simplest URL that will be valid to link, locally,
1378 * to the current Title. It includes the fragment, but does not include
1379 * the server unless action=render is used (or the link is external). If
1380 * there's a fragment but the prefixed text is empty, we just return a link
1381 * to the fragment.
1383 * The result obviously should not be URL-escaped, but does need to be
1384 * HTML-escaped if it's being output in HTML.
1386 * See getLocalURL for the arguments.
1388 * @see self::getLocalURL
1389 * @return String the URL
1391 public function getLinkURL( $query = '', $query2 = false ) {
1392 wfProfileIn( __METHOD__ );
1393 if ( $this->isExternal() ) {
1394 $ret = $this->getFullURL( $query, $query2 );
1395 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1396 $ret = $this->getFragmentForURL();
1397 } else {
1398 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1400 wfProfileOut( __METHOD__ );
1401 return $ret;
1405 * Get an HTML-escaped version of the URL form, suitable for
1406 * using in a link, without a server name or fragment
1408 * See getLocalURL for the arguments.
1410 * @see self::getLocalURL
1411 * @return String the URL
1413 public function escapeLocalURL( $query = '', $query2 = false ) {
1414 wfDeprecated( __METHOD__, '1.19' );
1415 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1419 * Get an HTML-escaped version of the URL form, suitable for
1420 * using in a link, including the server name and fragment
1422 * See getLocalURL for the arguments.
1424 * @see self::getLocalURL
1425 * @return String the URL
1427 public function escapeFullURL( $query = '', $query2 = false ) {
1428 wfDeprecated( __METHOD__, '1.19' );
1429 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1433 * Get the URL form for an internal link.
1434 * - Used in various Squid-related code, in case we have a different
1435 * internal hostname for the server from the exposed one.
1437 * This uses $wgInternalServer to qualify the path, or $wgServer
1438 * if $wgInternalServer is not set. If the server variable used is
1439 * protocol-relative, the URL will be expanded to http://
1441 * See getLocalURL for the arguments.
1443 * @see self::getLocalURL
1444 * @return String the URL
1446 public function getInternalURL( $query = '', $query2 = false ) {
1447 global $wgInternalServer, $wgServer;
1448 $query = self::fixUrlQueryArgs( $query, $query2 );
1449 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1450 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1451 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1452 return $url;
1456 * Get the URL for a canonical link, for use in things like IRC and
1457 * e-mail notifications. Uses $wgCanonicalServer and the
1458 * GetCanonicalURL hook.
1460 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1462 * See getLocalURL for the arguments.
1464 * @see self::getLocalURL
1465 * @return string The URL
1466 * @since 1.18
1468 public function getCanonicalURL( $query = '', $query2 = false ) {
1469 $query = self::fixUrlQueryArgs( $query, $query2 );
1470 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1471 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1472 return $url;
1476 * HTML-escaped version of getCanonicalURL()
1478 * See getLocalURL for the arguments.
1480 * @see self::getLocalURL
1481 * @since 1.18
1482 * @return string
1484 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1485 wfDeprecated( __METHOD__, '1.19' );
1486 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1490 * Get the edit URL for this Title
1492 * @return String the URL, or a null string if this is an
1493 * interwiki link
1495 public function getEditURL() {
1496 if ( $this->mInterwiki != '' ) {
1497 return '';
1499 $s = $this->getLocalURL( 'action=edit' );
1501 return $s;
1505 * Is $wgUser watching this page?
1507 * @return Bool
1509 public function userIsWatching() {
1510 global $wgUser;
1512 if ( is_null( $this->mWatched ) ) {
1513 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1514 $this->mWatched = false;
1515 } else {
1516 $this->mWatched = $wgUser->isWatched( $this );
1519 return $this->mWatched;
1523 * Can $wgUser read this page?
1525 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1526 * @return Bool
1527 * @todo fold these checks into userCan()
1529 public function userCanRead() {
1530 wfDeprecated( __METHOD__, '1.19' );
1531 return $this->userCan( 'read' );
1535 * Can $user perform $action on this page?
1536 * This skips potentially expensive cascading permission checks
1537 * as well as avoids expensive error formatting
1539 * Suitable for use for nonessential UI controls in common cases, but
1540 * _not_ for functional access control.
1542 * May provide false positives, but should never provide a false negative.
1544 * @param $action String action that permission needs to be checked for
1545 * @param $user User to check (since 1.19); $wgUser will be used if not
1546 * provided.
1547 * @return Bool
1549 public function quickUserCan( $action, $user = null ) {
1550 return $this->userCan( $action, $user, false );
1554 * Can $user perform $action on this page?
1556 * @param $action String action that permission needs to be checked for
1557 * @param $user User to check (since 1.19); $wgUser will be used if not
1558 * provided.
1559 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1560 * unnecessary queries.
1561 * @return Bool
1563 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1564 if ( !$user instanceof User ) {
1565 global $wgUser;
1566 $user = $wgUser;
1568 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1572 * Can $user perform $action on this page?
1574 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1576 * @param $action String action that permission needs to be checked for
1577 * @param $user User to check
1578 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1579 * queries by skipping checks for cascading protections and user blocks.
1580 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1581 * whose corresponding errors may be ignored.
1582 * @return Array of arguments to wfMsg to explain permissions problems.
1584 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1585 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1587 // Remove the errors being ignored.
1588 foreach ( $errors as $index => $error ) {
1589 $error_key = is_array( $error ) ? $error[0] : $error;
1591 if ( in_array( $error_key, $ignoreErrors ) ) {
1592 unset( $errors[$index] );
1596 return $errors;
1600 * Permissions checks that fail most often, and which are easiest to test.
1602 * @param $action String the action to check
1603 * @param $user User user to check
1604 * @param $errors Array list of current errors
1605 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1606 * @param $short Boolean short circuit on first error
1608 * @return Array list of errors
1610 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1611 if ( $action == 'create' ) {
1612 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1613 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1614 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1616 } elseif ( $action == 'move' ) {
1617 if ( !$user->isAllowed( 'move-rootuserpages' )
1618 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1619 // Show user page-specific message only if the user can move other pages
1620 $errors[] = array( 'cant-move-user-page' );
1623 // Check if user is allowed to move files if it's a file
1624 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1625 $errors[] = array( 'movenotallowedfile' );
1628 if ( !$user->isAllowed( 'move' ) ) {
1629 // User can't move anything
1630 global $wgGroupPermissions;
1631 $userCanMove = false;
1632 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1633 $userCanMove = $wgGroupPermissions['user']['move'];
1635 $autoconfirmedCanMove = false;
1636 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1637 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1639 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1640 // custom message if logged-in users without any special rights can move
1641 $errors[] = array( 'movenologintext' );
1642 } else {
1643 $errors[] = array( 'movenotallowed' );
1646 } elseif ( $action == 'move-target' ) {
1647 if ( !$user->isAllowed( 'move' ) ) {
1648 // User can't move anything
1649 $errors[] = array( 'movenotallowed' );
1650 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1651 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1652 // Show user page-specific message only if the user can move other pages
1653 $errors[] = array( 'cant-move-to-user-page' );
1655 } elseif ( !$user->isAllowed( $action ) ) {
1656 $errors[] = $this->missingPermissionError( $action, $short );
1659 return $errors;
1663 * Add the resulting error code to the errors array
1665 * @param $errors Array list of current errors
1666 * @param $result Mixed result of errors
1668 * @return Array list of errors
1670 private function resultToError( $errors, $result ) {
1671 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1672 // A single array representing an error
1673 $errors[] = $result;
1674 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1675 // A nested array representing multiple errors
1676 $errors = array_merge( $errors, $result );
1677 } elseif ( $result !== '' && is_string( $result ) ) {
1678 // A string representing a message-id
1679 $errors[] = array( $result );
1680 } elseif ( $result === false ) {
1681 // a generic "We don't want them to do that"
1682 $errors[] = array( 'badaccess-group0' );
1684 return $errors;
1688 * Check various permission hooks
1690 * @param $action String the action to check
1691 * @param $user User user to check
1692 * @param $errors Array list of current errors
1693 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1694 * @param $short Boolean short circuit on first error
1696 * @return Array list of errors
1698 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1699 // Use getUserPermissionsErrors instead
1700 $result = '';
1701 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1702 return $result ? array() : array( array( 'badaccess-group0' ) );
1704 // Check getUserPermissionsErrors hook
1705 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1706 $errors = $this->resultToError( $errors, $result );
1708 // Check getUserPermissionsErrorsExpensive hook
1709 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1710 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1711 $errors = $this->resultToError( $errors, $result );
1714 return $errors;
1718 * Check permissions on special pages & namespaces
1720 * @param $action String the action to check
1721 * @param $user User user to check
1722 * @param $errors Array list of current errors
1723 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1724 * @param $short Boolean short circuit on first error
1726 * @return Array list of errors
1728 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1729 # Only 'createaccount' and 'execute' can be performed on
1730 # special pages, which don't actually exist in the DB.
1731 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1732 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1733 $errors[] = array( 'ns-specialprotected' );
1736 # Check $wgNamespaceProtection for restricted namespaces
1737 if ( $this->isNamespaceProtected( $user ) ) {
1738 $ns = $this->mNamespace == NS_MAIN ?
1739 wfMsg( 'nstab-main' ) : $this->getNsText();
1740 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1741 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1744 return $errors;
1748 * Check CSS/JS sub-page permissions
1750 * @param $action String the action to check
1751 * @param $user User user to check
1752 * @param $errors Array list of current errors
1753 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1754 * @param $short Boolean short circuit on first error
1756 * @return Array list of errors
1758 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1759 # Protect css/js subpages of user pages
1760 # XXX: this might be better using restrictions
1761 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1762 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1763 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1764 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1765 $errors[] = array( 'customcssprotected' );
1766 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1767 $errors[] = array( 'customjsprotected' );
1771 return $errors;
1775 * Check against page_restrictions table requirements on this
1776 * page. The user must possess all required rights for this
1777 * action.
1779 * @param $action String the action to check
1780 * @param $user User user to check
1781 * @param $errors Array list of current errors
1782 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1783 * @param $short Boolean short circuit on first error
1785 * @return Array list of errors
1787 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1788 foreach ( $this->getRestrictions( $action ) as $right ) {
1789 // Backwards compatibility, rewrite sysop -> protect
1790 if ( $right == 'sysop' ) {
1791 $right = 'protect';
1793 if ( $right != '' && !$user->isAllowed( $right ) ) {
1794 // Users with 'editprotected' permission can edit protected pages
1795 // without cascading option turned on.
1796 if ( $action != 'edit' || !$user->isAllowed( 'editprotected' )
1797 || $this->mCascadeRestriction )
1799 $errors[] = array( 'protectedpagetext', $right );
1804 return $errors;
1808 * Check restrictions on cascading pages.
1810 * @param $action String the action to check
1811 * @param $user User to check
1812 * @param $errors Array list of current errors
1813 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1814 * @param $short Boolean short circuit on first error
1816 * @return Array list of errors
1818 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1819 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1820 # We /could/ use the protection level on the source page, but it's
1821 # fairly ugly as we have to establish a precedence hierarchy for pages
1822 # included by multiple cascade-protected pages. So just restrict
1823 # it to people with 'protect' permission, as they could remove the
1824 # protection anyway.
1825 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1826 # Cascading protection depends on more than this page...
1827 # Several cascading protected pages may include this page...
1828 # Check each cascading level
1829 # This is only for protection restrictions, not for all actions
1830 if ( isset( $restrictions[$action] ) ) {
1831 foreach ( $restrictions[$action] as $right ) {
1832 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1833 if ( $right != '' && !$user->isAllowed( $right ) ) {
1834 $pages = '';
1835 foreach ( $cascadingSources as $page )
1836 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1837 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1843 return $errors;
1847 * Check action permissions not already checked in checkQuickPermissions
1849 * @param $action String the action to check
1850 * @param $user User to check
1851 * @param $errors Array list of current errors
1852 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1853 * @param $short Boolean short circuit on first error
1855 * @return Array list of errors
1857 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1858 global $wgDeleteRevisionsLimit, $wgLang;
1860 if ( $action == 'protect' ) {
1861 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1862 // If they can't edit, they shouldn't protect.
1863 $errors[] = array( 'protect-cantedit' );
1865 } elseif ( $action == 'create' ) {
1866 $title_protection = $this->getTitleProtection();
1867 if( $title_protection ) {
1868 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1869 $title_protection['pt_create_perm'] = 'protect'; // B/C
1871 if( $title_protection['pt_create_perm'] == '' ||
1872 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1874 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1877 } elseif ( $action == 'move' ) {
1878 // Check for immobile pages
1879 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1880 // Specific message for this case
1881 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1882 } elseif ( !$this->isMovable() ) {
1883 // Less specific message for rarer cases
1884 $errors[] = array( 'immobile-source-page' );
1886 } elseif ( $action == 'move-target' ) {
1887 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1888 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1889 } elseif ( !$this->isMovable() ) {
1890 $errors[] = array( 'immobile-target-page' );
1892 } elseif ( $action == 'delete' ) {
1893 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1894 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1896 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1899 return $errors;
1903 * Check that the user isn't blocked from editting.
1905 * @param $action String the action to check
1906 * @param $user User to check
1907 * @param $errors Array list of current errors
1908 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1909 * @param $short Boolean short circuit on first error
1911 * @return Array list of errors
1913 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1914 // Account creation blocks handled at userlogin.
1915 // Unblocking handled in SpecialUnblock
1916 if( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1917 return $errors;
1920 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1922 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1923 $errors[] = array( 'confirmedittext' );
1926 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1927 // Don't block the user from editing their own talk page unless they've been
1928 // explicitly blocked from that too.
1929 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1930 $block = $user->getBlock();
1932 // This is from OutputPage::blockedPage
1933 // Copied at r23888 by werdna
1935 $id = $user->blockedBy();
1936 $reason = $user->blockedFor();
1937 if ( $reason == '' ) {
1938 $reason = wfMsg( 'blockednoreason' );
1940 $ip = $user->getRequest()->getIP();
1942 if ( is_numeric( $id ) ) {
1943 $name = User::whoIs( $id );
1944 } else {
1945 $name = $id;
1948 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1949 $blockid = $block->getId();
1950 $blockExpiry = $block->getExpiry();
1951 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true );
1952 if ( $blockExpiry == 'infinity' ) {
1953 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1954 } else {
1955 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1958 $intended = strval( $block->getTarget() );
1960 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1961 $blockid, $blockExpiry, $intended, $blockTimestamp );
1964 return $errors;
1968 * Check that the user is allowed to read this page.
1970 * @param $action String the action to check
1971 * @param $user User to check
1972 * @param $errors Array list of current errors
1973 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1974 * @param $short Boolean short circuit on first error
1976 * @return Array list of errors
1978 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1979 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1980 static $useShortcut = null;
1982 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1983 if ( is_null( $useShortcut ) ) {
1984 $useShortcut = true;
1985 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1986 # Not a public wiki, so no shortcut
1987 $useShortcut = false;
1988 } elseif ( !empty( $wgRevokePermissions ) ) {
1990 * Iterate through each group with permissions being revoked (key not included since we don't care
1991 * what the group name is), then check if the read permission is being revoked. If it is, then
1992 * we don't use the shortcut below since the user might not be able to read, even though anon
1993 * reading is allowed.
1995 foreach ( $wgRevokePermissions as $perms ) {
1996 if ( !empty( $perms['read'] ) ) {
1997 # We might be removing the read right from the user, so no shortcut
1998 $useShortcut = false;
1999 break;
2005 $whitelisted = false;
2006 if ( $useShortcut ) {
2007 # Shortcut for public wikis, allows skipping quite a bit of code
2008 $whitelisted = true;
2009 } elseif ( $user->isAllowed( 'read' ) ) {
2010 # If the user is allowed to read pages, he is allowed to read all pages
2011 $whitelisted = true;
2012 } elseif ( $this->isSpecial( 'Userlogin' )
2013 || $this->isSpecial( 'ChangePassword' )
2014 || $this->isSpecial( 'PasswordReset' )
2016 # Always grant access to the login page.
2017 # Even anons need to be able to log in.
2018 $whitelisted = true;
2019 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2020 # Time to check the whitelist
2021 # Only do these checks is there's something to check against
2022 $name = $this->getPrefixedText();
2023 $dbName = $this->getPrefixedDBKey();
2025 // Check for explicit whitelisting with and without underscores
2026 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2027 $whitelisted = true;
2028 } elseif ( $this->getNamespace() == NS_MAIN ) {
2029 # Old settings might have the title prefixed with
2030 # a colon for main-namespace pages
2031 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2032 $whitelisted = true;
2034 } elseif ( $this->isSpecialPage() ) {
2035 # If it's a special page, ditch the subpage bit and check again
2036 $name = $this->getDBkey();
2037 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2038 if ( $name !== false ) {
2039 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2040 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2041 $whitelisted = true;
2047 if ( !$whitelisted ) {
2048 # If the title is not whitelisted, give extensions a chance to do so...
2049 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2050 if ( !$whitelisted ) {
2051 $errors[] = $this->missingPermissionError( $action, $short );
2055 return $errors;
2059 * Get a description array when the user doesn't have the right to perform
2060 * $action (i.e. when User::isAllowed() returns false)
2062 * @param $action String the action to check
2063 * @param $short Boolean short circuit on first error
2064 * @return Array list of errors
2066 private function missingPermissionError( $action, $short ) {
2067 // We avoid expensive display logic for quickUserCan's and such
2068 if ( $short ) {
2069 return array( 'badaccess-group0' );
2072 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2073 User::getGroupsWithPermission( $action ) );
2075 if ( count( $groups ) ) {
2076 global $wgLang;
2077 return array(
2078 'badaccess-groups',
2079 $wgLang->commaList( $groups ),
2080 count( $groups )
2082 } else {
2083 return array( 'badaccess-group0' );
2088 * Can $user perform $action on this page? This is an internal function,
2089 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2090 * checks on wfReadOnly() and blocks)
2092 * @param $action String action that permission needs to be checked for
2093 * @param $user User to check
2094 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2095 * @param $short Bool Set this to true to stop after the first permission error.
2096 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2098 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2099 wfProfileIn( __METHOD__ );
2101 # Read has special handling
2102 if ( $action == 'read' ) {
2103 $checks = array(
2104 'checkPermissionHooks',
2105 'checkReadPermissions',
2107 } else {
2108 $checks = array(
2109 'checkQuickPermissions',
2110 'checkPermissionHooks',
2111 'checkSpecialsAndNSPermissions',
2112 'checkCSSandJSPermissions',
2113 'checkPageRestrictions',
2114 'checkCascadingSourcesRestrictions',
2115 'checkActionPermissions',
2116 'checkUserBlock'
2120 $errors = array();
2121 while( count( $checks ) > 0 &&
2122 !( $short && count( $errors ) > 0 ) ) {
2123 $method = array_shift( $checks );
2124 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2127 wfProfileOut( __METHOD__ );
2128 return $errors;
2132 * Protect css subpages of user pages: can $wgUser edit
2133 * this page?
2135 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2136 * @return Bool
2138 public function userCanEditCssSubpage() {
2139 global $wgUser;
2140 wfDeprecated( __METHOD__, '1.19' );
2141 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2142 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2146 * Protect js subpages of user pages: can $wgUser edit
2147 * this page?
2149 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2150 * @return Bool
2152 public function userCanEditJsSubpage() {
2153 global $wgUser;
2154 wfDeprecated( __METHOD__, '1.19' );
2155 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2156 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2160 * Get a filtered list of all restriction types supported by this wiki.
2161 * @param bool $exists True to get all restriction types that apply to
2162 * titles that do exist, False for all restriction types that apply to
2163 * titles that do not exist
2164 * @return array
2166 public static function getFilteredRestrictionTypes( $exists = true ) {
2167 global $wgRestrictionTypes;
2168 $types = $wgRestrictionTypes;
2169 if ( $exists ) {
2170 # Remove the create restriction for existing titles
2171 $types = array_diff( $types, array( 'create' ) );
2172 } else {
2173 # Only the create and upload restrictions apply to non-existing titles
2174 $types = array_intersect( $types, array( 'create', 'upload' ) );
2176 return $types;
2180 * Returns restriction types for the current Title
2182 * @return array applicable restriction types
2184 public function getRestrictionTypes() {
2185 if ( $this->isSpecialPage() ) {
2186 return array();
2189 $types = self::getFilteredRestrictionTypes( $this->exists() );
2191 if ( $this->getNamespace() != NS_FILE ) {
2192 # Remove the upload restriction for non-file titles
2193 $types = array_diff( $types, array( 'upload' ) );
2196 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2198 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2199 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2201 return $types;
2205 * Is this title subject to title protection?
2206 * Title protection is the one applied against creation of such title.
2208 * @return Mixed An associative array representing any existent title
2209 * protection, or false if there's none.
2211 private function getTitleProtection() {
2212 // Can't protect pages in special namespaces
2213 if ( $this->getNamespace() < 0 ) {
2214 return false;
2217 // Can't protect pages that exist.
2218 if ( $this->exists() ) {
2219 return false;
2222 if ( !isset( $this->mTitleProtection ) ) {
2223 $dbr = wfGetDB( DB_SLAVE );
2224 $res = $dbr->select( 'protected_titles', '*',
2225 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2226 __METHOD__ );
2228 // fetchRow returns false if there are no rows.
2229 $this->mTitleProtection = $dbr->fetchRow( $res );
2231 return $this->mTitleProtection;
2235 * Update the title protection status
2237 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2238 * @param $create_perm String Permission required for creation
2239 * @param $reason String Reason for protection
2240 * @param $expiry String Expiry timestamp
2241 * @return boolean true
2243 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2244 wfDeprecated( __METHOD__, '1.19' );
2246 global $wgUser;
2248 $limit = array( 'create' => $create_perm );
2249 $expiry = array( 'create' => $expiry );
2251 $page = WikiPage::factory( $this );
2252 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2254 return $status->isOK();
2258 * Remove any title protection due to page existing
2260 public function deleteTitleProtection() {
2261 $dbw = wfGetDB( DB_MASTER );
2263 $dbw->delete(
2264 'protected_titles',
2265 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2266 __METHOD__
2268 $this->mTitleProtection = false;
2272 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2274 * @param $action String Action to check (default: edit)
2275 * @return Bool
2277 public function isSemiProtected( $action = 'edit' ) {
2278 if ( $this->exists() ) {
2279 $restrictions = $this->getRestrictions( $action );
2280 if ( count( $restrictions ) > 0 ) {
2281 foreach ( $restrictions as $restriction ) {
2282 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2283 return false;
2286 } else {
2287 # Not protected
2288 return false;
2290 return true;
2291 } else {
2292 # If it doesn't exist, it can't be protected
2293 return false;
2298 * Does the title correspond to a protected article?
2300 * @param $action String the action the page is protected from,
2301 * by default checks all actions.
2302 * @return Bool
2304 public function isProtected( $action = '' ) {
2305 global $wgRestrictionLevels;
2307 $restrictionTypes = $this->getRestrictionTypes();
2309 # Special pages have inherent protection
2310 if( $this->isSpecialPage() ) {
2311 return true;
2314 # Check regular protection levels
2315 foreach ( $restrictionTypes as $type ) {
2316 if ( $action == $type || $action == '' ) {
2317 $r = $this->getRestrictions( $type );
2318 foreach ( $wgRestrictionLevels as $level ) {
2319 if ( in_array( $level, $r ) && $level != '' ) {
2320 return true;
2326 return false;
2330 * Determines if $user is unable to edit this page because it has been protected
2331 * by $wgNamespaceProtection.
2333 * @param $user User object to check permissions
2334 * @return Bool
2336 public function isNamespaceProtected( User $user ) {
2337 global $wgNamespaceProtection;
2339 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2340 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2341 if ( $right != '' && !$user->isAllowed( $right ) ) {
2342 return true;
2346 return false;
2350 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2352 * @return Bool If the page is subject to cascading restrictions.
2354 public function isCascadeProtected() {
2355 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2356 return ( $sources > 0 );
2360 * Cascading protection: Get the source of any cascading restrictions on this page.
2362 * @param $getPages Bool Whether or not to retrieve the actual pages
2363 * that the restrictions have come from.
2364 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2365 * have come, false for none, or true if such restrictions exist, but $getPages
2366 * was not set. The restriction array is an array of each type, each of which
2367 * contains a array of unique groups.
2369 public function getCascadeProtectionSources( $getPages = true ) {
2370 global $wgContLang;
2371 $pagerestrictions = array();
2373 if ( isset( $this->mCascadeSources ) && $getPages ) {
2374 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2375 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2376 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2379 wfProfileIn( __METHOD__ );
2381 $dbr = wfGetDB( DB_SLAVE );
2383 if ( $this->getNamespace() == NS_FILE ) {
2384 $tables = array( 'imagelinks', 'page_restrictions' );
2385 $where_clauses = array(
2386 'il_to' => $this->getDBkey(),
2387 'il_from=pr_page',
2388 'pr_cascade' => 1
2390 } else {
2391 $tables = array( 'templatelinks', 'page_restrictions' );
2392 $where_clauses = array(
2393 'tl_namespace' => $this->getNamespace(),
2394 'tl_title' => $this->getDBkey(),
2395 'tl_from=pr_page',
2396 'pr_cascade' => 1
2400 if ( $getPages ) {
2401 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2402 'pr_expiry', 'pr_type', 'pr_level' );
2403 $where_clauses[] = 'page_id=pr_page';
2404 $tables[] = 'page';
2405 } else {
2406 $cols = array( 'pr_expiry' );
2409 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2411 $sources = $getPages ? array() : false;
2412 $now = wfTimestampNow();
2413 $purgeExpired = false;
2415 foreach ( $res as $row ) {
2416 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2417 if ( $expiry > $now ) {
2418 if ( $getPages ) {
2419 $page_id = $row->pr_page;
2420 $page_ns = $row->page_namespace;
2421 $page_title = $row->page_title;
2422 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2423 # Add groups needed for each restriction type if its not already there
2424 # Make sure this restriction type still exists
2426 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2427 $pagerestrictions[$row->pr_type] = array();
2430 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2431 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2432 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2434 } else {
2435 $sources = true;
2437 } else {
2438 // Trigger lazy purge of expired restrictions from the db
2439 $purgeExpired = true;
2442 if ( $purgeExpired ) {
2443 Title::purgeExpiredRestrictions();
2446 if ( $getPages ) {
2447 $this->mCascadeSources = $sources;
2448 $this->mCascadingRestrictions = $pagerestrictions;
2449 } else {
2450 $this->mHasCascadingRestrictions = $sources;
2453 wfProfileOut( __METHOD__ );
2454 return array( $sources, $pagerestrictions );
2458 * Accessor/initialisation for mRestrictions
2460 * @param $action String action that permission needs to be checked for
2461 * @return Array of Strings the array of groups allowed to edit this article
2463 public function getRestrictions( $action ) {
2464 if ( !$this->mRestrictionsLoaded ) {
2465 $this->loadRestrictions();
2467 return isset( $this->mRestrictions[$action] )
2468 ? $this->mRestrictions[$action]
2469 : array();
2473 * Get the expiry time for the restriction against a given action
2475 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2476 * or not protected at all, or false if the action is not recognised.
2478 public function getRestrictionExpiry( $action ) {
2479 if ( !$this->mRestrictionsLoaded ) {
2480 $this->loadRestrictions();
2482 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2486 * Returns cascading restrictions for the current article
2488 * @return Boolean
2490 function areRestrictionsCascading() {
2491 if ( !$this->mRestrictionsLoaded ) {
2492 $this->loadRestrictions();
2495 return $this->mCascadeRestriction;
2499 * Loads a string into mRestrictions array
2501 * @param $res Resource restrictions as an SQL result.
2502 * @param $oldFashionedRestrictions String comma-separated list of page
2503 * restrictions from page table (pre 1.10)
2505 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2506 $rows = array();
2508 foreach ( $res as $row ) {
2509 $rows[] = $row;
2512 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2516 * Compiles list of active page restrictions from both page table (pre 1.10)
2517 * and page_restrictions table for this existing page.
2518 * Public for usage by LiquidThreads.
2520 * @param $rows array of db result objects
2521 * @param $oldFashionedRestrictions string comma-separated list of page
2522 * restrictions from page table (pre 1.10)
2524 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2525 global $wgContLang;
2526 $dbr = wfGetDB( DB_SLAVE );
2528 $restrictionTypes = $this->getRestrictionTypes();
2530 foreach ( $restrictionTypes as $type ) {
2531 $this->mRestrictions[$type] = array();
2532 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2535 $this->mCascadeRestriction = false;
2537 # Backwards-compatibility: also load the restrictions from the page record (old format).
2539 if ( $oldFashionedRestrictions === null ) {
2540 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2541 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2544 if ( $oldFashionedRestrictions != '' ) {
2546 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2547 $temp = explode( '=', trim( $restrict ) );
2548 if ( count( $temp ) == 1 ) {
2549 // old old format should be treated as edit/move restriction
2550 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2551 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2552 } else {
2553 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2557 $this->mOldRestrictions = true;
2561 if ( count( $rows ) ) {
2562 # Current system - load second to make them override.
2563 $now = wfTimestampNow();
2564 $purgeExpired = false;
2566 # Cycle through all the restrictions.
2567 foreach ( $rows as $row ) {
2569 // Don't take care of restrictions types that aren't allowed
2570 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2571 continue;
2573 // This code should be refactored, now that it's being used more generally,
2574 // But I don't really see any harm in leaving it in Block for now -werdna
2575 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2577 // Only apply the restrictions if they haven't expired!
2578 if ( !$expiry || $expiry > $now ) {
2579 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2580 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2582 $this->mCascadeRestriction |= $row->pr_cascade;
2583 } else {
2584 // Trigger a lazy purge of expired restrictions
2585 $purgeExpired = true;
2589 if ( $purgeExpired ) {
2590 Title::purgeExpiredRestrictions();
2594 $this->mRestrictionsLoaded = true;
2598 * Load restrictions from the page_restrictions table
2600 * @param $oldFashionedRestrictions String comma-separated list of page
2601 * restrictions from page table (pre 1.10)
2603 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2604 global $wgContLang;
2605 if ( !$this->mRestrictionsLoaded ) {
2606 if ( $this->exists() ) {
2607 $dbr = wfGetDB( DB_SLAVE );
2609 $res = $dbr->select(
2610 'page_restrictions',
2611 '*',
2612 array( 'pr_page' => $this->getArticleId() ),
2613 __METHOD__
2616 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2617 } else {
2618 $title_protection = $this->getTitleProtection();
2620 if ( $title_protection ) {
2621 $now = wfTimestampNow();
2622 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2624 if ( !$expiry || $expiry > $now ) {
2625 // Apply the restrictions
2626 $this->mRestrictionsExpiry['create'] = $expiry;
2627 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2628 } else { // Get rid of the old restrictions
2629 Title::purgeExpiredRestrictions();
2630 $this->mTitleProtection = false;
2632 } else {
2633 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2635 $this->mRestrictionsLoaded = true;
2641 * Flush the protection cache in this object and force reload from the database.
2642 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2644 public function flushRestrictions() {
2645 $this->mRestrictionsLoaded = false;
2646 $this->mTitleProtection = null;
2650 * Purge expired restrictions from the page_restrictions table
2652 static function purgeExpiredRestrictions() {
2653 $dbw = wfGetDB( DB_MASTER );
2654 $dbw->delete(
2655 'page_restrictions',
2656 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2657 __METHOD__
2660 $dbw->delete(
2661 'protected_titles',
2662 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2663 __METHOD__
2668 * Does this have subpages? (Warning, usually requires an extra DB query.)
2670 * @return Bool
2672 public function hasSubpages() {
2673 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
2674 # Duh
2675 return false;
2678 # We dynamically add a member variable for the purpose of this method
2679 # alone to cache the result. There's no point in having it hanging
2680 # around uninitialized in every Title object; therefore we only add it
2681 # if needed and don't declare it statically.
2682 if ( isset( $this->mHasSubpages ) ) {
2683 return $this->mHasSubpages;
2686 $subpages = $this->getSubpages( 1 );
2687 if ( $subpages instanceof TitleArray ) {
2688 return $this->mHasSubpages = (bool)$subpages->count();
2690 return $this->mHasSubpages = false;
2694 * Get all subpages of this page.
2696 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2697 * @return mixed TitleArray, or empty array if this page's namespace
2698 * doesn't allow subpages
2700 public function getSubpages( $limit = -1 ) {
2701 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
2702 return array();
2705 $dbr = wfGetDB( DB_SLAVE );
2706 $conds['page_namespace'] = $this->getNamespace();
2707 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2708 $options = array();
2709 if ( $limit > -1 ) {
2710 $options['LIMIT'] = $limit;
2712 return $this->mSubpages = TitleArray::newFromResult(
2713 $dbr->select( 'page',
2714 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2715 $conds,
2716 __METHOD__,
2717 $options
2723 * Is there a version of this page in the deletion archive?
2725 * @return Int the number of archived revisions
2727 public function isDeleted() {
2728 if ( $this->getNamespace() < 0 ) {
2729 $n = 0;
2730 } else {
2731 $dbr = wfGetDB( DB_SLAVE );
2733 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2734 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2735 __METHOD__
2737 if ( $this->getNamespace() == NS_FILE ) {
2738 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2739 array( 'fa_name' => $this->getDBkey() ),
2740 __METHOD__
2744 return (int)$n;
2748 * Is there a version of this page in the deletion archive?
2750 * @return Boolean
2752 public function isDeletedQuick() {
2753 if ( $this->getNamespace() < 0 ) {
2754 return false;
2756 $dbr = wfGetDB( DB_SLAVE );
2757 $deleted = (bool)$dbr->selectField( 'archive', '1',
2758 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2759 __METHOD__
2761 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2762 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2763 array( 'fa_name' => $this->getDBkey() ),
2764 __METHOD__
2767 return $deleted;
2771 * Get the article ID for this Title from the link cache,
2772 * adding it if necessary
2774 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2775 * for update
2776 * @return Int the ID
2778 public function getArticleID( $flags = 0 ) {
2779 if ( $this->getNamespace() < 0 ) {
2780 return $this->mArticleID = 0;
2782 $linkCache = LinkCache::singleton();
2783 if ( $flags & self::GAID_FOR_UPDATE ) {
2784 $oldUpdate = $linkCache->forUpdate( true );
2785 $linkCache->clearLink( $this );
2786 $this->mArticleID = $linkCache->addLinkObj( $this );
2787 $linkCache->forUpdate( $oldUpdate );
2788 } else {
2789 if ( -1 == $this->mArticleID ) {
2790 $this->mArticleID = $linkCache->addLinkObj( $this );
2793 return $this->mArticleID;
2797 * Is this an article that is a redirect page?
2798 * Uses link cache, adding it if necessary
2800 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2801 * @return Bool
2803 public function isRedirect( $flags = 0 ) {
2804 if ( !is_null( $this->mRedirect ) ) {
2805 return $this->mRedirect;
2807 # Calling getArticleID() loads the field from cache as needed
2808 if ( !$this->getArticleID( $flags ) ) {
2809 return $this->mRedirect = false;
2811 $linkCache = LinkCache::singleton();
2812 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2814 return $this->mRedirect;
2818 * What is the length of this page?
2819 * Uses link cache, adding it if necessary
2821 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2822 * @return Int
2824 public function getLength( $flags = 0 ) {
2825 if ( $this->mLength != -1 ) {
2826 return $this->mLength;
2828 # Calling getArticleID() loads the field from cache as needed
2829 if ( !$this->getArticleID( $flags ) ) {
2830 return $this->mLength = 0;
2832 $linkCache = LinkCache::singleton();
2833 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2835 return $this->mLength;
2839 * What is the page_latest field for this page?
2841 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2842 * @return Int or 0 if the page doesn't exist
2844 public function getLatestRevID( $flags = 0 ) {
2845 if ( $this->mLatestID !== false ) {
2846 return intval( $this->mLatestID );
2848 # Calling getArticleID() loads the field from cache as needed
2849 if ( !$this->getArticleID( $flags ) ) {
2850 return $this->mLatestID = 0;
2852 $linkCache = LinkCache::singleton();
2853 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2855 return $this->mLatestID;
2859 * This clears some fields in this object, and clears any associated
2860 * keys in the "bad links" section of the link cache.
2862 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2863 * loading of the new page_id. It's also called from
2864 * WikiPage::doDeleteArticle()
2866 * @param $newid Int the new Article ID
2868 public function resetArticleID( $newid ) {
2869 $linkCache = LinkCache::singleton();
2870 $linkCache->clearLink( $this );
2872 if ( $newid === false ) {
2873 $this->mArticleID = -1;
2874 } else {
2875 $this->mArticleID = intval( $newid );
2877 $this->mRestrictionsLoaded = false;
2878 $this->mRestrictions = array();
2879 $this->mRedirect = null;
2880 $this->mLength = -1;
2881 $this->mLatestID = false;
2882 $this->mEstimateRevisions = null;
2886 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2888 * @param $text String containing title to capitalize
2889 * @param $ns int namespace index, defaults to NS_MAIN
2890 * @return String containing capitalized title
2892 public static function capitalize( $text, $ns = NS_MAIN ) {
2893 global $wgContLang;
2895 if ( MWNamespace::isCapitalized( $ns ) ) {
2896 return $wgContLang->ucfirst( $text );
2897 } else {
2898 return $text;
2903 * Secure and split - main initialisation function for this object
2905 * Assumes that mDbkeyform has been set, and is urldecoded
2906 * and uses underscores, but not otherwise munged. This function
2907 * removes illegal characters, splits off the interwiki and
2908 * namespace prefixes, sets the other forms, and canonicalizes
2909 * everything.
2911 * @return Bool true on success
2913 private function secureAndSplit() {
2914 global $wgContLang, $wgLocalInterwiki;
2916 # Initialisation
2917 $this->mInterwiki = $this->mFragment = '';
2918 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2920 $dbkey = $this->mDbkeyform;
2922 # Strip Unicode bidi override characters.
2923 # Sometimes they slip into cut-n-pasted page titles, where the
2924 # override chars get included in list displays.
2925 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2927 # Clean up whitespace
2928 # Note: use of the /u option on preg_replace here will cause
2929 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2930 # conveniently disabling them.
2931 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2932 $dbkey = trim( $dbkey, '_' );
2934 if ( $dbkey == '' ) {
2935 return false;
2938 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2939 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2940 return false;
2943 $this->mDbkeyform = $dbkey;
2945 # Initial colon indicates main namespace rather than specified default
2946 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2947 if ( ':' == $dbkey[0] ) {
2948 $this->mNamespace = NS_MAIN;
2949 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2950 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2953 # Namespace or interwiki prefix
2954 $firstPass = true;
2955 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2956 do {
2957 $m = array();
2958 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2959 $p = $m[1];
2960 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2961 # Ordinary namespace
2962 $dbkey = $m[2];
2963 $this->mNamespace = $ns;
2964 # For Talk:X pages, check if X has a "namespace" prefix
2965 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2966 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2967 # Disallow Talk:File:x type titles...
2968 return false;
2969 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
2970 # Disallow Talk:Interwiki:x type titles...
2971 return false;
2974 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2975 if ( !$firstPass ) {
2976 # Can't make a local interwiki link to an interwiki link.
2977 # That's just crazy!
2978 return false;
2981 # Interwiki link
2982 $dbkey = $m[2];
2983 $this->mInterwiki = $wgContLang->lc( $p );
2985 # Redundant interwiki prefix to the local wiki
2986 if ( $wgLocalInterwiki !== false
2987 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2989 if ( $dbkey == '' ) {
2990 # Can't have an empty self-link
2991 return false;
2993 $this->mInterwiki = '';
2994 $firstPass = false;
2995 # Do another namespace split...
2996 continue;
2999 # If there's an initial colon after the interwiki, that also
3000 # resets the default namespace
3001 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3002 $this->mNamespace = NS_MAIN;
3003 $dbkey = substr( $dbkey, 1 );
3006 # If there's no recognized interwiki or namespace,
3007 # then let the colon expression be part of the title.
3009 break;
3010 } while ( true );
3012 # We already know that some pages won't be in the database!
3013 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
3014 $this->mArticleID = 0;
3016 $fragment = strstr( $dbkey, '#' );
3017 if ( false !== $fragment ) {
3018 $this->setFragment( $fragment );
3019 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3020 # remove whitespace again: prevents "Foo_bar_#"
3021 # becoming "Foo_bar_"
3022 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3025 # Reject illegal characters.
3026 $rxTc = self::getTitleInvalidRegex();
3027 if ( preg_match( $rxTc, $dbkey ) ) {
3028 return false;
3031 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3032 # reachable due to the way web browsers deal with 'relative' URLs.
3033 # Also, they conflict with subpage syntax. Forbid them explicitly.
3034 if ( strpos( $dbkey, '.' ) !== false &&
3035 ( $dbkey === '.' || $dbkey === '..' ||
3036 strpos( $dbkey, './' ) === 0 ||
3037 strpos( $dbkey, '../' ) === 0 ||
3038 strpos( $dbkey, '/./' ) !== false ||
3039 strpos( $dbkey, '/../' ) !== false ||
3040 substr( $dbkey, -2 ) == '/.' ||
3041 substr( $dbkey, -3 ) == '/..' ) )
3043 return false;
3046 # Magic tilde sequences? Nu-uh!
3047 if ( strpos( $dbkey, '~~~' ) !== false ) {
3048 return false;
3051 # Limit the size of titles to 255 bytes. This is typically the size of the
3052 # underlying database field. We make an exception for special pages, which
3053 # don't need to be stored in the database, and may edge over 255 bytes due
3054 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3055 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
3056 strlen( $dbkey ) > 512 )
3058 return false;
3061 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3062 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3063 # other site might be case-sensitive.
3064 $this->mUserCaseDBKey = $dbkey;
3065 if ( $this->mInterwiki == '' ) {
3066 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
3069 # Can't make a link to a namespace alone... "empty" local links can only be
3070 # self-links with a fragment identifier.
3071 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
3072 return false;
3075 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3076 // IP names are not allowed for accounts, and can only be referring to
3077 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3078 // there are numerous ways to present the same IP. Having sp:contribs scan
3079 // them all is silly and having some show the edits and others not is
3080 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3081 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
3082 ? IP::sanitizeIP( $dbkey )
3083 : $dbkey;
3085 // Any remaining initial :s are illegal.
3086 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3087 return false;
3090 # Fill fields
3091 $this->mDbkeyform = $dbkey;
3092 $this->mUrlform = wfUrlencode( $dbkey );
3094 $this->mTextform = str_replace( '_', ' ', $dbkey );
3096 return true;
3100 * Get an array of Title objects linking to this Title
3101 * Also stores the IDs in the link cache.
3103 * WARNING: do not use this function on arbitrary user-supplied titles!
3104 * On heavily-used templates it will max out the memory.
3106 * @param $options Array: may be FOR UPDATE
3107 * @param $table String: table name
3108 * @param $prefix String: fields prefix
3109 * @return Array of Title objects linking here
3111 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3112 if ( count( $options ) > 0 ) {
3113 $db = wfGetDB( DB_MASTER );
3114 } else {
3115 $db = wfGetDB( DB_SLAVE );
3118 $res = $db->select(
3119 array( 'page', $table ),
3120 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3121 array(
3122 "{$prefix}_from=page_id",
3123 "{$prefix}_namespace" => $this->getNamespace(),
3124 "{$prefix}_title" => $this->getDBkey() ),
3125 __METHOD__,
3126 $options
3129 $retVal = array();
3130 if ( $res->numRows() ) {
3131 $linkCache = LinkCache::singleton();
3132 foreach ( $res as $row ) {
3133 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3134 if ( $titleObj ) {
3135 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3136 $retVal[] = $titleObj;
3140 return $retVal;
3144 * Get an array of Title objects using this Title as a template
3145 * Also stores the IDs in the link cache.
3147 * WARNING: do not use this function on arbitrary user-supplied titles!
3148 * On heavily-used templates it will max out the memory.
3150 * @param $options Array: may be FOR UPDATE
3151 * @return Array of Title the Title objects linking here
3153 public function getTemplateLinksTo( $options = array() ) {
3154 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3158 * Get an array of Title objects linked from this Title
3159 * Also stores the IDs in the link cache.
3161 * WARNING: do not use this function on arbitrary user-supplied titles!
3162 * On heavily-used templates it will max out the memory.
3164 * @param $options Array: may be FOR UPDATE
3165 * @param $table String: table name
3166 * @param $prefix String: fields prefix
3167 * @return Array of Title objects linking here
3169 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3170 $id = $this->getArticleId();
3172 # If the page doesn't exist; there can't be any link from this page
3173 if ( !$id ) {
3174 return array();
3177 if ( count( $options ) > 0 ) {
3178 $db = wfGetDB( DB_MASTER );
3179 } else {
3180 $db = wfGetDB( DB_SLAVE );
3183 $namespaceFiled = "{$prefix}_namespace";
3184 $titleField = "{$prefix}_title";
3186 $res = $db->select(
3187 array( $table, 'page' ),
3188 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3189 array( "{$prefix}_from" => $id ),
3190 __METHOD__,
3191 $options,
3192 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3195 $retVal = array();
3196 if ( $res->numRows() ) {
3197 $linkCache = LinkCache::singleton();
3198 foreach ( $res as $row ) {
3199 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3200 if ( $titleObj ) {
3201 if ( $row->page_id ) {
3202 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3203 } else {
3204 $linkCache->addBadLinkObj( $titleObj );
3206 $retVal[] = $titleObj;
3210 return $retVal;
3214 * Get an array of Title objects used on this Title as a template
3215 * Also stores the IDs in the link cache.
3217 * WARNING: do not use this function on arbitrary user-supplied titles!
3218 * On heavily-used templates it will max out the memory.
3220 * @param $options Array: may be FOR UPDATE
3221 * @return Array of Title the Title objects used here
3223 public function getTemplateLinksFrom( $options = array() ) {
3224 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3228 * Get an array of Title objects referring to non-existent articles linked from this page
3230 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3231 * @return Array of Title the Title objects
3233 public function getBrokenLinksFrom() {
3234 if ( $this->getArticleId() == 0 ) {
3235 # All links from article ID 0 are false positives
3236 return array();
3239 $dbr = wfGetDB( DB_SLAVE );
3240 $res = $dbr->select(
3241 array( 'page', 'pagelinks' ),
3242 array( 'pl_namespace', 'pl_title' ),
3243 array(
3244 'pl_from' => $this->getArticleId(),
3245 'page_namespace IS NULL'
3247 __METHOD__, array(),
3248 array(
3249 'page' => array(
3250 'LEFT JOIN',
3251 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3256 $retVal = array();
3257 foreach ( $res as $row ) {
3258 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3260 return $retVal;
3265 * Get a list of URLs to purge from the Squid cache when this
3266 * page changes
3268 * @return Array of String the URLs
3270 public function getSquidURLs() {
3271 global $wgContLang;
3273 $urls = array(
3274 $this->getInternalURL(),
3275 $this->getInternalURL( 'action=history' )
3278 // purge variant urls as well
3279 if ( $wgContLang->hasVariants() ) {
3280 $variants = $wgContLang->getVariants();
3281 foreach ( $variants as $vCode ) {
3282 $urls[] = $this->getInternalURL( '', $vCode );
3286 return $urls;
3290 * Purge all applicable Squid URLs
3292 public function purgeSquid() {
3293 global $wgUseSquid;
3294 if ( $wgUseSquid ) {
3295 $urls = $this->getSquidURLs();
3296 $u = new SquidUpdate( $urls );
3297 $u->doUpdate();
3302 * Move this page without authentication
3304 * @param $nt Title the new page Title
3305 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3307 public function moveNoAuth( &$nt ) {
3308 return $this->moveTo( $nt, false );
3312 * Check whether a given move operation would be valid.
3313 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3315 * @param $nt Title the new title
3316 * @param $auth Bool indicates whether $wgUser's permissions
3317 * should be checked
3318 * @param $reason String is the log summary of the move, used for spam checking
3319 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3321 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3322 global $wgUser;
3324 $errors = array();
3325 if ( !$nt ) {
3326 // Normally we'd add this to $errors, but we'll get
3327 // lots of syntax errors if $nt is not an object
3328 return array( array( 'badtitletext' ) );
3330 if ( $this->equals( $nt ) ) {
3331 $errors[] = array( 'selfmove' );
3333 if ( !$this->isMovable() ) {
3334 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3336 if ( $nt->getInterwiki() != '' ) {
3337 $errors[] = array( 'immobile-target-namespace-iw' );
3339 if ( !$nt->isMovable() ) {
3340 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3343 $oldid = $this->getArticleID();
3344 $newid = $nt->getArticleID();
3346 if ( strlen( $nt->getDBkey() ) < 1 ) {
3347 $errors[] = array( 'articleexists' );
3349 if ( ( $this->getDBkey() == '' ) ||
3350 ( !$oldid ) ||
3351 ( $nt->getDBkey() == '' ) ) {
3352 $errors[] = array( 'badarticleerror' );
3355 // Image-specific checks
3356 if ( $this->getNamespace() == NS_FILE ) {
3357 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3360 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3361 $errors[] = array( 'nonfile-cannot-move-to-file' );
3364 if ( $auth ) {
3365 $errors = wfMergeErrorArrays( $errors,
3366 $this->getUserPermissionsErrors( 'move', $wgUser ),
3367 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3368 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3369 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3372 $match = EditPage::matchSummarySpamRegex( $reason );
3373 if ( $match !== false ) {
3374 // This is kind of lame, won't display nice
3375 $errors[] = array( 'spamprotectiontext' );
3378 $err = null;
3379 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3380 $errors[] = array( 'hookaborted', $err );
3383 # The move is allowed only if (1) the target doesn't exist, or
3384 # (2) the target is a redirect to the source, and has no history
3385 # (so we can undo bad moves right after they're done).
3387 if ( 0 != $newid ) { # Target exists; check for validity
3388 if ( !$this->isValidMoveTarget( $nt ) ) {
3389 $errors[] = array( 'articleexists' );
3391 } else {
3392 $tp = $nt->getTitleProtection();
3393 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3394 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3395 $errors[] = array( 'cantmove-titleprotected' );
3398 if ( empty( $errors ) ) {
3399 return true;
3401 return $errors;
3405 * Check if the requested move target is a valid file move target
3406 * @param Title $nt Target title
3407 * @return array List of errors
3409 protected function validateFileMoveOperation( $nt ) {
3410 global $wgUser;
3412 $errors = array();
3414 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3416 $file = wfLocalFile( $this );
3417 if ( $file->exists() ) {
3418 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3419 $errors[] = array( 'imageinvalidfilename' );
3421 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3422 $errors[] = array( 'imagetypemismatch' );
3426 if ( $nt->getNamespace() != NS_FILE ) {
3427 $errors[] = array( 'imagenocrossnamespace' );
3428 // From here we want to do checks on a file object, so if we can't
3429 // create one, we must return.
3430 return $errors;
3433 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3435 $destFile = wfLocalFile( $nt );
3436 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3437 $errors[] = array( 'file-exists-sharedrepo' );
3440 return $errors;
3444 * Move a title to a new location
3446 * @param $nt Title the new title
3447 * @param $auth Bool indicates whether $wgUser's permissions
3448 * should be checked
3449 * @param $reason String the reason for the move
3450 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3451 * Ignored if the user doesn't have the suppressredirect right.
3452 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3454 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3455 global $wgUser;
3456 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3457 if ( is_array( $err ) ) {
3458 // Auto-block user's IP if the account was "hard" blocked
3459 $wgUser->spreadAnyEditBlock();
3460 return $err;
3463 // If it is a file, move it first.
3464 // It is done before all other moving stuff is done because it's hard to revert.
3465 $dbw = wfGetDB( DB_MASTER );
3466 if ( $this->getNamespace() == NS_FILE ) {
3467 $file = wfLocalFile( $this );
3468 if ( $file->exists() ) {
3469 $status = $file->move( $nt );
3470 if ( !$status->isOk() ) {
3471 return $status->getErrorsArray();
3474 // Clear RepoGroup process cache
3475 RepoGroup::singleton()->clearCache( $this );
3476 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3479 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3480 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3481 $protected = $this->isProtected();
3483 // Do the actual move
3484 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3485 if ( is_array( $err ) ) {
3486 # @todo FIXME: What about the File we have already moved?
3487 $dbw->rollback();
3488 return $err;
3491 // Refresh the sortkey for this row. Be careful to avoid resetting
3492 // cl_timestamp, which may disturb time-based lists on some sites.
3493 $prefixes = $dbw->select(
3494 'categorylinks',
3495 array( 'cl_sortkey_prefix', 'cl_to' ),
3496 array( 'cl_from' => $pageid ),
3497 __METHOD__
3499 foreach ( $prefixes as $prefixRow ) {
3500 $prefix = $prefixRow->cl_sortkey_prefix;
3501 $catTo = $prefixRow->cl_to;
3502 $dbw->update( 'categorylinks',
3503 array(
3504 'cl_sortkey' => Collation::singleton()->getSortKey(
3505 $nt->getCategorySortkey( $prefix ) ),
3506 'cl_timestamp=cl_timestamp' ),
3507 array(
3508 'cl_from' => $pageid,
3509 'cl_to' => $catTo ),
3510 __METHOD__
3514 $redirid = $this->getArticleID();
3516 if ( $protected ) {
3517 # Protect the redirect title as the title used to be...
3518 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3519 array(
3520 'pr_page' => $redirid,
3521 'pr_type' => 'pr_type',
3522 'pr_level' => 'pr_level',
3523 'pr_cascade' => 'pr_cascade',
3524 'pr_user' => 'pr_user',
3525 'pr_expiry' => 'pr_expiry'
3527 array( 'pr_page' => $pageid ),
3528 __METHOD__,
3529 array( 'IGNORE' )
3531 # Update the protection log
3532 $log = new LogPage( 'protect' );
3533 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3534 if ( $reason ) {
3535 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3537 // @todo FIXME: $params?
3538 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3541 # Update watchlists
3542 $oldnamespace = $this->getNamespace() & ~1;
3543 $newnamespace = $nt->getNamespace() & ~1;
3544 $oldtitle = $this->getDBkey();
3545 $newtitle = $nt->getDBkey();
3547 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3548 WatchedItem::duplicateEntries( $this, $nt );
3551 $dbw->commit();
3553 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3554 return true;
3558 * Move page to a title which is either a redirect to the
3559 * source page or nonexistent
3561 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3562 * @param $reason String The reason for the move
3563 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3564 * if the user doesn't have the suppressredirect right
3566 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3567 global $wgUser, $wgContLang;
3569 if ( $nt->exists() ) {
3570 $moveOverRedirect = true;
3571 $logType = 'move_redir';
3572 } else {
3573 $moveOverRedirect = false;
3574 $logType = 'move';
3577 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3579 $logEntry = new ManualLogEntry( 'move', $logType );
3580 $logEntry->setPerformer( $wgUser );
3581 $logEntry->setTarget( $this );
3582 $logEntry->setComment( $reason );
3583 $logEntry->setParameters( array(
3584 '4::target' => $nt->getPrefixedText(),
3585 '5::noredir' => $redirectSuppressed ? '1': '0',
3586 ) );
3588 $formatter = LogFormatter::newFromEntry( $logEntry );
3589 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3590 $comment = $formatter->getPlainActionText();
3591 if ( $reason ) {
3592 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3594 # Truncate for whole multibyte characters.
3595 $comment = $wgContLang->truncate( $comment, 255 );
3597 $oldid = $this->getArticleID();
3598 $latest = $this->getLatestRevID();
3600 $dbw = wfGetDB( DB_MASTER );
3602 $newpage = WikiPage::factory( $nt );
3604 if ( $moveOverRedirect ) {
3605 $newid = $nt->getArticleID();
3607 # Delete the old redirect. We don't save it to history since
3608 # by definition if we've got here it's rather uninteresting.
3609 # We have to remove it so that the next step doesn't trigger
3610 # a conflict on the unique namespace+title index...
3611 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3613 $newpage->doDeleteUpdates( $newid );
3616 # Save a null revision in the page's history notifying of the move
3617 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3618 if ( !is_object( $nullRevision ) ) {
3619 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3621 $nullRevId = $nullRevision->insertOn( $dbw );
3623 # Change the name of the target page:
3624 $dbw->update( 'page',
3625 /* SET */ array(
3626 'page_namespace' => $nt->getNamespace(),
3627 'page_title' => $nt->getDBkey(),
3629 /* WHERE */ array( 'page_id' => $oldid ),
3630 __METHOD__
3633 $this->resetArticleID( 0 );
3634 $nt->resetArticleID( $oldid );
3636 $newpage->updateRevisionOn( $dbw, $nullRevision );
3638 wfRunHooks( 'NewRevisionFromEditComplete',
3639 array( $newpage, $nullRevision, $latest, $wgUser ) );
3641 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3643 # Recreate the redirect, this time in the other direction.
3644 if ( $redirectSuppressed ) {
3645 WikiPage::onArticleDelete( $this );
3646 } else {
3647 $mwRedir = MagicWord::get( 'redirect' );
3648 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3649 $redirectArticle = WikiPage::factory( $this );
3650 $newid = $redirectArticle->insertOn( $dbw );
3651 if ( $newid ) { // sanity
3652 $redirectRevision = new Revision( array(
3653 'page' => $newid,
3654 'comment' => $comment,
3655 'text' => $redirectText ) );
3656 $redirectRevision->insertOn( $dbw );
3657 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3659 wfRunHooks( 'NewRevisionFromEditComplete',
3660 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3662 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3666 # Log the move
3667 $logid = $logEntry->insert();
3668 $logEntry->publish( $logid );
3672 * Move this page's subpages to be subpages of $nt
3674 * @param $nt Title Move target
3675 * @param $auth bool Whether $wgUser's permissions should be checked
3676 * @param $reason string The reason for the move
3677 * @param $createRedirect bool Whether to create redirects from the old subpages to
3678 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3679 * @return mixed array with old page titles as keys, and strings (new page titles) or
3680 * arrays (errors) as values, or an error array with numeric indices if no pages
3681 * were moved
3683 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3684 global $wgMaximumMovedPages;
3685 // Check permissions
3686 if ( !$this->userCan( 'move-subpages' ) ) {
3687 return array( 'cant-move-subpages' );
3689 // Do the source and target namespaces support subpages?
3690 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3691 return array( 'namespace-nosubpages',
3692 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3694 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3695 return array( 'namespace-nosubpages',
3696 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3699 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3700 $retval = array();
3701 $count = 0;
3702 foreach ( $subpages as $oldSubpage ) {
3703 $count++;
3704 if ( $count > $wgMaximumMovedPages ) {
3705 $retval[$oldSubpage->getPrefixedTitle()] =
3706 array( 'movepage-max-pages',
3707 $wgMaximumMovedPages );
3708 break;
3711 // We don't know whether this function was called before
3712 // or after moving the root page, so check both
3713 // $this and $nt
3714 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3715 $oldSubpage->getArticleID() == $nt->getArticleId() )
3717 // When moving a page to a subpage of itself,
3718 // don't move it twice
3719 continue;
3721 $newPageName = preg_replace(
3722 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3723 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3724 $oldSubpage->getDBkey() );
3725 if ( $oldSubpage->isTalkPage() ) {
3726 $newNs = $nt->getTalkPage()->getNamespace();
3727 } else {
3728 $newNs = $nt->getSubjectPage()->getNamespace();
3730 # Bug 14385: we need makeTitleSafe because the new page names may
3731 # be longer than 255 characters.
3732 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3734 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3735 if ( $success === true ) {
3736 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3737 } else {
3738 $retval[$oldSubpage->getPrefixedText()] = $success;
3741 return $retval;
3745 * Checks if this page is just a one-rev redirect.
3746 * Adds lock, so don't use just for light purposes.
3748 * @return Bool
3750 public function isSingleRevRedirect() {
3751 $dbw = wfGetDB( DB_MASTER );
3752 # Is it a redirect?
3753 $row = $dbw->selectRow( 'page',
3754 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3755 $this->pageCond(),
3756 __METHOD__,
3757 array( 'FOR UPDATE' )
3759 # Cache some fields we may want
3760 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3761 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3762 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3763 if ( !$this->mRedirect ) {
3764 return false;
3766 # Does the article have a history?
3767 $row = $dbw->selectField( array( 'page', 'revision' ),
3768 'rev_id',
3769 array( 'page_namespace' => $this->getNamespace(),
3770 'page_title' => $this->getDBkey(),
3771 'page_id=rev_page',
3772 'page_latest != rev_id'
3774 __METHOD__,
3775 array( 'FOR UPDATE' )
3777 # Return true if there was no history
3778 return ( $row === false );
3782 * Checks if $this can be moved to a given Title
3783 * - Selects for update, so don't call it unless you mean business
3785 * @param $nt Title the new title to check
3786 * @return Bool
3788 public function isValidMoveTarget( $nt ) {
3789 # Is it an existing file?
3790 if ( $nt->getNamespace() == NS_FILE ) {
3791 $file = wfLocalFile( $nt );
3792 if ( $file->exists() ) {
3793 wfDebug( __METHOD__ . ": file exists\n" );
3794 return false;
3797 # Is it a redirect with no history?
3798 if ( !$nt->isSingleRevRedirect() ) {
3799 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3800 return false;
3802 # Get the article text
3803 $rev = Revision::newFromTitle( $nt );
3804 if( !is_object( $rev ) ){
3805 return false;
3807 $text = $rev->getText();
3808 # Does the redirect point to the source?
3809 # Or is it a broken self-redirect, usually caused by namespace collisions?
3810 $m = array();
3811 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3812 $redirTitle = Title::newFromText( $m[1] );
3813 if ( !is_object( $redirTitle ) ||
3814 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3815 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3816 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3817 return false;
3819 } else {
3820 # Fail safe
3821 wfDebug( __METHOD__ . ": failsafe\n" );
3822 return false;
3824 return true;
3828 * Get categories to which this Title belongs and return an array of
3829 * categories' names.
3831 * @return Array of parents in the form:
3832 * $parent => $currentarticle
3834 public function getParentCategories() {
3835 global $wgContLang;
3837 $data = array();
3839 $titleKey = $this->getArticleId();
3841 if ( $titleKey === 0 ) {
3842 return $data;
3845 $dbr = wfGetDB( DB_SLAVE );
3847 $res = $dbr->select( 'categorylinks', '*',
3848 array(
3849 'cl_from' => $titleKey,
3851 __METHOD__,
3852 array()
3855 if ( $dbr->numRows( $res ) > 0 ) {
3856 foreach ( $res as $row ) {
3857 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3858 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3861 return $data;
3865 * Get a tree of parent categories
3867 * @param $children Array with the children in the keys, to check for circular refs
3868 * @return Array Tree of parent categories
3870 public function getParentCategoryTree( $children = array() ) {
3871 $stack = array();
3872 $parents = $this->getParentCategories();
3874 if ( $parents ) {
3875 foreach ( $parents as $parent => $current ) {
3876 if ( array_key_exists( $parent, $children ) ) {
3877 # Circular reference
3878 $stack[$parent] = array();
3879 } else {
3880 $nt = Title::newFromText( $parent );
3881 if ( $nt ) {
3882 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3888 return $stack;
3892 * Get an associative array for selecting this title from
3893 * the "page" table
3895 * @return Array suitable for the $where parameter of DB::select()
3897 public function pageCond() {
3898 if ( $this->mArticleID > 0 ) {
3899 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3900 return array( 'page_id' => $this->mArticleID );
3901 } else {
3902 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3907 * Get the revision ID of the previous revision
3909 * @param $revId Int Revision ID. Get the revision that was before this one.
3910 * @param $flags Int Title::GAID_FOR_UPDATE
3911 * @return Int|Bool Old revision ID, or FALSE if none exists
3913 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3914 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3915 return $db->selectField( 'revision', 'rev_id',
3916 array(
3917 'rev_page' => $this->getArticleId( $flags ),
3918 'rev_id < ' . intval( $revId )
3920 __METHOD__,
3921 array( 'ORDER BY' => 'rev_id DESC' )
3926 * Get the revision ID of the next revision
3928 * @param $revId Int Revision ID. Get the revision that was after this one.
3929 * @param $flags Int Title::GAID_FOR_UPDATE
3930 * @return Int|Bool Next revision ID, or FALSE if none exists
3932 public function getNextRevisionID( $revId, $flags = 0 ) {
3933 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3934 return $db->selectField( 'revision', 'rev_id',
3935 array(
3936 'rev_page' => $this->getArticleId( $flags ),
3937 'rev_id > ' . intval( $revId )
3939 __METHOD__,
3940 array( 'ORDER BY' => 'rev_id' )
3945 * Get the first revision of the page
3947 * @param $flags Int Title::GAID_FOR_UPDATE
3948 * @return Revision|Null if page doesn't exist
3950 public function getFirstRevision( $flags = 0 ) {
3951 $pageId = $this->getArticleId( $flags );
3952 if ( $pageId ) {
3953 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3954 $row = $db->selectRow( 'revision', '*',
3955 array( 'rev_page' => $pageId ),
3956 __METHOD__,
3957 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3959 if ( $row ) {
3960 return new Revision( $row );
3963 return null;
3967 * Get the oldest revision timestamp of this page
3969 * @param $flags Int Title::GAID_FOR_UPDATE
3970 * @return String: MW timestamp
3972 public function getEarliestRevTime( $flags = 0 ) {
3973 $rev = $this->getFirstRevision( $flags );
3974 return $rev ? $rev->getTimestamp() : null;
3978 * Check if this is a new page
3980 * @return bool
3982 public function isNewPage() {
3983 $dbr = wfGetDB( DB_SLAVE );
3984 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3988 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3990 * @return bool
3992 public function isBigDeletion() {
3993 global $wgDeleteRevisionsLimit;
3995 if ( !$wgDeleteRevisionsLimit ) {
3996 return false;
3999 $revCount = $this->estimateRevisionCount();
4000 return $revCount > $wgDeleteRevisionsLimit;
4004 * Get the approximate revision count of this page.
4006 * @return int
4008 public function estimateRevisionCount() {
4009 if ( !$this->exists() ) {
4010 return 0;
4013 if ( $this->mEstimateRevisions === null ) {
4014 $dbr = wfGetDB( DB_SLAVE );
4015 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4016 array( 'rev_page' => $this->getArticleId() ), __METHOD__ );
4019 return $this->mEstimateRevisions;
4023 * Get the number of revisions between the given revision.
4024 * Used for diffs and other things that really need it.
4026 * @param $old int|Revision Old revision or rev ID (first before range)
4027 * @param $new int|Revision New revision or rev ID (first after range)
4028 * @return Int Number of revisions between these revisions.
4030 public function countRevisionsBetween( $old, $new ) {
4031 if ( !( $old instanceof Revision ) ) {
4032 $old = Revision::newFromTitle( $this, (int)$old );
4034 if ( !( $new instanceof Revision ) ) {
4035 $new = Revision::newFromTitle( $this, (int)$new );
4037 if ( !$old || !$new ) {
4038 return 0; // nothing to compare
4040 $dbr = wfGetDB( DB_SLAVE );
4041 return (int)$dbr->selectField( 'revision', 'count(*)',
4042 array(
4043 'rev_page' => $this->getArticleId(),
4044 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4045 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4047 __METHOD__
4052 * Get the number of authors between the given revision IDs.
4053 * Used for diffs and other things that really need it.
4055 * @param $old int|Revision Old revision or rev ID (first before range)
4056 * @param $new int|Revision New revision or rev ID (first after range)
4057 * @param $limit Int Maximum number of authors
4058 * @return Int Number of revision authors between these revisions.
4060 public function countAuthorsBetween( $old, $new, $limit ) {
4061 if ( !( $old instanceof Revision ) ) {
4062 $old = Revision::newFromTitle( $this, (int)$old );
4064 if ( !( $new instanceof Revision ) ) {
4065 $new = Revision::newFromTitle( $this, (int)$new );
4067 if ( !$old || !$new ) {
4068 return 0; // nothing to compare
4070 $dbr = wfGetDB( DB_SLAVE );
4071 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4072 array(
4073 'rev_page' => $this->getArticleID(),
4074 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4075 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4076 ), __METHOD__,
4077 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4079 return (int)$dbr->numRows( $res );
4083 * Compare with another title.
4085 * @param $title Title
4086 * @return Bool
4088 public function equals( Title $title ) {
4089 // Note: === is necessary for proper matching of number-like titles.
4090 return $this->getInterwiki() === $title->getInterwiki()
4091 && $this->getNamespace() == $title->getNamespace()
4092 && $this->getDBkey() === $title->getDBkey();
4096 * Check if this title is a subpage of another title
4098 * @param $title Title
4099 * @return Bool
4101 public function isSubpageOf( Title $title ) {
4102 return $this->getInterwiki() === $title->getInterwiki()
4103 && $this->getNamespace() == $title->getNamespace()
4104 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4108 * Check if page exists. For historical reasons, this function simply
4109 * checks for the existence of the title in the page table, and will
4110 * thus return false for interwiki links, special pages and the like.
4111 * If you want to know if a title can be meaningfully viewed, you should
4112 * probably call the isKnown() method instead.
4114 * @return Bool
4116 public function exists() {
4117 return $this->getArticleId() != 0;
4121 * Should links to this title be shown as potentially viewable (i.e. as
4122 * "bluelinks"), even if there's no record by this title in the page
4123 * table?
4125 * This function is semi-deprecated for public use, as well as somewhat
4126 * misleadingly named. You probably just want to call isKnown(), which
4127 * calls this function internally.
4129 * (ISSUE: Most of these checks are cheap, but the file existence check
4130 * can potentially be quite expensive. Including it here fixes a lot of
4131 * existing code, but we might want to add an optional parameter to skip
4132 * it and any other expensive checks.)
4134 * @return Bool
4136 public function isAlwaysKnown() {
4137 $isKnown = null;
4140 * Allows overriding default behaviour for determining if a page exists.
4141 * If $isKnown is kept as null, regular checks happen. If it's
4142 * a boolean, this value is returned by the isKnown method.
4144 * @since 1.20
4146 * @param Title $title
4147 * @param boolean|null $isKnown
4149 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4151 if ( !is_null( $isKnown ) ) {
4152 return $isKnown;
4155 if ( $this->mInterwiki != '' ) {
4156 return true; // any interwiki link might be viewable, for all we know
4159 switch( $this->mNamespace ) {
4160 case NS_MEDIA:
4161 case NS_FILE:
4162 // file exists, possibly in a foreign repo
4163 return (bool)wfFindFile( $this );
4164 case NS_SPECIAL:
4165 // valid special page
4166 return SpecialPageFactory::exists( $this->getDBkey() );
4167 case NS_MAIN:
4168 // selflink, possibly with fragment
4169 return $this->mDbkeyform == '';
4170 case NS_MEDIAWIKI:
4171 // known system message
4172 return $this->hasSourceText() !== false;
4173 default:
4174 return false;
4179 * Does this title refer to a page that can (or might) be meaningfully
4180 * viewed? In particular, this function may be used to determine if
4181 * links to the title should be rendered as "bluelinks" (as opposed to
4182 * "redlinks" to non-existent pages).
4183 * Adding something else to this function will cause inconsistency
4184 * since LinkHolderArray calls isAlwaysKnown() and does its own
4185 * page existence check.
4187 * @return Bool
4189 public function isKnown() {
4190 return $this->isAlwaysKnown() || $this->exists();
4194 * Does this page have source text?
4196 * @return Boolean
4198 public function hasSourceText() {
4199 if ( $this->exists() ) {
4200 return true;
4203 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4204 // If the page doesn't exist but is a known system message, default
4205 // message content will be displayed, same for language subpages-
4206 // Use always content language to avoid loading hundreds of languages
4207 // to get the link color.
4208 global $wgContLang;
4209 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4210 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4211 return $message->exists();
4214 return false;
4218 * Get the default message text or false if the message doesn't exist
4220 * @return String or false
4222 public function getDefaultMessageText() {
4223 global $wgContLang;
4225 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4226 return false;
4229 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4230 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4232 if ( $message->exists() ) {
4233 return $message->plain();
4234 } else {
4235 return false;
4240 * Updates page_touched for this page; called from LinksUpdate.php
4242 * @return Bool true if the update succeded
4244 public function invalidateCache() {
4245 if ( wfReadOnly() ) {
4246 return false;
4248 $dbw = wfGetDB( DB_MASTER );
4249 $success = $dbw->update(
4250 'page',
4251 array( 'page_touched' => $dbw->timestamp() ),
4252 $this->pageCond(),
4253 __METHOD__
4255 HTMLFileCache::clearFileCache( $this );
4256 return $success;
4260 * Update page_touched timestamps and send squid purge messages for
4261 * pages linking to this title. May be sent to the job queue depending
4262 * on the number of links. Typically called on create and delete.
4264 public function touchLinks() {
4265 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4266 $u->doUpdate();
4268 if ( $this->getNamespace() == NS_CATEGORY ) {
4269 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4270 $u->doUpdate();
4275 * Get the last touched timestamp
4277 * @param $db DatabaseBase: optional db
4278 * @return String last-touched timestamp
4280 public function getTouched( $db = null ) {
4281 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4282 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4283 return $touched;
4287 * Get the timestamp when this page was updated since the user last saw it.
4289 * @param $user User
4290 * @return String|Null
4292 public function getNotificationTimestamp( $user = null ) {
4293 global $wgUser, $wgShowUpdatedMarker;
4294 // Assume current user if none given
4295 if ( !$user ) {
4296 $user = $wgUser;
4298 // Check cache first
4299 $uid = $user->getId();
4300 // avoid isset here, as it'll return false for null entries
4301 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4302 return $this->mNotificationTimestamp[$uid];
4304 if ( !$uid || !$wgShowUpdatedMarker ) {
4305 return $this->mNotificationTimestamp[$uid] = false;
4307 // Don't cache too much!
4308 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4309 $this->mNotificationTimestamp = array();
4311 $dbr = wfGetDB( DB_SLAVE );
4312 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4313 'wl_notificationtimestamp',
4314 array( 'wl_namespace' => $this->getNamespace(),
4315 'wl_title' => $this->getDBkey(),
4316 'wl_user' => $user->getId()
4318 __METHOD__
4320 return $this->mNotificationTimestamp[$uid];
4324 * Generate strings used for xml 'id' names in monobook tabs
4326 * @param $prepend string defaults to 'nstab-'
4327 * @return String XML 'id' name
4329 public function getNamespaceKey( $prepend = 'nstab-' ) {
4330 global $wgContLang;
4331 // Gets the subject namespace if this title
4332 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4333 // Checks if cononical namespace name exists for namespace
4334 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4335 // Uses canonical namespace name
4336 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4337 } else {
4338 // Uses text of namespace
4339 $namespaceKey = $this->getSubjectNsText();
4341 // Makes namespace key lowercase
4342 $namespaceKey = $wgContLang->lc( $namespaceKey );
4343 // Uses main
4344 if ( $namespaceKey == '' ) {
4345 $namespaceKey = 'main';
4347 // Changes file to image for backwards compatibility
4348 if ( $namespaceKey == 'file' ) {
4349 $namespaceKey = 'image';
4351 return $prepend . $namespaceKey;
4355 * Get all extant redirects to this Title
4357 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4358 * @return Array of Title redirects to this title
4360 public function getRedirectsHere( $ns = null ) {
4361 $redirs = array();
4363 $dbr = wfGetDB( DB_SLAVE );
4364 $where = array(
4365 'rd_namespace' => $this->getNamespace(),
4366 'rd_title' => $this->getDBkey(),
4367 'rd_from = page_id'
4369 if ( !is_null( $ns ) ) {
4370 $where['page_namespace'] = $ns;
4373 $res = $dbr->select(
4374 array( 'redirect', 'page' ),
4375 array( 'page_namespace', 'page_title' ),
4376 $where,
4377 __METHOD__
4380 foreach ( $res as $row ) {
4381 $redirs[] = self::newFromRow( $row );
4383 return $redirs;
4387 * Check if this Title is a valid redirect target
4389 * @return Bool
4391 public function isValidRedirectTarget() {
4392 global $wgInvalidRedirectTargets;
4394 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4395 if ( $this->isSpecial( 'Userlogout' ) ) {
4396 return false;
4399 foreach ( $wgInvalidRedirectTargets as $target ) {
4400 if ( $this->isSpecial( $target ) ) {
4401 return false;
4405 return true;
4409 * Get a backlink cache object
4411 * @return BacklinkCache
4413 function getBacklinkCache() {
4414 if ( is_null( $this->mBacklinkCache ) ) {
4415 $this->mBacklinkCache = new BacklinkCache( $this );
4417 return $this->mBacklinkCache;
4421 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4423 * @return Boolean
4425 public function canUseNoindex() {
4426 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4428 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4429 ? $wgContentNamespaces
4430 : $wgExemptFromUserRobotsControl;
4432 return !in_array( $this->mNamespace, $bannedNamespaces );
4437 * Returns the raw sort key to be used for categories, with the specified
4438 * prefix. This will be fed to Collation::getSortKey() to get a
4439 * binary sortkey that can be used for actual sorting.
4441 * @param $prefix string The prefix to be used, specified using
4442 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4443 * prefix.
4444 * @return string
4446 public function getCategorySortkey( $prefix = '' ) {
4447 $unprefixed = $this->getText();
4449 // Anything that uses this hook should only depend
4450 // on the Title object passed in, and should probably
4451 // tell the users to run updateCollations.php --force
4452 // in order to re-sort existing category relations.
4453 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4454 if ( $prefix !== '' ) {
4455 # Separate with a line feed, so the unprefixed part is only used as
4456 # a tiebreaker when two pages have the exact same prefix.
4457 # In UCA, tab is the only character that can sort above LF
4458 # so we strip both of them from the original prefix.
4459 $prefix = strtr( $prefix, "\n\t", ' ' );
4460 return "$prefix\n$unprefixed";
4462 return $unprefixed;
4466 * Get the language in which the content of this page is written.
4467 * Defaults to $wgContLang, but in certain cases it can be e.g.
4468 * $wgLang (such as special pages, which are in the user language).
4470 * @since 1.18
4471 * @return object Language
4473 public function getPageLanguage() {
4474 global $wgLang;
4475 if ( $this->isSpecialPage() ) {
4476 // special pages are in the user language
4477 return $wgLang;
4478 } elseif ( $this->isCssOrJsPage() ) {
4479 // css/js should always be LTR and is, in fact, English
4480 return wfGetLangObj( 'en' );
4481 } elseif ( $this->getNamespace() == NS_MEDIAWIKI ) {
4482 // Parse mediawiki messages with correct target language
4483 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $this->getText() );
4484 return wfGetLangObj( $lang );
4486 global $wgContLang;
4487 // If nothing special, it should be in the wiki content language
4488 $pageLang = $wgContLang;
4489 // Hook at the end because we don't want to override the above stuff
4490 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4491 return wfGetLangObj( $pageLang );