Localisation updates for core and extension messages from translatewiki.net (2011...
[mediawiki.git] / includes / Title.php
blobd69610f4f41df4f6550c20e1efd3d5c8a5e2a4a6
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
7 /**
8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname( __FILE__ ) . '/normal/UtfNormal.php' );
16 /**
17 * @deprecated This used to be a define, but was moved to
18 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
20 define( 'GAID_FOR_UPDATE', Title::GAID_FOR_UPDATE );
22 /**
23 * Represents a title within MediaWiki.
24 * Optionally may contain an interwiki designation or namespace.
25 * @note This class can fetch various kinds of data from the database;
26 * however, it does so inefficiently.
28 * @internal documentation reviewed 15 Mar 2010
30 class Title {
31 /** @name Static cache variables */
32 // @{
33 static private $titleCache = array();
34 // @}
36 /**
37 * Title::newFromText maintains a cache to avoid expensive re-normalization of
38 * commonly used titles. On a batch operation this can become a memory leak
39 * if not bounded. After hitting this many titles reset the cache.
41 const CACHE_MAX = 1000;
43 /**
44 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
45 * to use the master DB
47 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 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
67 var $mOldRestrictions = false;
68 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
69 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
70 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
71 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
72 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
73 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
74 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
75 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
76 # Don't change the following default, NS_MAIN is hardcoded in several
77 # places. See bug 696.
78 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
79 # Zero except in {{transclusion}} tags
80 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
81 var $mLength = -1; // /< The page length, 0 for special pages
82 var $mRedirect = null; // /< Is the article at this title a redirect?
83 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
84 var $mBacklinkCache = null; // /< Cache of links to this title
85 // @}
88 /**
89 * Constructor
90 * @private
92 /* private */ 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 );
256 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
257 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
258 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
259 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
261 return $t;
265 * Create a new Title from a namespace index and a DB key.
266 * It's assumed that $ns and $title are *valid*, for instance when
267 * they came directly from the database or a special page name.
268 * For convenience, spaces are converted to underscores so that
269 * eg user_text fields can be used directly.
271 * @param $ns Int the namespace of the article
272 * @param $title String the unprefixed database key form
273 * @param $fragment String the link fragment (after the "#")
274 * @param $interwiki String the interwiki prefix
275 * @return Title the new object
277 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
278 $t = new Title();
279 $t->mInterwiki = $interwiki;
280 $t->mFragment = $fragment;
281 $t->mNamespace = $ns = intval( $ns );
282 $t->mDbkeyform = str_replace( ' ', '_', $title );
283 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
284 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
285 $t->mTextform = str_replace( '_', ' ', $title );
286 return $t;
290 * Create a new Title from a namespace index and a DB key.
291 * The parameters will be checked for validity, which is a bit slower
292 * than makeTitle() but safer for user-provided data.
294 * @param $ns Int the namespace of the article
295 * @param $title String database key form
296 * @param $fragment String the link fragment (after the "#")
297 * @param $interwiki String interwiki prefix
298 * @return Title the new object, or NULL on an error
300 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
301 $t = new Title();
302 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
303 if ( $t->secureAndSplit() ) {
304 return $t;
305 } else {
306 return null;
311 * Create a new Title for the Main Page
313 * @return Title the new object
315 public static function newMainPage() {
316 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
317 // Don't give fatal errors if the message is broken
318 if ( !$title ) {
319 $title = Title::newFromText( 'Main Page' );
321 return $title;
325 * Extract a redirect destination from a string and return the
326 * Title, or null if the text doesn't contain a valid redirect
327 * This will only return the very next target, useful for
328 * the redirect table and other checks that don't need full recursion
330 * @param $text String: Text with possible redirect
331 * @return Title: The corresponding Title
333 public static function newFromRedirect( $text ) {
334 return self::newFromRedirectInternal( $text );
338 * Extract a redirect destination from a string and return the
339 * Title, or null if the text doesn't contain a valid redirect
340 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
341 * in order to provide (hopefully) the Title of the final destination instead of another redirect
343 * @param $text String Text with possible redirect
344 * @return Title
346 public static function newFromRedirectRecurse( $text ) {
347 $titles = self::newFromRedirectArray( $text );
348 return $titles ? array_pop( $titles ) : null;
352 * Extract a redirect destination from a string and return an
353 * array of Titles, or null if the text doesn't contain a valid redirect
354 * The last element in the array is the final destination after all redirects
355 * have been resolved (up to $wgMaxRedirects times)
357 * @param $text String Text with possible redirect
358 * @return Array of Titles, with the destination last
360 public static function newFromRedirectArray( $text ) {
361 global $wgMaxRedirects;
362 $title = self::newFromRedirectInternal( $text );
363 if ( is_null( $title ) ) {
364 return null;
366 // recursive check to follow double redirects
367 $recurse = $wgMaxRedirects;
368 $titles = array( $title );
369 while ( --$recurse > 0 ) {
370 if ( $title->isRedirect() ) {
371 $article = new Article( $title, 0 );
372 $newtitle = $article->getRedirectTarget();
373 } else {
374 break;
376 // Redirects to some special pages are not permitted
377 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
378 // the new title passes the checks, so make that our current title so that further recursion can be checked
379 $title = $newtitle;
380 $titles[] = $newtitle;
381 } else {
382 break;
385 return $titles;
389 * Really extract the redirect destination
390 * Do not call this function directly, use one of the newFromRedirect* functions above
392 * @param $text String Text with possible redirect
393 * @return Title
395 protected static function newFromRedirectInternal( $text ) {
396 global $wgMaxRedirects;
397 if ( $wgMaxRedirects < 1 ) {
398 //redirects are disabled, so quit early
399 return null;
401 $redir = MagicWord::get( 'redirect' );
402 $text = trim( $text );
403 if ( $redir->matchStartAndRemove( $text ) ) {
404 // Extract the first link and see if it's usable
405 // Ensure that it really does come directly after #REDIRECT
406 // Some older redirects included a colon, so don't freak about that!
407 $m = array();
408 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
409 // Strip preceding colon used to "escape" categories, etc.
410 // and URL-decode links
411 if ( strpos( $m[1], '%' ) !== false ) {
412 // Match behavior of inline link parsing here;
413 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
415 $title = Title::newFromText( $m[1] );
416 // If the title is a redirect to bad special pages or is invalid, return null
417 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
418 return null;
420 return $title;
423 return null;
426 # ----------------------------------------------------------------------------
427 # Static functions
428 # ----------------------------------------------------------------------------
431 * Get the prefixed DB key associated with an ID
433 * @param $id Int the page_id of the article
434 * @return Title an object representing the article, or NULL if no such article was found
436 public static function nameOf( $id ) {
437 $dbr = wfGetDB( DB_SLAVE );
439 $s = $dbr->selectRow(
440 'page',
441 array( 'page_namespace', 'page_title' ),
442 array( 'page_id' => $id ),
443 __METHOD__
445 if ( $s === false ) {
446 return null;
449 $n = self::makeName( $s->page_namespace, $s->page_title );
450 return $n;
454 * Get a regex character class describing the legal characters in a link
456 * @return String the list of characters, not delimited
458 public static function legalChars() {
459 global $wgLegalTitleChars;
460 return $wgLegalTitleChars;
464 * Get a string representation of a title suitable for
465 * including in a search index
467 * @param $ns Int a namespace index
468 * @param $title String text-form main part
469 * @return String a stripped-down title string ready for the search index
471 public static function indexTitle( $ns, $title ) {
472 global $wgContLang;
474 $lc = SearchEngine::legalSearchChars() . '&#;';
475 $t = $wgContLang->normalizeForSearch( $title );
476 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
477 $t = $wgContLang->lc( $t );
479 # Handle 's, s'
480 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
481 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
483 $t = preg_replace( "/\\s+/", ' ', $t );
485 if ( $ns == NS_FILE ) {
486 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
488 return trim( $t );
492 * Make a prefixed DB key from a DB key and a namespace index
494 * @param $ns Int numerical representation of the namespace
495 * @param $title String the DB key form the title
496 * @param $fragment String The link fragment (after the "#")
497 * @param $interwiki String The interwiki prefix
498 * @return String the prefixed form of the title
500 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
501 global $wgContLang;
503 $namespace = $wgContLang->getNsText( $ns );
504 $name = $namespace == '' ? $title : "$namespace:$title";
505 if ( strval( $interwiki ) != '' ) {
506 $name = "$interwiki:$name";
508 if ( strval( $fragment ) != '' ) {
509 $name .= '#' . $fragment;
511 return $name;
515 * Determine whether the object refers to a page within
516 * this project.
518 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
520 public function isLocal() {
521 if ( $this->mInterwiki != '' ) {
522 return Interwiki::fetch( $this->mInterwiki )->isLocal();
523 } else {
524 return true;
529 * Determine whether the object refers to a page within
530 * this project and is transcludable.
532 * @return Bool TRUE if this is transcludable
534 public function isTrans() {
535 if ( $this->mInterwiki == '' ) {
536 return false;
539 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
543 * Returns the DB name of the distant wiki which owns the object.
545 * @return String the DB name
547 public function getTransWikiID() {
548 if ( $this->mInterwiki == '' ) {
549 return false;
552 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
556 * Escape a text fragment, say from a link, for a URL
558 * @param $fragment string containing a URL or link fragment (after the "#")
559 * @return String: escaped string
561 static function escapeFragmentForURL( $fragment ) {
562 # Note that we don't urlencode the fragment. urlencoded Unicode
563 # fragments appear not to work in IE (at least up to 7) or in at least
564 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
565 # to care if they aren't encoded.
566 return Sanitizer::escapeId( $fragment, 'noninitial' );
569 # ----------------------------------------------------------------------------
570 # Other stuff
571 # ----------------------------------------------------------------------------
573 /** Simple accessors */
575 * Get the text form (spaces not underscores) of the main part
577 * @return String Main part of the title
579 public function getText() { return $this->mTextform; }
582 * Get the URL-encoded form of the main part
584 * @return String Main part of the title, URL-encoded
586 public function getPartialURL() { return $this->mUrlform; }
589 * Get the main part with underscores
591 * @return String: Main part of the title, with underscores
593 public function getDBkey() { return $this->mDbkeyform; }
596 * Get the namespace index, i.e. one of the NS_xxxx constants.
598 * @return Integer: Namespace index
600 public function getNamespace() { return $this->mNamespace; }
603 * Get the namespace text
605 * @return String: Namespace text
607 public function getNsText() {
608 global $wgContLang;
610 if ( $this->mInterwiki != '' ) {
611 // This probably shouldn't even happen. ohh man, oh yuck.
612 // But for interwiki transclusion it sometimes does.
613 // Shit. Shit shit shit.
615 // Use the canonical namespaces if possible to try to
616 // resolve a foreign namespace.
617 if ( MWNamespace::exists( $this->mNamespace ) ) {
618 return MWNamespace::getCanonicalName( $this->mNamespace );
622 if ( $wgContLang->needsGenderDistinction() &&
623 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
624 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
625 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
628 return $wgContLang->getNsText( $this->mNamespace );
632 * Get the DB key with the initial letter case as specified by the user
634 * @return String DB key
636 function getUserCaseDBKey() {
637 return $this->mUserCaseDBKey;
641 * Get the namespace text of the subject (rather than talk) page
643 * @return String Namespace text
645 public function getSubjectNsText() {
646 global $wgContLang;
647 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
651 * Get the namespace text of the talk page
653 * @return String Namespace text
655 public function getTalkNsText() {
656 global $wgContLang;
657 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
661 * Could this title have a corresponding talk page?
663 * @return Bool TRUE or FALSE
665 public function canTalk() {
666 return( MWNamespace::canTalk( $this->mNamespace ) );
670 * Get the interwiki prefix (or null string)
672 * @return String Interwiki prefix
674 public function getInterwiki() { return $this->mInterwiki; }
677 * Get the Title fragment (i.e.\ the bit after the #) in text form
679 * @return String Title fragment
681 public function getFragment() { return $this->mFragment; }
684 * Get the fragment in URL form, including the "#" character if there is one
685 * @return String Fragment in URL form
687 public function getFragmentForURL() {
688 if ( $this->mFragment == '' ) {
689 return '';
690 } else {
691 return '#' . Title::escapeFragmentForURL( $this->mFragment );
696 * Get the default namespace index, for when there is no namespace
698 * @return Int Default namespace index
700 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
703 * Get title for search index
705 * @return String a stripped-down title string ready for the
706 * search index
708 public function getIndexTitle() {
709 return Title::indexTitle( $this->mNamespace, $this->mTextform );
713 * Get the prefixed database key form
715 * @return String the prefixed title, with underscores and
716 * any interwiki and namespace prefixes
718 public function getPrefixedDBkey() {
719 $s = $this->prefix( $this->mDbkeyform );
720 $s = str_replace( ' ', '_', $s );
721 return $s;
725 * Get the prefixed title with spaces.
726 * This is the form usually used for display
728 * @return String the prefixed title, with spaces
730 public function getPrefixedText() {
731 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
732 $s = $this->prefix( $this->mTextform );
733 $s = str_replace( '_', ' ', $s );
734 $this->mPrefixedText = $s;
736 return $this->mPrefixedText;
740 * Get the prefixed title with spaces, plus any fragment
741 * (part beginning with '#')
743 * @return String the prefixed title, with spaces and the fragment, including '#'
745 public function getFullText() {
746 $text = $this->getPrefixedText();
747 if ( $this->mFragment != '' ) {
748 $text .= '#' . $this->mFragment;
750 return $text;
754 * Get the base name, i.e. the leftmost parts before the /
756 * @return String Base name
758 public function getBaseText() {
759 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
760 return $this->getText();
763 $parts = explode( '/', $this->getText() );
764 # Don't discard the real title if there's no subpage involved
765 if ( count( $parts ) > 1 ) {
766 unset( $parts[count( $parts ) - 1] );
768 return implode( '/', $parts );
772 * Get the lowest-level subpage name, i.e. the rightmost part after /
774 * @return String Subpage name
776 public function getSubpageText() {
777 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
778 return( $this->mTextform );
780 $parts = explode( '/', $this->mTextform );
781 return( $parts[count( $parts ) - 1] );
785 * Get a URL-encoded form of the subpage text
787 * @return String URL-encoded subpage name
789 public function getSubpageUrlForm() {
790 $text = $this->getSubpageText();
791 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
792 return( $text );
796 * Get a URL-encoded title (not an actual URL) including interwiki
798 * @return String the URL-encoded form
800 public function getPrefixedURL() {
801 $s = $this->prefix( $this->mDbkeyform );
802 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
803 return $s;
807 * Get a real URL referring to this title, with interwiki link and
808 * fragment
810 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
811 * links. Can be specified as an associative array as well, e.g.,
812 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
813 * @param $variant String language variant of url (for sr, zh..)
814 * @return String the URL
816 public function getFullURL( $query = '', $variant = false ) {
817 global $wgServer, $wgRequest;
819 if ( is_array( $query ) ) {
820 $query = wfArrayToCGI( $query );
823 $interwiki = Interwiki::fetch( $this->mInterwiki );
824 if ( !$interwiki ) {
825 $url = $this->getLocalURL( $query, $variant );
827 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
828 // Correct fix would be to move the prepending elsewhere.
829 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
830 $url = $wgServer . $url;
832 } else {
833 $baseUrl = $interwiki->getURL();
835 $namespace = wfUrlencode( $this->getNsText() );
836 if ( $namespace != '' ) {
837 # Can this actually happen? Interwikis shouldn't be parsed.
838 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
839 $namespace .= ':';
841 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
842 $url = wfAppendQuery( $url, $query );
845 # Finally, add the fragment.
846 $url .= $this->getFragmentForURL();
848 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
849 return $url;
853 * Get a URL with no fragment or server name. If this page is generated
854 * with action=render, $wgServer is prepended.
856 * @param $query Mixed: an optional query string; if not specified,
857 * $wgArticlePath will be used. Can be specified as an associative array
858 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
859 * URL-escaped).
860 * @param $variant String language variant of url (for sr, zh..)
861 * @return String the URL
863 public function getLocalURL( $query = '', $variant = false ) {
864 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
865 global $wgVariantArticlePath, $wgContLang;
867 if ( is_array( $query ) ) {
868 $query = wfArrayToCGI( $query );
871 if ( $this->isExternal() ) {
872 $url = $this->getFullURL();
873 if ( $query ) {
874 // This is currently only used for edit section links in the
875 // context of interwiki transclusion. In theory we should
876 // append the query to the end of any existing query string,
877 // but interwiki transclusion is already broken in that case.
878 $url .= "?$query";
880 } else {
881 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
882 if ( $query == '' ) {
883 if ( $variant != false && $wgContLang->hasVariants() ) {
884 if ( !$wgVariantArticlePath ) {
885 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
886 } else {
887 $variantArticlePath = $wgVariantArticlePath;
889 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
890 $url = str_replace( '$1', $dbkey, $url );
891 } else {
892 $url = str_replace( '$1', $dbkey, $wgArticlePath );
894 } else {
895 global $wgActionPaths;
896 $url = false;
897 $matches = array();
898 if ( !empty( $wgActionPaths ) &&
899 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
901 $action = urldecode( $matches[2] );
902 if ( isset( $wgActionPaths[$action] ) ) {
903 $query = $matches[1];
904 if ( isset( $matches[4] ) ) {
905 $query .= $matches[4];
907 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
908 if ( $query != '' ) {
909 $url = wfAppendQuery( $url, $query );
913 if ( $url === false ) {
914 if ( $query == '-' ) {
915 $query = '';
917 $url = "{$wgScript}?title={$dbkey}&{$query}";
921 // FIXME: this causes breakage in various places when we
922 // actually expected a local URL and end up with dupe prefixes.
923 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
924 $url = $wgServer . $url;
927 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
928 return $url;
932 * Get a URL that's the simplest URL that will be valid to link, locally,
933 * to the current Title. It includes the fragment, but does not include
934 * the server unless action=render is used (or the link is external). If
935 * there's a fragment but the prefixed text is empty, we just return a link
936 * to the fragment.
938 * The result obviously should not be URL-escaped, but does need to be
939 * HTML-escaped if it's being output in HTML.
941 * @param $query Array of Strings An associative array of key => value pairs for the
942 * query string. Keys and values will be escaped.
943 * @param $variant String language variant of URL (for sr, zh..). Ignored
944 * for external links. Default is "false" (same variant as current page,
945 * for anonymous users).
946 * @return String the URL
948 public function getLinkUrl( $query = array(), $variant = false ) {
949 wfProfileIn( __METHOD__ );
950 if ( $this->isExternal() ) {
951 $ret = $this->getFullURL( $query );
952 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
953 $ret = $this->getFragmentForURL();
954 } else {
955 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
957 wfProfileOut( __METHOD__ );
958 return $ret;
962 * Get an HTML-escaped version of the URL form, suitable for
963 * using in a link, without a server name or fragment
965 * @param $query String an optional query string
966 * @return String the URL
968 public function escapeLocalURL( $query = '' ) {
969 return htmlspecialchars( $this->getLocalURL( $query ) );
973 * Get an HTML-escaped version of the URL form, suitable for
974 * using in a link, including the server name and fragment
976 * @param $query String an optional query string
977 * @return String the URL
979 public function escapeFullURL( $query = '' ) {
980 return htmlspecialchars( $this->getFullURL( $query ) );
984 * Get the URL form for an internal link.
985 * - Used in various Squid-related code, in case we have a different
986 * internal hostname for the server from the exposed one.
988 * @param $query String an optional query string
989 * @param $variant String language variant of url (for sr, zh..)
990 * @return String the URL
992 public function getInternalURL( $query = '', $variant = false ) {
993 global $wgInternalServer;
994 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
995 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
996 return $url;
1000 * Get the edit URL for this Title
1002 * @return String the URL, or a null string if this is an
1003 * interwiki link
1005 public function getEditURL() {
1006 if ( $this->mInterwiki != '' ) {
1007 return '';
1009 $s = $this->getLocalURL( 'action=edit' );
1011 return $s;
1015 * Get the HTML-escaped displayable text form.
1016 * Used for the title field in <a> tags.
1018 * @return String the text, including any prefixes
1020 public function getEscapedText() {
1021 return htmlspecialchars( $this->getPrefixedText() );
1025 * Is this Title interwiki?
1027 * @return Bool
1029 public function isExternal() {
1030 return ( $this->mInterwiki != '' );
1034 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1036 * @param $action String Action to check (default: edit)
1037 * @return Bool
1039 public function isSemiProtected( $action = 'edit' ) {
1040 if ( $this->exists() ) {
1041 $restrictions = $this->getRestrictions( $action );
1042 if ( count( $restrictions ) > 0 ) {
1043 foreach ( $restrictions as $restriction ) {
1044 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1045 return false;
1048 } else {
1049 # Not protected
1050 return false;
1052 return true;
1053 } else {
1054 # If it doesn't exist, it can't be protected
1055 return false;
1060 * Does the title correspond to a protected article?
1062 * @param $action String the action the page is protected from,
1063 * by default checks all actions.
1064 * @return Bool
1066 public function isProtected( $action = '' ) {
1067 global $wgRestrictionLevels;
1069 $restrictionTypes = $this->getRestrictionTypes();
1071 # Special pages have inherent protection
1072 if( $this->getNamespace() == NS_SPECIAL ) {
1073 return true;
1076 # Check regular protection levels
1077 foreach ( $restrictionTypes as $type ) {
1078 if ( $action == $type || $action == '' ) {
1079 $r = $this->getRestrictions( $type );
1080 foreach ( $wgRestrictionLevels as $level ) {
1081 if ( in_array( $level, $r ) && $level != '' ) {
1082 return true;
1088 return false;
1092 * Is this a conversion table for the LanguageConverter?
1094 * @return Bool
1096 public function isConversionTable() {
1098 $this->getNamespace() == NS_MEDIAWIKI &&
1099 strpos( $this->getText(), 'Conversiontable' ) !== false
1102 return true;
1105 return false;
1109 * Is $wgUser watching this page?
1111 * @return Bool
1113 public function userIsWatching() {
1114 global $wgUser;
1116 if ( is_null( $this->mWatched ) ) {
1117 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1118 $this->mWatched = false;
1119 } else {
1120 $this->mWatched = $wgUser->isWatched( $this );
1123 return $this->mWatched;
1127 * Can $wgUser perform $action on this page?
1128 * This skips potentially expensive cascading permission checks
1129 * as well as avoids expensive error formatting
1131 * Suitable for use for nonessential UI controls in common cases, but
1132 * _not_ for functional access control.
1134 * May provide false positives, but should never provide a false negative.
1136 * @param $action String action that permission needs to be checked for
1137 * @return Bool
1139 public function quickUserCan( $action ) {
1140 return $this->userCan( $action, false );
1144 * Determines if $user is unable to edit this page because it has been protected
1145 * by $wgNamespaceProtection.
1147 * @param $user User object, $wgUser will be used if not passed
1148 * @return Bool
1150 public function isNamespaceProtected( User $user = null ) {
1151 global $wgNamespaceProtection;
1153 if ( $user === null ) {
1154 global $wgUser;
1155 $user = $wgUser;
1158 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1159 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1160 if ( $right != '' && !$user->isAllowed( $right ) ) {
1161 return true;
1165 return false;
1169 * Can $wgUser perform $action on this page?
1171 * @param $action String action that permission needs to be checked for
1172 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1173 * @return Bool
1175 public function userCan( $action, $doExpensiveQueries = true ) {
1176 global $wgUser;
1177 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1181 * Can $user perform $action on this page?
1183 * FIXME: This *does not* check throttles (User::pingLimiter()).
1185 * @param $action String action that permission needs to be checked for
1186 * @param $user User to check
1187 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1188 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1189 * @return Array of arguments to wfMsg to explain permissions problems.
1191 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1192 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1194 // Remove the errors being ignored.
1195 foreach ( $errors as $index => $error ) {
1196 $error_key = is_array( $error ) ? $error[0] : $error;
1198 if ( in_array( $error_key, $ignoreErrors ) ) {
1199 unset( $errors[$index] );
1203 return $errors;
1207 * Permissions checks that fail most often, and which are easiest to test.
1209 * @param $action String the action to check
1210 * @param $user User user to check
1211 * @param $errors Array list of current errors
1212 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1213 * @param $short Boolean short circuit on first error
1215 * @return Array list of errors
1217 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1218 if ( $action == 'create' ) {
1219 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1220 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1221 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1223 } elseif ( $action == 'move' ) {
1224 if ( !$user->isAllowed( 'move-rootuserpages' )
1225 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1226 // Show user page-specific message only if the user can move other pages
1227 $errors[] = array( 'cant-move-user-page' );
1230 // Check if user is allowed to move files if it's a file
1231 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1232 $errors[] = array( 'movenotallowedfile' );
1235 if ( !$user->isAllowed( 'move' ) ) {
1236 // User can't move anything
1237 global $wgGroupPermissions;
1238 $userCanMove = false;
1239 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1240 $userCanMove = $wgGroupPermissions['user']['move'];
1242 $autoconfirmedCanMove = false;
1243 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1244 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1246 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1247 // custom message if logged-in users without any special rights can move
1248 $errors[] = array( 'movenologintext' );
1249 } else {
1250 $errors[] = array( 'movenotallowed' );
1253 } elseif ( $action == 'move-target' ) {
1254 if ( !$user->isAllowed( 'move' ) ) {
1255 // User can't move anything
1256 $errors[] = array( 'movenotallowed' );
1257 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1258 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1259 // Show user page-specific message only if the user can move other pages
1260 $errors[] = array( 'cant-move-to-user-page' );
1262 } elseif ( !$user->isAllowed( $action ) ) {
1263 // We avoid expensive display logic for quickUserCan's and such
1264 $groups = false;
1265 if ( !$short ) {
1266 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1267 User::getGroupsWithPermission( $action ) );
1270 if ( $groups ) {
1271 global $wgLang;
1272 $return = array(
1273 'badaccess-groups',
1274 $wgLang->commaList( $groups ),
1275 count( $groups )
1277 } else {
1278 $return = array( 'badaccess-group0' );
1280 $errors[] = $return;
1283 return $errors;
1287 * Add the resulting error code to the errors array
1289 * @param $errors Array list of current errors
1290 * @param $result Mixed result of errors
1292 * @return Array list of errors
1294 private function resultToError( $errors, $result ) {
1295 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1296 // A single array representing an error
1297 $errors[] = $result;
1298 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1299 // A nested array representing multiple errors
1300 $errors = array_merge( $errors, $result );
1301 } else if ( $result !== '' && is_string( $result ) ) {
1302 // A string representing a message-id
1303 $errors[] = array( $result );
1304 } else if ( $result === false ) {
1305 // a generic "We don't want them to do that"
1306 $errors[] = array( 'badaccess-group0' );
1308 return $errors;
1312 * Check various permission hooks
1314 * @param $action String the action to check
1315 * @param $user User user to check
1316 * @param $errors Array list of current errors
1317 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1318 * @param $short Boolean short circuit on first error
1320 * @return Array list of errors
1322 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1323 // Use getUserPermissionsErrors instead
1324 $result = '';
1325 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1326 return $result ? array() : array( array( 'badaccess-group0' ) );
1328 // Check getUserPermissionsErrors hook
1329 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1330 $errors = $this->resultToError( $errors, $result );
1332 // Check getUserPermissionsErrorsExpensive hook
1333 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1334 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1335 $errors = $this->resultToError( $errors, $result );
1338 return $errors;
1342 * Check permissions on special pages & namespaces
1344 * @param $action String the action to check
1345 * @param $user User user to check
1346 * @param $errors Array list of current errors
1347 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1348 * @param $short Boolean short circuit on first error
1350 * @return Array list of errors
1352 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1353 # Only 'createaccount' and 'execute' can be performed on
1354 # special pages, which don't actually exist in the DB.
1355 $specialOKActions = array( 'createaccount', 'execute' );
1356 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1357 $errors[] = array( 'ns-specialprotected' );
1360 # Check $wgNamespaceProtection for restricted namespaces
1361 if ( $this->isNamespaceProtected( $user ) ) {
1362 $ns = $this->mNamespace == NS_MAIN ?
1363 wfMsg( 'nstab-main' ) : $this->getNsText();
1364 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1365 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1368 return $errors;
1372 * Check CSS/JS sub-page permissions
1374 * @param $action String the action to check
1375 * @param $user User user to check
1376 * @param $errors Array list of current errors
1377 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1378 * @param $short Boolean short circuit on first error
1380 * @return Array list of errors
1382 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1383 # Protect css/js subpages of user pages
1384 # XXX: this might be better using restrictions
1385 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1386 # and $this->userCanEditJsSubpage() from working
1387 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1388 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1389 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1390 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1391 $errors[] = array( 'customcssjsprotected' );
1392 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1393 $errors[] = array( 'customcssjsprotected' );
1397 return $errors;
1401 * Check against page_restrictions table requirements on this
1402 * page. The user must possess all required rights for this
1403 * action.
1405 * @param $action String the action to check
1406 * @param $user User user to check
1407 * @param $errors Array list of current errors
1408 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1409 * @param $short Boolean short circuit on first error
1411 * @return Array list of errors
1413 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1414 foreach ( $this->getRestrictions( $action ) as $right ) {
1415 // Backwards compatibility, rewrite sysop -> protect
1416 if ( $right == 'sysop' ) {
1417 $right = 'protect';
1419 if ( $right != '' && !$user->isAllowed( $right ) ) {
1420 // Users with 'editprotected' permission can edit protected pages
1421 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1422 // Users with 'editprotected' permission cannot edit protected pages
1423 // with cascading option turned on.
1424 if ( $this->mCascadeRestriction ) {
1425 $errors[] = array( 'protectedpagetext', $right );
1427 } else {
1428 $errors[] = array( 'protectedpagetext', $right );
1433 return $errors;
1437 * Check restrictions on cascading pages.
1439 * @param $action String the action to check
1440 * @param $user User to check
1441 * @param $errors Array list of current errors
1442 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1443 * @param $short Boolean short circuit on first error
1445 * @return Array list of errors
1447 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1448 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1449 # We /could/ use the protection level on the source page, but it's
1450 # fairly ugly as we have to establish a precedence hierarchy for pages
1451 # included by multiple cascade-protected pages. So just restrict
1452 # it to people with 'protect' permission, as they could remove the
1453 # protection anyway.
1454 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1455 # Cascading protection depends on more than this page...
1456 # Several cascading protected pages may include this page...
1457 # Check each cascading level
1458 # This is only for protection restrictions, not for all actions
1459 if ( isset( $restrictions[$action] ) ) {
1460 foreach ( $restrictions[$action] as $right ) {
1461 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1462 if ( $right != '' && !$user->isAllowed( $right ) ) {
1463 $pages = '';
1464 foreach ( $cascadingSources as $page )
1465 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1466 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1472 return $errors;
1476 * Check action permissions not already checked in checkQuickPermissions
1478 * @param $action String the action to check
1479 * @param $user User to check
1480 * @param $errors Array list of current errors
1481 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1482 * @param $short Boolean short circuit on first error
1484 * @return Array list of errors
1486 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1487 if ( $action == 'protect' ) {
1488 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1489 // If they can't edit, they shouldn't protect.
1490 $errors[] = array( 'protect-cantedit' );
1492 } elseif ( $action == 'create' ) {
1493 $title_protection = $this->getTitleProtection();
1494 if( $title_protection ) {
1495 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1496 $title_protection['pt_create_perm'] = 'protect'; // B/C
1498 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1499 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1502 } elseif ( $action == 'move' ) {
1503 // Check for immobile pages
1504 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1505 // Specific message for this case
1506 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1507 } elseif ( !$this->isMovable() ) {
1508 // Less specific message for rarer cases
1509 $errors[] = array( 'immobile-page' );
1511 } elseif ( $action == 'move-target' ) {
1512 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1513 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1514 } elseif ( !$this->isMovable() ) {
1515 $errors[] = array( 'immobile-target-page' );
1518 return $errors;
1522 * Check that the user isn't blocked from editting.
1524 * @param $action String the action to check
1525 * @param $user User to check
1526 * @param $errors Array list of current errors
1527 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1528 * @param $short Boolean short circuit on first error
1530 * @return Array list of errors
1532 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1533 if( $short && count( $errors ) > 0 ) {
1534 return $errors;
1537 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1539 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1540 $errors[] = array( 'confirmedittext' );
1543 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1544 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1545 $block = $user->mBlock;
1547 // This is from OutputPage::blockedPage
1548 // Copied at r23888 by werdna
1550 $id = $user->blockedBy();
1551 $reason = $user->blockedFor();
1552 if ( $reason == '' ) {
1553 $reason = wfMsg( 'blockednoreason' );
1555 $ip = wfGetIP();
1557 if ( is_numeric( $id ) ) {
1558 $name = User::whoIs( $id );
1559 } else {
1560 $name = $id;
1563 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1564 $blockid = $block->mId;
1565 $blockExpiry = $user->mBlock->mExpiry;
1566 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1567 if ( $blockExpiry == 'infinity' ) {
1568 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1569 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1571 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1572 if ( !strpos( $option, ':' ) )
1573 continue;
1575 list( $show, $value ) = explode( ':', $option );
1577 if ( $value == 'infinite' || $value == 'indefinite' ) {
1578 $blockExpiry = $show;
1579 break;
1582 } else {
1583 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1586 $intended = $user->mBlock->mAddress;
1588 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1589 $blockid, $blockExpiry, $intended, $blockTimestamp );
1592 return $errors;
1596 * Can $user perform $action on this page? This is an internal function,
1597 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1598 * checks on wfReadOnly() and blocks)
1600 * @param $action String action that permission needs to be checked for
1601 * @param $user User to check
1602 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1603 * @param $short Bool Set this to true to stop after the first permission error.
1604 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1606 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1607 wfProfileIn( __METHOD__ );
1609 $errors = array();
1610 $checks = array(
1611 'checkQuickPermissions',
1612 'checkPermissionHooks',
1613 'checkSpecialsAndNSPermissions',
1614 'checkCSSandJSPermissions',
1615 'checkPageRestrictions',
1616 'checkCascadingSourcesRestrictions',
1617 'checkActionPermissions',
1618 'checkUserBlock'
1621 while( count( $checks ) > 0 &&
1622 !( $short && count( $errors ) > 0 ) ) {
1623 $method = array_shift( $checks );
1624 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1627 wfProfileOut( __METHOD__ );
1628 return $errors;
1632 * Is this title subject to title protection?
1633 * Title protection is the one applied against creation of such title.
1635 * @return Mixed An associative array representing any existent title
1636 * protection, or false if there's none.
1638 private function getTitleProtection() {
1639 // Can't protect pages in special namespaces
1640 if ( $this->getNamespace() < 0 ) {
1641 return false;
1644 // Can't protect pages that exist.
1645 if ( $this->exists() ) {
1646 return false;
1649 if ( !isset( $this->mTitleProtection ) ) {
1650 $dbr = wfGetDB( DB_SLAVE );
1651 $res = $dbr->select( 'protected_titles', '*',
1652 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1653 __METHOD__ );
1655 // fetchRow returns false if there are no rows.
1656 $this->mTitleProtection = $dbr->fetchRow( $res );
1658 return $this->mTitleProtection;
1662 * Update the title protection status
1664 * @param $create_perm String Permission required for creation
1665 * @param $reason String Reason for protection
1666 * @param $expiry String Expiry timestamp
1667 * @return boolean true
1669 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1670 global $wgUser, $wgContLang;
1672 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1673 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1674 // No change
1675 return true;
1678 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1680 $dbw = wfGetDB( DB_MASTER );
1682 $encodedExpiry = Block::encodeExpiry( $expiry, $dbw );
1684 $expiry_description = '';
1685 if ( $encodedExpiry != 'infinity' ) {
1686 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1687 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1688 } else {
1689 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1692 # Update protection table
1693 if ( $create_perm != '' ) {
1694 $this->mTitleProtection = array(
1695 'pt_namespace' => $namespace,
1696 'pt_title' => $title,
1697 'pt_create_perm' => $create_perm,
1698 'pt_timestamp' => Block::encodeExpiry( wfTimestampNow(), $dbw ),
1699 'pt_expiry' => $encodedExpiry,
1700 'pt_user' => $wgUser->getId(),
1701 'pt_reason' => $reason,
1703 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1704 $this->mTitleProtection, __METHOD__ );
1705 } else {
1706 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1707 'pt_title' => $title ), __METHOD__ );
1708 $this->mTitleProtection = false;
1711 # Update the protection log
1712 if ( $dbw->affectedRows() ) {
1713 $log = new LogPage( 'protect' );
1715 if ( $create_perm ) {
1716 $params = array( "[create=$create_perm] $expiry_description", '' );
1717 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1718 } else {
1719 $log->addEntry( 'unprotect', $this, $reason );
1723 return true;
1727 * Remove any title protection due to page existing
1729 public function deleteTitleProtection() {
1730 $dbw = wfGetDB( DB_MASTER );
1732 $dbw->delete(
1733 'protected_titles',
1734 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1735 __METHOD__
1737 $this->mTitleProtection = false;
1741 * Would anybody with sufficient privileges be able to move this page?
1742 * Some pages just aren't movable.
1744 * @return Bool TRUE or FALSE
1746 public function isMovable() {
1747 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1751 * Can $wgUser read this page?
1753 * @return Bool
1754 * @todo fold these checks into userCan()
1756 public function userCanRead() {
1757 global $wgUser, $wgGroupPermissions;
1759 static $useShortcut = null;
1761 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1762 if ( is_null( $useShortcut ) ) {
1763 global $wgRevokePermissions;
1764 $useShortcut = true;
1765 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1766 # Not a public wiki, so no shortcut
1767 $useShortcut = false;
1768 } elseif ( !empty( $wgRevokePermissions ) ) {
1770 * Iterate through each group with permissions being revoked (key not included since we don't care
1771 * what the group name is), then check if the read permission is being revoked. If it is, then
1772 * we don't use the shortcut below since the user might not be able to read, even though anon
1773 * reading is allowed.
1775 foreach ( $wgRevokePermissions as $perms ) {
1776 if ( !empty( $perms['read'] ) ) {
1777 # We might be removing the read right from the user, so no shortcut
1778 $useShortcut = false;
1779 break;
1785 $result = null;
1786 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1787 if ( $result !== null ) {
1788 return $result;
1791 # Shortcut for public wikis, allows skipping quite a bit of code
1792 if ( $useShortcut ) {
1793 return true;
1796 if ( $wgUser->isAllowed( 'read' ) ) {
1797 return true;
1798 } else {
1799 global $wgWhitelistRead;
1801 # Always grant access to the login page.
1802 # Even anons need to be able to log in.
1803 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1804 return true;
1807 # Bail out if there isn't whitelist
1808 if ( !is_array( $wgWhitelistRead ) ) {
1809 return false;
1812 # Check for explicit whitelisting
1813 $name = $this->getPrefixedText();
1814 $dbName = $this->getPrefixedDBKey();
1815 // Check with and without underscores
1816 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1817 return true;
1819 # Old settings might have the title prefixed with
1820 # a colon for main-namespace pages
1821 if ( $this->getNamespace() == NS_MAIN ) {
1822 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1823 return true;
1827 # If it's a special page, ditch the subpage bit and check again
1828 if ( $this->getNamespace() == NS_SPECIAL ) {
1829 $name = $this->getDBkey();
1830 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1831 if ( $name === false ) {
1832 # Invalid special page, but we show standard login required message
1833 return false;
1836 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1837 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1838 return true;
1843 return false;
1847 * Is this the mainpage?
1848 * @note Title::newFromText seams to be sufficiently optimized by the title
1849 * cache that we don't need to over-optimize by doing direct comparisons and
1850 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1851 * ends up reporting something differently than $title->isMainPage();
1853 * @return Bool
1855 public function isMainPage() {
1856 return $this->equals( Title::newMainPage() );
1860 * Is this a talk page of some sort?
1862 * @return Bool
1864 public function isTalkPage() {
1865 return MWNamespace::isTalk( $this->getNamespace() );
1869 * Is this a subpage?
1871 * @return Bool
1873 public function isSubpage() {
1874 return MWNamespace::hasSubpages( $this->mNamespace )
1875 ? strpos( $this->getText(), '/' ) !== false
1876 : false;
1880 * Does this have subpages? (Warning, usually requires an extra DB query.)
1882 * @return Bool
1884 public function hasSubpages() {
1885 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1886 # Duh
1887 return false;
1890 # We dynamically add a member variable for the purpose of this method
1891 # alone to cache the result. There's no point in having it hanging
1892 # around uninitialized in every Title object; therefore we only add it
1893 # if needed and don't declare it statically.
1894 if ( isset( $this->mHasSubpages ) ) {
1895 return $this->mHasSubpages;
1898 $subpages = $this->getSubpages( 1 );
1899 if ( $subpages instanceof TitleArray ) {
1900 return $this->mHasSubpages = (bool)$subpages->count();
1902 return $this->mHasSubpages = false;
1906 * Get all subpages of this page.
1908 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1909 * @return mixed TitleArray, or empty array if this page's namespace
1910 * doesn't allow subpages
1912 public function getSubpages( $limit = -1 ) {
1913 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1914 return array();
1917 $dbr = wfGetDB( DB_SLAVE );
1918 $conds['page_namespace'] = $this->getNamespace();
1919 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1920 $options = array();
1921 if ( $limit > -1 ) {
1922 $options['LIMIT'] = $limit;
1924 return $this->mSubpages = TitleArray::newFromResult(
1925 $dbr->select( 'page',
1926 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1927 $conds,
1928 __METHOD__,
1929 $options
1935 * Could this page contain custom CSS or JavaScript, based
1936 * on the title?
1938 * @return Bool
1940 public function isCssOrJsPage() {
1941 return $this->mNamespace == NS_MEDIAWIKI
1942 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1946 * Is this a .css or .js subpage of a user page?
1947 * @return Bool
1949 public function isCssJsSubpage() {
1950 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1954 * Is this a *valid* .css or .js subpage of a user page?
1956 * @return Bool
1957 * @deprecated @since 1.17
1959 public function isValidCssJsSubpage() {
1960 return $this->isCssJsSubpage();
1964 * Trim down a .css or .js subpage title to get the corresponding skin name
1966 * @return string containing skin name from .css or .js subpage title
1968 public function getSkinFromCssJsSubpage() {
1969 $subpage = explode( '/', $this->mTextform );
1970 $subpage = $subpage[ count( $subpage ) - 1 ];
1971 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1975 * Is this a .css subpage of a user page?
1977 * @return Bool
1979 public function isCssSubpage() {
1980 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1984 * Is this a .js subpage of a user page?
1986 * @return Bool
1988 public function isJsSubpage() {
1989 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1993 * Protect css subpages of user pages: can $wgUser edit
1994 * this page?
1996 * @return Bool
1997 * @todo XXX: this might be better using restrictions
1999 public function userCanEditCssSubpage() {
2000 global $wgUser;
2001 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
2002 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2006 * Protect js subpages of user pages: can $wgUser edit
2007 * this page?
2009 * @return Bool
2010 * @todo XXX: this might be better using restrictions
2012 public function userCanEditJsSubpage() {
2013 global $wgUser;
2014 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
2015 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2019 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2021 * @return Bool If the page is subject to cascading restrictions.
2023 public function isCascadeProtected() {
2024 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2025 return ( $sources > 0 );
2029 * Cascading protection: Get the source of any cascading restrictions on this page.
2031 * @param $getPages Bool Whether or not to retrieve the actual pages
2032 * that the restrictions have come from.
2033 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2034 * have come, false for none, or true if such restrictions exist, but $getPages
2035 * was not set. The restriction array is an array of each type, each of which
2036 * contains a array of unique groups.
2038 public function getCascadeProtectionSources( $getPages = true ) {
2039 $pagerestrictions = array();
2041 if ( isset( $this->mCascadeSources ) && $getPages ) {
2042 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2043 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2044 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2047 wfProfileIn( __METHOD__ );
2049 $dbr = wfGetDB( DB_SLAVE );
2051 if ( $this->getNamespace() == NS_FILE ) {
2052 $tables = array( 'imagelinks', 'page_restrictions' );
2053 $where_clauses = array(
2054 'il_to' => $this->getDBkey(),
2055 'il_from=pr_page',
2056 'pr_cascade' => 1
2058 } else {
2059 $tables = array( 'templatelinks', 'page_restrictions' );
2060 $where_clauses = array(
2061 'tl_namespace' => $this->getNamespace(),
2062 'tl_title' => $this->getDBkey(),
2063 'tl_from=pr_page',
2064 'pr_cascade' => 1
2068 if ( $getPages ) {
2069 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2070 'pr_expiry', 'pr_type', 'pr_level' );
2071 $where_clauses[] = 'page_id=pr_page';
2072 $tables[] = 'page';
2073 } else {
2074 $cols = array( 'pr_expiry' );
2077 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2079 $sources = $getPages ? array() : false;
2080 $now = wfTimestampNow();
2081 $purgeExpired = false;
2083 foreach ( $res as $row ) {
2084 $expiry = Block::decodeExpiry( $row->pr_expiry );
2085 if ( $expiry > $now ) {
2086 if ( $getPages ) {
2087 $page_id = $row->pr_page;
2088 $page_ns = $row->page_namespace;
2089 $page_title = $row->page_title;
2090 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2091 # Add groups needed for each restriction type if its not already there
2092 # Make sure this restriction type still exists
2094 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2095 $pagerestrictions[$row->pr_type] = array();
2098 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2099 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2100 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2102 } else {
2103 $sources = true;
2105 } else {
2106 // Trigger lazy purge of expired restrictions from the db
2107 $purgeExpired = true;
2110 if ( $purgeExpired ) {
2111 Title::purgeExpiredRestrictions();
2114 if ( $getPages ) {
2115 $this->mCascadeSources = $sources;
2116 $this->mCascadingRestrictions = $pagerestrictions;
2117 } else {
2118 $this->mHasCascadingRestrictions = $sources;
2121 wfProfileOut( __METHOD__ );
2122 return array( $sources, $pagerestrictions );
2126 * Returns cascading restrictions for the current article
2128 * @return Boolean
2130 function areRestrictionsCascading() {
2131 if ( !$this->mRestrictionsLoaded ) {
2132 $this->loadRestrictions();
2135 return $this->mCascadeRestriction;
2139 * Loads a string into mRestrictions array
2141 * @param $res Resource restrictions as an SQL result.
2142 * @param $oldFashionedRestrictions String comma-separated list of page
2143 * restrictions from page table (pre 1.10)
2145 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2146 $rows = array();
2148 foreach ( $res as $row ) {
2149 $rows[] = $row;
2152 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2156 * Compiles list of active page restrictions from both page table (pre 1.10)
2157 * and page_restrictions table for this existing page.
2158 * Public for usage by LiquidThreads.
2160 * @param $rows array of db result objects
2161 * @param $oldFashionedRestrictions string comma-separated list of page
2162 * restrictions from page table (pre 1.10)
2164 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2165 $dbr = wfGetDB( DB_SLAVE );
2167 $restrictionTypes = $this->getRestrictionTypes();
2169 foreach ( $restrictionTypes as $type ) {
2170 $this->mRestrictions[$type] = array();
2171 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry( '' );
2174 $this->mCascadeRestriction = false;
2176 # Backwards-compatibility: also load the restrictions from the page record (old format).
2178 if ( $oldFashionedRestrictions === null ) {
2179 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2180 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2183 if ( $oldFashionedRestrictions != '' ) {
2185 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2186 $temp = explode( '=', trim( $restrict ) );
2187 if ( count( $temp ) == 1 ) {
2188 // old old format should be treated as edit/move restriction
2189 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2190 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2191 } else {
2192 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2196 $this->mOldRestrictions = true;
2200 if ( count( $rows ) ) {
2201 # Current system - load second to make them override.
2202 $now = wfTimestampNow();
2203 $purgeExpired = false;
2205 # Cycle through all the restrictions.
2206 foreach ( $rows as $row ) {
2208 // Don't take care of restrictions types that aren't allowed
2209 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2210 continue;
2212 // This code should be refactored, now that it's being used more generally,
2213 // But I don't really see any harm in leaving it in Block for now -werdna
2214 $expiry = Block::decodeExpiry( $row->pr_expiry );
2216 // Only apply the restrictions if they haven't expired!
2217 if ( !$expiry || $expiry > $now ) {
2218 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2219 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2221 $this->mCascadeRestriction |= $row->pr_cascade;
2222 } else {
2223 // Trigger a lazy purge of expired restrictions
2224 $purgeExpired = true;
2228 if ( $purgeExpired ) {
2229 Title::purgeExpiredRestrictions();
2233 $this->mRestrictionsLoaded = true;
2237 * Load restrictions from the page_restrictions table
2239 * @param $oldFashionedRestrictions String comma-separated list of page
2240 * restrictions from page table (pre 1.10)
2242 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2243 if ( !$this->mRestrictionsLoaded ) {
2244 if ( $this->exists() ) {
2245 $dbr = wfGetDB( DB_SLAVE );
2247 $res = $dbr->select( 'page_restrictions', '*',
2248 array( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2250 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2251 } else {
2252 $title_protection = $this->getTitleProtection();
2254 if ( $title_protection ) {
2255 $now = wfTimestampNow();
2256 $expiry = Block::decodeExpiry( $title_protection['pt_expiry'] );
2258 if ( !$expiry || $expiry > $now ) {
2259 // Apply the restrictions
2260 $this->mRestrictionsExpiry['create'] = $expiry;
2261 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2262 } else { // Get rid of the old restrictions
2263 Title::purgeExpiredRestrictions();
2264 $this->mTitleProtection = false;
2266 } else {
2267 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry( '' );
2269 $this->mRestrictionsLoaded = true;
2275 * Purge expired restrictions from the page_restrictions table
2277 static function purgeExpiredRestrictions() {
2278 $dbw = wfGetDB( DB_MASTER );
2279 $dbw->delete(
2280 'page_restrictions',
2281 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2282 __METHOD__
2285 $dbw->delete(
2286 'protected_titles',
2287 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2288 __METHOD__
2293 * Accessor/initialisation for mRestrictions
2295 * @param $action String action that permission needs to be checked for
2296 * @return Array of Strings the array of groups allowed to edit this article
2298 public function getRestrictions( $action ) {
2299 if ( !$this->mRestrictionsLoaded ) {
2300 $this->loadRestrictions();
2302 return isset( $this->mRestrictions[$action] )
2303 ? $this->mRestrictions[$action]
2304 : array();
2308 * Get the expiry time for the restriction against a given action
2310 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2311 * or not protected at all, or false if the action is not recognised.
2313 public function getRestrictionExpiry( $action ) {
2314 if ( !$this->mRestrictionsLoaded ) {
2315 $this->loadRestrictions();
2317 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2321 * Is there a version of this page in the deletion archive?
2323 * @return Int the number of archived revisions
2325 public function isDeleted() {
2326 if ( $this->getNamespace() < 0 ) {
2327 $n = 0;
2328 } else {
2329 $dbr = wfGetDB( DB_SLAVE );
2330 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2331 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2332 __METHOD__
2334 if ( $this->getNamespace() == NS_FILE ) {
2335 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2336 array( 'fa_name' => $this->getDBkey() ),
2337 __METHOD__
2341 return (int)$n;
2345 * Is there a version of this page in the deletion archive?
2347 * @return Boolean
2349 public function isDeletedQuick() {
2350 if ( $this->getNamespace() < 0 ) {
2351 return false;
2353 $dbr = wfGetDB( DB_SLAVE );
2354 $deleted = (bool)$dbr->selectField( 'archive', '1',
2355 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2356 __METHOD__
2358 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2359 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2360 array( 'fa_name' => $this->getDBkey() ),
2361 __METHOD__
2364 return $deleted;
2368 * Get the article ID for this Title from the link cache,
2369 * adding it if necessary
2371 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2372 * for update
2373 * @return Int the ID
2375 public function getArticleID( $flags = 0 ) {
2376 if ( $this->getNamespace() < 0 ) {
2377 return $this->mArticleID = 0;
2379 $linkCache = LinkCache::singleton();
2380 if ( $flags & self::GAID_FOR_UPDATE ) {
2381 $oldUpdate = $linkCache->forUpdate( true );
2382 $linkCache->clearLink( $this );
2383 $this->mArticleID = $linkCache->addLinkObj( $this );
2384 $linkCache->forUpdate( $oldUpdate );
2385 } else {
2386 if ( -1 == $this->mArticleID ) {
2387 $this->mArticleID = $linkCache->addLinkObj( $this );
2390 return $this->mArticleID;
2394 * Is this an article that is a redirect page?
2395 * Uses link cache, adding it if necessary
2397 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2398 * @return Bool
2400 public function isRedirect( $flags = 0 ) {
2401 if ( !is_null( $this->mRedirect ) ) {
2402 return $this->mRedirect;
2404 # Calling getArticleID() loads the field from cache as needed
2405 if ( !$this->getArticleID( $flags ) ) {
2406 return $this->mRedirect = false;
2408 $linkCache = LinkCache::singleton();
2409 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2411 return $this->mRedirect;
2415 * What is the length of this page?
2416 * Uses link cache, adding it if necessary
2418 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2419 * @return Int
2421 public function getLength( $flags = 0 ) {
2422 if ( $this->mLength != -1 ) {
2423 return $this->mLength;
2425 # Calling getArticleID() loads the field from cache as needed
2426 if ( !$this->getArticleID( $flags ) ) {
2427 return $this->mLength = 0;
2429 $linkCache = LinkCache::singleton();
2430 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2432 return $this->mLength;
2436 * What is the page_latest field for this page?
2438 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2439 * @return Int or 0 if the page doesn't exist
2441 public function getLatestRevID( $flags = 0 ) {
2442 if ( $this->mLatestID !== false ) {
2443 return intval( $this->mLatestID );
2445 # Calling getArticleID() loads the field from cache as needed
2446 if ( !$this->getArticleID( $flags ) ) {
2447 return $this->mLatestID = 0;
2449 $linkCache = LinkCache::singleton();
2450 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2452 return $this->mLatestID;
2456 * This clears some fields in this object, and clears any associated
2457 * keys in the "bad links" section of the link cache.
2459 * - This is called from Article::doEdit() and Article::insertOn() to allow
2460 * loading of the new page_id. It's also called from
2461 * Article::doDeleteArticle()
2463 * @param $newid Int the new Article ID
2465 public function resetArticleID( $newid ) {
2466 $linkCache = LinkCache::singleton();
2467 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2469 if ( $newid === false ) {
2470 $this->mArticleID = -1;
2471 } else {
2472 $this->mArticleID = intval( $newid );
2474 $this->mRestrictionsLoaded = false;
2475 $this->mRestrictions = array();
2476 $this->mRedirect = null;
2477 $this->mLength = -1;
2478 $this->mLatestID = false;
2482 * Updates page_touched for this page; called from LinksUpdate.php
2484 * @return Bool true if the update succeded
2486 public function invalidateCache() {
2487 if ( wfReadOnly() ) {
2488 return;
2490 $dbw = wfGetDB( DB_MASTER );
2491 $success = $dbw->update(
2492 'page',
2493 array( 'page_touched' => $dbw->timestamp() ),
2494 $this->pageCond(),
2495 __METHOD__
2497 HTMLFileCache::clearFileCache( $this );
2498 return $success;
2502 * Prefix some arbitrary text with the namespace or interwiki prefix
2503 * of this object
2505 * @param $name String the text
2506 * @return String the prefixed text
2507 * @private
2509 /* private */ function prefix( $name ) {
2510 $p = '';
2511 if ( $this->mInterwiki != '' ) {
2512 $p = $this->mInterwiki . ':';
2515 if ( 0 != $this->mNamespace ) {
2516 $p .= $this->getNsText() . ':';
2518 return $p . $name;
2522 * Returns a simple regex that will match on characters and sequences invalid in titles.
2523 * Note that this doesn't pick up many things that could be wrong with titles, but that
2524 * replacing this regex with something valid will make many titles valid.
2526 * @return String regex string
2528 static function getTitleInvalidRegex() {
2529 static $rxTc = false;
2530 if ( !$rxTc ) {
2531 # Matching titles will be held as illegal.
2532 $rxTc = '/' .
2533 # Any character not allowed is forbidden...
2534 '[^' . Title::legalChars() . ']' .
2535 # URL percent encoding sequences interfere with the ability
2536 # to round-trip titles -- you can't link to them consistently.
2537 '|%[0-9A-Fa-f]{2}' .
2538 # XML/HTML character references produce similar issues.
2539 '|&[A-Za-z0-9\x80-\xff]+;' .
2540 '|&#[0-9]+;' .
2541 '|&#x[0-9A-Fa-f]+;' .
2542 '/S';
2545 return $rxTc;
2549 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2551 * @param $text String containing title to capitalize
2552 * @param $ns int namespace index, defaults to NS_MAIN
2553 * @return String containing capitalized title
2555 public static function capitalize( $text, $ns = NS_MAIN ) {
2556 global $wgContLang;
2558 if ( MWNamespace::isCapitalized( $ns ) ) {
2559 return $wgContLang->ucfirst( $text );
2560 } else {
2561 return $text;
2566 * Secure and split - main initialisation function for this object
2568 * Assumes that mDbkeyform has been set, and is urldecoded
2569 * and uses underscores, but not otherwise munged. This function
2570 * removes illegal characters, splits off the interwiki and
2571 * namespace prefixes, sets the other forms, and canonicalizes
2572 * everything.
2574 * @return Bool true on success
2576 private function secureAndSplit() {
2577 global $wgContLang, $wgLocalInterwiki;
2579 # Initialisation
2580 $rxTc = self::getTitleInvalidRegex();
2582 $this->mInterwiki = $this->mFragment = '';
2583 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2585 $dbkey = $this->mDbkeyform;
2587 # Strip Unicode bidi override characters.
2588 # Sometimes they slip into cut-n-pasted page titles, where the
2589 # override chars get included in list displays.
2590 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2592 # Clean up whitespace
2593 # Note: use of the /u option on preg_replace here will cause
2594 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2595 # conveniently disabling them.
2596 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2597 $dbkey = trim( $dbkey, '_' );
2599 if ( $dbkey == '' ) {
2600 return false;
2603 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2604 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2605 return false;
2608 $this->mDbkeyform = $dbkey;
2610 # Initial colon indicates main namespace rather than specified default
2611 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2612 if ( ':' == $dbkey { 0 } ) {
2613 $this->mNamespace = NS_MAIN;
2614 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2615 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2618 # Namespace or interwiki prefix
2619 $firstPass = true;
2620 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2621 do {
2622 $m = array();
2623 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2624 $p = $m[1];
2625 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2626 # Ordinary namespace
2627 $dbkey = $m[2];
2628 $this->mNamespace = $ns;
2629 # For Talk:X pages, check if X has a "namespace" prefix
2630 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2631 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2632 # Disallow Talk:File:x type titles...
2633 return false;
2634 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2635 # Disallow Talk:Interwiki:x type titles...
2636 return false;
2639 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2640 if ( !$firstPass ) {
2641 # Can't make a local interwiki link to an interwiki link.
2642 # That's just crazy!
2643 return false;
2646 # Interwiki link
2647 $dbkey = $m[2];
2648 $this->mInterwiki = $wgContLang->lc( $p );
2650 # Redundant interwiki prefix to the local wiki
2651 if ( $wgLocalInterwiki !== false
2652 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2654 if ( $dbkey == '' ) {
2655 # Can't have an empty self-link
2656 return false;
2658 $this->mInterwiki = '';
2659 $firstPass = false;
2660 # Do another namespace split...
2661 continue;
2664 # If there's an initial colon after the interwiki, that also
2665 # resets the default namespace
2666 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2667 $this->mNamespace = NS_MAIN;
2668 $dbkey = substr( $dbkey, 1 );
2671 # If there's no recognized interwiki or namespace,
2672 # then let the colon expression be part of the title.
2674 break;
2675 } while ( true );
2677 # We already know that some pages won't be in the database!
2678 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2679 $this->mArticleID = 0;
2681 $fragment = strstr( $dbkey, '#' );
2682 if ( false !== $fragment ) {
2683 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2684 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2685 # remove whitespace again: prevents "Foo_bar_#"
2686 # becoming "Foo_bar_"
2687 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2690 # Reject illegal characters.
2691 if ( preg_match( $rxTc, $dbkey ) ) {
2692 return false;
2695 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2696 # reachable due to the way web browsers deal with 'relative' URLs.
2697 # Also, they conflict with subpage syntax. Forbid them explicitly.
2698 if ( strpos( $dbkey, '.' ) !== false &&
2699 ( $dbkey === '.' || $dbkey === '..' ||
2700 strpos( $dbkey, './' ) === 0 ||
2701 strpos( $dbkey, '../' ) === 0 ||
2702 strpos( $dbkey, '/./' ) !== false ||
2703 strpos( $dbkey, '/../' ) !== false ||
2704 substr( $dbkey, -2 ) == '/.' ||
2705 substr( $dbkey, -3 ) == '/..' ) )
2707 return false;
2710 # Magic tilde sequences? Nu-uh!
2711 if ( strpos( $dbkey, '~~~' ) !== false ) {
2712 return false;
2715 # Limit the size of titles to 255 bytes. This is typically the size of the
2716 # underlying database field. We make an exception for special pages, which
2717 # don't need to be stored in the database, and may edge over 255 bytes due
2718 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2719 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2720 strlen( $dbkey ) > 512 )
2722 return false;
2725 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2726 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2727 # other site might be case-sensitive.
2728 $this->mUserCaseDBKey = $dbkey;
2729 if ( $this->mInterwiki == '' ) {
2730 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2733 # Can't make a link to a namespace alone... "empty" local links can only be
2734 # self-links with a fragment identifier.
2735 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2736 return false;
2739 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2740 // IP names are not allowed for accounts, and can only be referring to
2741 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2742 // there are numerous ways to present the same IP. Having sp:contribs scan
2743 // them all is silly and having some show the edits and others not is
2744 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2745 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2746 ? IP::sanitizeIP( $dbkey )
2747 : $dbkey;
2749 // Any remaining initial :s are illegal.
2750 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2751 return false;
2754 # Fill fields
2755 $this->mDbkeyform = $dbkey;
2756 $this->mUrlform = wfUrlencode( $dbkey );
2758 $this->mTextform = str_replace( '_', ' ', $dbkey );
2760 return true;
2764 * Set the fragment for this title. Removes the first character from the
2765 * specified fragment before setting, so it assumes you're passing it with
2766 * an initial "#".
2768 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2769 * Still in active use privately.
2771 * @param $fragment String text
2773 public function setFragment( $fragment ) {
2774 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2778 * Get a Title object associated with the talk page of this article
2780 * @return Title the object for the talk page
2782 public function getTalkPage() {
2783 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2787 * Get a title object associated with the subject page of this
2788 * talk page
2790 * @return Title the object for the subject page
2792 public function getSubjectPage() {
2793 // Is this the same title?
2794 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2795 if ( $this->getNamespace() == $subjectNS ) {
2796 return $this;
2798 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2802 * Get an array of Title objects linking to this Title
2803 * Also stores the IDs in the link cache.
2805 * WARNING: do not use this function on arbitrary user-supplied titles!
2806 * On heavily-used templates it will max out the memory.
2808 * @param $options Array: may be FOR UPDATE
2809 * @param $table String: table name
2810 * @param $prefix String: fields prefix
2811 * @return Array of Title objects linking here
2813 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2814 $linkCache = LinkCache::singleton();
2816 if ( count( $options ) > 0 ) {
2817 $db = wfGetDB( DB_MASTER );
2818 } else {
2819 $db = wfGetDB( DB_SLAVE );
2822 $res = $db->select(
2823 array( 'page', $table ),
2824 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2825 array(
2826 "{$prefix}_from=page_id",
2827 "{$prefix}_namespace" => $this->getNamespace(),
2828 "{$prefix}_title" => $this->getDBkey() ),
2829 __METHOD__,
2830 $options
2833 $retVal = array();
2834 if ( $db->numRows( $res ) ) {
2835 foreach ( $res as $row ) {
2836 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2837 if ( $titleObj ) {
2838 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2839 $retVal[] = $titleObj;
2843 return $retVal;
2847 * Get an array of Title objects using this Title as a template
2848 * Also stores the IDs in the link cache.
2850 * WARNING: do not use this function on arbitrary user-supplied titles!
2851 * On heavily-used templates it will max out the memory.
2853 * @param $options Array: may be FOR UPDATE
2854 * @return Array of Title the Title objects linking here
2856 public function getTemplateLinksTo( $options = array() ) {
2857 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2861 * Get an array of Title objects referring to non-existent articles linked from this page
2863 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2864 * @return Array of Title the Title objects
2866 public function getBrokenLinksFrom() {
2867 if ( $this->getArticleId() == 0 ) {
2868 # All links from article ID 0 are false positives
2869 return array();
2872 $dbr = wfGetDB( DB_SLAVE );
2873 $res = $dbr->select(
2874 array( 'page', 'pagelinks' ),
2875 array( 'pl_namespace', 'pl_title' ),
2876 array(
2877 'pl_from' => $this->getArticleId(),
2878 'page_namespace IS NULL'
2880 __METHOD__, array(),
2881 array(
2882 'page' => array(
2883 'LEFT JOIN',
2884 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2889 $retVal = array();
2890 foreach ( $res as $row ) {
2891 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2893 return $retVal;
2898 * Get a list of URLs to purge from the Squid cache when this
2899 * page changes
2901 * @return Array of String the URLs
2903 public function getSquidURLs() {
2904 global $wgContLang;
2906 $urls = array(
2907 $this->getInternalURL(),
2908 $this->getInternalURL( 'action=history' )
2911 // purge variant urls as well
2912 if ( $wgContLang->hasVariants() ) {
2913 $variants = $wgContLang->getVariants();
2914 foreach ( $variants as $vCode ) {
2915 $urls[] = $this->getInternalURL( '', $vCode );
2919 return $urls;
2923 * Purge all applicable Squid URLs
2925 public function purgeSquid() {
2926 global $wgUseSquid;
2927 if ( $wgUseSquid ) {
2928 $urls = $this->getSquidURLs();
2929 $u = new SquidUpdate( $urls );
2930 $u->doUpdate();
2935 * Move this page without authentication
2937 * @param $nt Title the new page Title
2938 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2940 public function moveNoAuth( &$nt ) {
2941 return $this->moveTo( $nt, false );
2945 * Check whether a given move operation would be valid.
2946 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2948 * @param $nt Title the new title
2949 * @param $auth Bool indicates whether $wgUser's permissions
2950 * should be checked
2951 * @param $reason String is the log summary of the move, used for spam checking
2952 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2954 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2955 global $wgUser;
2957 $errors = array();
2958 if ( !$nt ) {
2959 // Normally we'd add this to $errors, but we'll get
2960 // lots of syntax errors if $nt is not an object
2961 return array( array( 'badtitletext' ) );
2963 if ( $this->equals( $nt ) ) {
2964 $errors[] = array( 'selfmove' );
2966 if ( !$this->isMovable() ) {
2967 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2969 if ( $nt->getInterwiki() != '' ) {
2970 $errors[] = array( 'immobile-target-namespace-iw' );
2972 if ( !$nt->isMovable() ) {
2973 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2976 $oldid = $this->getArticleID();
2977 $newid = $nt->getArticleID();
2979 if ( strlen( $nt->getDBkey() ) < 1 ) {
2980 $errors[] = array( 'articleexists' );
2982 if ( ( $this->getDBkey() == '' ) ||
2983 ( !$oldid ) ||
2984 ( $nt->getDBkey() == '' ) ) {
2985 $errors[] = array( 'badarticleerror' );
2988 // Image-specific checks
2989 if ( $this->getNamespace() == NS_FILE ) {
2990 if ( $nt->getNamespace() != NS_FILE ) {
2991 $errors[] = array( 'imagenocrossnamespace' );
2993 $file = wfLocalFile( $this );
2994 if ( $file->exists() ) {
2995 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2996 $errors[] = array( 'imageinvalidfilename' );
2998 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2999 $errors[] = array( 'imagetypemismatch' );
3002 $destfile = wfLocalFile( $nt );
3003 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
3004 $errors[] = array( 'file-exists-sharedrepo' );
3008 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3009 $errors[] = array( 'nonfile-cannot-move-to-file' );
3012 if ( $auth ) {
3013 $errors = wfMergeErrorArrays( $errors,
3014 $this->getUserPermissionsErrors( 'move', $wgUser ),
3015 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3016 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3017 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3020 $match = EditPage::matchSummarySpamRegex( $reason );
3021 if ( $match !== false ) {
3022 // This is kind of lame, won't display nice
3023 $errors[] = array( 'spamprotectiontext' );
3026 $err = null;
3027 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3028 $errors[] = array( 'hookaborted', $err );
3031 # The move is allowed only if (1) the target doesn't exist, or
3032 # (2) the target is a redirect to the source, and has no history
3033 # (so we can undo bad moves right after they're done).
3035 if ( 0 != $newid ) { # Target exists; check for validity
3036 if ( !$this->isValidMoveTarget( $nt ) ) {
3037 $errors[] = array( 'articleexists' );
3039 } else {
3040 $tp = $nt->getTitleProtection();
3041 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3042 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3043 $errors[] = array( 'cantmove-titleprotected' );
3046 if ( empty( $errors ) ) {
3047 return true;
3049 return $errors;
3053 * Move a title to a new location
3055 * @param $nt Title the new title
3056 * @param $auth Bool indicates whether $wgUser's permissions
3057 * should be checked
3058 * @param $reason String the reason for the move
3059 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3060 * Ignored if the user doesn't have the suppressredirect right.
3061 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3063 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3064 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3065 if ( is_array( $err ) ) {
3066 return $err;
3069 // If it is a file, move it first. It is done before all other moving stuff is
3070 // done because it's hard to revert
3071 $dbw = wfGetDB( DB_MASTER );
3072 if ( $this->getNamespace() == NS_FILE ) {
3073 $file = wfLocalFile( $this );
3074 if ( $file->exists() ) {
3075 $status = $file->move( $nt );
3076 if ( !$status->isOk() ) {
3077 return $status->getErrorsArray();
3082 $pageid = $this->getArticleID();
3083 $protected = $this->isProtected();
3084 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3086 // Do the actual move
3087 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3088 if ( is_array( $err ) ) {
3089 return $err;
3092 $redirid = $this->getArticleID();
3094 // Refresh the sortkey for this row. Be careful to avoid resetting
3095 // cl_timestamp, which may disturb time-based lists on some sites.
3096 $prefix = $dbw->selectField(
3097 'categorylinks',
3098 'cl_sortkey_prefix',
3099 array( 'cl_from' => $pageid ),
3100 __METHOD__
3102 $dbw->update( 'categorylinks',
3103 array(
3104 'cl_sortkey' => Collation::singleton()->getSortKey(
3105 $nt->getCategorySortkey( $prefix ) ),
3106 'cl_timestamp=cl_timestamp' ),
3107 array( 'cl_from' => $pageid ),
3108 __METHOD__ );
3110 if ( $protected ) {
3111 # Protect the redirect title as the title used to be...
3112 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3113 array(
3114 'pr_page' => $redirid,
3115 'pr_type' => 'pr_type',
3116 'pr_level' => 'pr_level',
3117 'pr_cascade' => 'pr_cascade',
3118 'pr_user' => 'pr_user',
3119 'pr_expiry' => 'pr_expiry'
3121 array( 'pr_page' => $pageid ),
3122 __METHOD__,
3123 array( 'IGNORE' )
3125 # Update the protection log
3126 $log = new LogPage( 'protect' );
3127 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3128 if ( $reason ) {
3129 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3131 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3134 # Update watchlists
3135 $oldnamespace = $this->getNamespace() & ~1;
3136 $newnamespace = $nt->getNamespace() & ~1;
3137 $oldtitle = $this->getDBkey();
3138 $newtitle = $nt->getDBkey();
3140 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3141 WatchedItem::duplicateEntries( $this, $nt );
3144 # Update search engine
3145 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3146 $u->doUpdate();
3147 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3148 $u->doUpdate();
3150 # Update site_stats
3151 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3152 # No longer a content page
3153 # Not viewed, edited, removing
3154 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3155 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3156 # Now a content page
3157 # Not viewed, edited, adding
3158 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3159 } elseif ( $pageCountChange ) {
3160 # Redirect added
3161 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3162 } else {
3163 # Nothing special
3164 $u = false;
3166 if ( $u ) {
3167 $u->doUpdate();
3169 # Update message cache for interface messages
3170 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3171 # @bug 17860: old article can be deleted, if this the case,
3172 # delete it from message cache
3173 if ( $this->getArticleID() === 0 ) {
3174 MessageCache::singleton()->replace( $this->getDBkey(), false );
3175 } else {
3176 $oldarticle = new Article( $this );
3177 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3180 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3181 $newarticle = new Article( $nt );
3182 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3185 global $wgUser;
3186 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3187 return true;
3191 * Move page to a title which is either a redirect to the
3192 * source page or nonexistent
3194 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3195 * @param $reason String The reason for the move
3196 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3197 * if the user doesn't have the suppressredirect right
3199 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3200 global $wgUser, $wgContLang;
3202 $moveOverRedirect = $nt->exists();
3204 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3205 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3207 if ( $reason ) {
3208 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3210 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3211 $comment = $wgContLang->truncate( $comment, 250 );
3213 $oldid = $this->getArticleID();
3214 $latest = $this->getLatestRevID();
3216 $dbw = wfGetDB( DB_MASTER );
3218 if ( $moveOverRedirect ) {
3219 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3221 $newid = $nt->getArticleID();
3222 $newns = $nt->getNamespace();
3223 $newdbk = $nt->getDBkey();
3225 # Delete the old redirect. We don't save it to history since
3226 # by definition if we've got here it's rather uninteresting.
3227 # We have to remove it so that the next step doesn't trigger
3228 # a conflict on the unique namespace+title index...
3229 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3230 if ( !$dbw->cascadingDeletes() ) {
3231 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3232 global $wgUseTrackbacks;
3233 if ( $wgUseTrackbacks ) {
3234 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3236 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3237 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3238 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3239 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3240 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3241 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3242 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3244 // If the target page was recently created, it may have an entry in recentchanges still
3245 $dbw->delete( 'recentchanges',
3246 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3247 __METHOD__
3251 # Save a null revision in the page's history notifying of the move
3252 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3253 if ( !is_object( $nullRevision ) ) {
3254 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3256 $nullRevId = $nullRevision->insertOn( $dbw );
3258 $article = new Article( $this );
3259 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3261 # Change the name of the target page:
3262 $dbw->update( 'page',
3263 /* SET */ array(
3264 'page_touched' => $dbw->timestamp(),
3265 'page_namespace' => $nt->getNamespace(),
3266 'page_title' => $nt->getDBkey(),
3267 'page_latest' => $nullRevId,
3269 /* WHERE */ array( 'page_id' => $oldid ),
3270 __METHOD__
3272 $nt->resetArticleID( $oldid );
3274 # Recreate the redirect, this time in the other direction.
3275 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3276 $mwRedir = MagicWord::get( 'redirect' );
3277 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3278 $redirectArticle = new Article( $this );
3279 $newid = $redirectArticle->insertOn( $dbw );
3280 $redirectRevision = new Revision( array(
3281 'page' => $newid,
3282 'comment' => $comment,
3283 'text' => $redirectText ) );
3284 $redirectRevision->insertOn( $dbw );
3285 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3287 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3289 # Now, we record the link from the redirect to the new title.
3290 # It should have no other outgoing links...
3291 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3292 $dbw->insert( 'pagelinks',
3293 array(
3294 'pl_from' => $newid,
3295 'pl_namespace' => $nt->getNamespace(),
3296 'pl_title' => $nt->getDBkey() ),
3297 __METHOD__ );
3298 $redirectSuppressed = false;
3299 } else {
3300 $this->resetArticleID( 0 );
3301 $redirectSuppressed = true;
3304 # Log the move
3305 $log = new LogPage( 'move' );
3306 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3307 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3309 # Purge caches for old and new titles
3310 if ( $moveOverRedirect ) {
3311 # A simple purge is enough when moving over a redirect
3312 $nt->purgeSquid();
3313 } else {
3314 # Purge caches as per article creation, including any pages that link to this title
3315 Article::onArticleCreate( $nt );
3317 $this->purgeSquid();
3321 * Move this page's subpages to be subpages of $nt
3323 * @param $nt Title Move target
3324 * @param $auth bool Whether $wgUser's permissions should be checked
3325 * @param $reason string The reason for the move
3326 * @param $createRedirect bool Whether to create redirects from the old subpages to
3327 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3328 * @return mixed array with old page titles as keys, and strings (new page titles) or
3329 * arrays (errors) as values, or an error array with numeric indices if no pages
3330 * were moved
3332 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3333 global $wgMaximumMovedPages;
3334 // Check permissions
3335 if ( !$this->userCan( 'move-subpages' ) ) {
3336 return array( 'cant-move-subpages' );
3338 // Do the source and target namespaces support subpages?
3339 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3340 return array( 'namespace-nosubpages',
3341 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3343 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3344 return array( 'namespace-nosubpages',
3345 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3348 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3349 $retval = array();
3350 $count = 0;
3351 foreach ( $subpages as $oldSubpage ) {
3352 $count++;
3353 if ( $count > $wgMaximumMovedPages ) {
3354 $retval[$oldSubpage->getPrefixedTitle()] =
3355 array( 'movepage-max-pages',
3356 $wgMaximumMovedPages );
3357 break;
3360 // We don't know whether this function was called before
3361 // or after moving the root page, so check both
3362 // $this and $nt
3363 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3364 $oldSubpage->getArticleID() == $nt->getArticleId() )
3366 // When moving a page to a subpage of itself,
3367 // don't move it twice
3368 continue;
3370 $newPageName = preg_replace(
3371 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3372 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3373 $oldSubpage->getDBkey() );
3374 if ( $oldSubpage->isTalkPage() ) {
3375 $newNs = $nt->getTalkPage()->getNamespace();
3376 } else {
3377 $newNs = $nt->getSubjectPage()->getNamespace();
3379 # Bug 14385: we need makeTitleSafe because the new page names may
3380 # be longer than 255 characters.
3381 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3383 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3384 if ( $success === true ) {
3385 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3386 } else {
3387 $retval[$oldSubpage->getPrefixedText()] = $success;
3390 return $retval;
3394 * Checks if this page is just a one-rev redirect.
3395 * Adds lock, so don't use just for light purposes.
3397 * @return Bool
3399 public function isSingleRevRedirect() {
3400 $dbw = wfGetDB( DB_MASTER );
3401 # Is it a redirect?
3402 $row = $dbw->selectRow( 'page',
3403 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3404 $this->pageCond(),
3405 __METHOD__,
3406 array( 'FOR UPDATE' )
3408 # Cache some fields we may want
3409 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3410 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3411 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3412 if ( !$this->mRedirect ) {
3413 return false;
3415 # Does the article have a history?
3416 $row = $dbw->selectField( array( 'page', 'revision' ),
3417 'rev_id',
3418 array( 'page_namespace' => $this->getNamespace(),
3419 'page_title' => $this->getDBkey(),
3420 'page_id=rev_page',
3421 'page_latest != rev_id'
3423 __METHOD__,
3424 array( 'FOR UPDATE' )
3426 # Return true if there was no history
3427 return ( $row === false );
3431 * Checks if $this can be moved to a given Title
3432 * - Selects for update, so don't call it unless you mean business
3434 * @param $nt Title the new title to check
3435 * @return Bool
3437 public function isValidMoveTarget( $nt ) {
3438 # Is it an existing file?
3439 if ( $nt->getNamespace() == NS_FILE ) {
3440 $file = wfLocalFile( $nt );
3441 if ( $file->exists() ) {
3442 wfDebug( __METHOD__ . ": file exists\n" );
3443 return false;
3446 # Is it a redirect with no history?
3447 if ( !$nt->isSingleRevRedirect() ) {
3448 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3449 return false;
3451 # Get the article text
3452 $rev = Revision::newFromTitle( $nt );
3453 $text = $rev->getText();
3454 # Does the redirect point to the source?
3455 # Or is it a broken self-redirect, usually caused by namespace collisions?
3456 $m = array();
3457 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3458 $redirTitle = Title::newFromText( $m[1] );
3459 if ( !is_object( $redirTitle ) ||
3460 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3461 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3462 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3463 return false;
3465 } else {
3466 # Fail safe
3467 wfDebug( __METHOD__ . ": failsafe\n" );
3468 return false;
3470 return true;
3474 * Can this title be added to a user's watchlist?
3476 * @return Bool TRUE or FALSE
3478 public function isWatchable() {
3479 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3483 * Get categories to which this Title belongs and return an array of
3484 * categories' names.
3486 * @return Array of parents in the form:
3487 * $parent => $currentarticle
3489 public function getParentCategories() {
3490 global $wgContLang;
3492 $data = array();
3494 $titleKey = $this->getArticleId();
3496 if ( $titleKey === 0 ) {
3497 return $data;
3500 $dbr = wfGetDB( DB_SLAVE );
3502 $res = $dbr->select( 'categorylinks', '*',
3503 array(
3504 'cl_from' => $titleKey,
3506 __METHOD__,
3507 array()
3510 if ( $dbr->numRows( $res ) > 0 ) {
3511 foreach ( $res as $row ) {
3512 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3513 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3516 return $data;
3520 * Get a tree of parent categories
3522 * @param $children Array with the children in the keys, to check for circular refs
3523 * @return Array Tree of parent categories
3525 public function getParentCategoryTree( $children = array() ) {
3526 $stack = array();
3527 $parents = $this->getParentCategories();
3529 if ( $parents ) {
3530 foreach ( $parents as $parent => $current ) {
3531 if ( array_key_exists( $parent, $children ) ) {
3532 # Circular reference
3533 $stack[$parent] = array();
3534 } else {
3535 $nt = Title::newFromText( $parent );
3536 if ( $nt ) {
3537 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3543 return $stack;
3547 * Get an associative array for selecting this title from
3548 * the "page" table
3550 * @return Array suitable for the $where parameter of DB::select()
3552 public function pageCond() {
3553 if ( $this->mArticleID > 0 ) {
3554 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3555 return array( 'page_id' => $this->mArticleID );
3556 } else {
3557 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3562 * Get the revision ID of the previous revision
3564 * @param $revId Int Revision ID. Get the revision that was before this one.
3565 * @param $flags Int Title::GAID_FOR_UPDATE
3566 * @return Int|Bool Old revision ID, or FALSE if none exists
3568 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3569 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3570 return $db->selectField( 'revision', 'rev_id',
3571 array(
3572 'rev_page' => $this->getArticleId( $flags ),
3573 'rev_id < ' . intval( $revId )
3575 __METHOD__,
3576 array( 'ORDER BY' => 'rev_id DESC' )
3581 * Get the revision ID of the next revision
3583 * @param $revId Int Revision ID. Get the revision that was after this one.
3584 * @param $flags Int Title::GAID_FOR_UPDATE
3585 * @return Int|Bool Next revision ID, or FALSE if none exists
3587 public function getNextRevisionID( $revId, $flags = 0 ) {
3588 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3589 return $db->selectField( 'revision', 'rev_id',
3590 array(
3591 'rev_page' => $this->getArticleId( $flags ),
3592 'rev_id > ' . intval( $revId )
3594 __METHOD__,
3595 array( 'ORDER BY' => 'rev_id' )
3600 * Get the first revision of the page
3602 * @param $flags Int Title::GAID_FOR_UPDATE
3603 * @return Revision|Null if page doesn't exist
3605 public function getFirstRevision( $flags = 0 ) {
3606 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3607 $pageId = $this->getArticleId( $flags );
3608 if ( !$pageId ) {
3609 return null;
3611 $row = $db->selectRow( 'revision', '*',
3612 array( 'rev_page' => $pageId ),
3613 __METHOD__,
3614 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3616 if ( !$row ) {
3617 return null;
3618 } else {
3619 return new Revision( $row );
3624 * Check if this is a new page
3626 * @return bool
3628 public function isNewPage() {
3629 $dbr = wfGetDB( DB_SLAVE );
3630 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3634 * Get the oldest revision timestamp of this page
3636 * @return String: MW timestamp
3638 public function getEarliestRevTime() {
3639 $dbr = wfGetDB( DB_SLAVE );
3640 if ( $this->exists() ) {
3641 $min = $dbr->selectField( 'revision',
3642 'MIN(rev_timestamp)',
3643 array( 'rev_page' => $this->getArticleId() ),
3644 __METHOD__ );
3645 return wfTimestampOrNull( TS_MW, $min );
3647 return null;
3651 * Get the number of revisions between the given revision IDs.
3652 * Used for diffs and other things that really need it.
3654 * @param $old Int Revision ID.
3655 * @param $new Int Revision ID.
3656 * @return Int Number of revisions between these IDs.
3658 public function countRevisionsBetween( $old, $new ) {
3659 $dbr = wfGetDB( DB_SLAVE );
3660 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3661 'rev_page' => intval( $this->getArticleId() ),
3662 'rev_id > ' . intval( $old ),
3663 'rev_id < ' . intval( $new )
3664 ), __METHOD__
3669 * Get the number of authors between the given revision IDs.
3670 * Used for diffs and other things that really need it.
3672 * @param $fromRevId Int Revision ID (first before range)
3673 * @param $toRevId Int Revision ID (first after range)
3674 * @param $limit Int Maximum number of authors
3675 * @param $flags Int Title::GAID_FOR_UPDATE
3676 * @return Int
3678 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3679 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3680 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3681 array(
3682 'rev_page' => $this->getArticleID(),
3683 'rev_id > ' . (int)$fromRevId,
3684 'rev_id < ' . (int)$toRevId
3685 ), __METHOD__,
3686 array( 'LIMIT' => $limit )
3688 return (int)$db->numRows( $res );
3692 * Compare with another title.
3694 * @param $title Title
3695 * @return Bool
3697 public function equals( Title $title ) {
3698 // Note: === is necessary for proper matching of number-like titles.
3699 return $this->getInterwiki() === $title->getInterwiki()
3700 && $this->getNamespace() == $title->getNamespace()
3701 && $this->getDBkey() === $title->getDBkey();
3705 * Callback for usort() to do title sorts by (namespace, title)
3707 * @return Integer: result of string comparison, or namespace comparison
3709 public static function compare( $a, $b ) {
3710 if ( $a->getNamespace() == $b->getNamespace() ) {
3711 return strcmp( $a->getText(), $b->getText() );
3712 } else {
3713 return $a->getNamespace() - $b->getNamespace();
3718 * Return a string representation of this title
3720 * @return String representation of this title
3722 public function __toString() {
3723 return $this->getPrefixedText();
3727 * Check if page exists. For historical reasons, this function simply
3728 * checks for the existence of the title in the page table, and will
3729 * thus return false for interwiki links, special pages and the like.
3730 * If you want to know if a title can be meaningfully viewed, you should
3731 * probably call the isKnown() method instead.
3733 * @return Bool
3735 public function exists() {
3736 return $this->getArticleId() != 0;
3740 * Should links to this title be shown as potentially viewable (i.e. as
3741 * "bluelinks"), even if there's no record by this title in the page
3742 * table?
3744 * This function is semi-deprecated for public use, as well as somewhat
3745 * misleadingly named. You probably just want to call isKnown(), which
3746 * calls this function internally.
3748 * (ISSUE: Most of these checks are cheap, but the file existence check
3749 * can potentially be quite expensive. Including it here fixes a lot of
3750 * existing code, but we might want to add an optional parameter to skip
3751 * it and any other expensive checks.)
3753 * @return Bool
3755 public function isAlwaysKnown() {
3756 if ( $this->mInterwiki != '' ) {
3757 return true; // any interwiki link might be viewable, for all we know
3759 switch( $this->mNamespace ) {
3760 case NS_MEDIA:
3761 case NS_FILE:
3762 // file exists, possibly in a foreign repo
3763 return (bool)wfFindFile( $this );
3764 case NS_SPECIAL:
3765 // valid special page
3766 return SpecialPage::exists( $this->getDBkey() );
3767 case NS_MAIN:
3768 // selflink, possibly with fragment
3769 return $this->mDbkeyform == '';
3770 case NS_MEDIAWIKI:
3771 // known system message
3772 return $this->getDefaultMessageText() !== false;
3773 default:
3774 return false;
3779 * Does this title refer to a page that can (or might) be meaningfully
3780 * viewed? In particular, this function may be used to determine if
3781 * links to the title should be rendered as "bluelinks" (as opposed to
3782 * "redlinks" to non-existent pages).
3784 * @return Bool
3786 public function isKnown() {
3787 return $this->isAlwaysKnown() || $this->exists();
3791 * Does this page have source text?
3793 * @return Boolean
3795 public function hasSourceText() {
3796 if ( $this->exists() ) {
3797 return true;
3800 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3801 // If the page doesn't exist but is a known system message, default
3802 // message content will be displayed, same for language subpages
3803 return $this->getDefaultMessageText() !== false;
3806 return false;
3810 * Get the default message text or false if the message doesn't exist
3812 * @return String or false
3814 public function getDefaultMessageText() {
3815 global $wgContLang;
3817 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3818 return false;
3821 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3822 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3824 if ( $message->exists() ) {
3825 return $message->plain();
3826 } else {
3827 return false;
3832 * Is this in a namespace that allows actual pages?
3834 * @return Bool
3835 * @internal note -- uses hardcoded namespace index instead of constants
3837 public function canExist() {
3838 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3842 * Update page_touched timestamps and send squid purge messages for
3843 * pages linking to this title. May be sent to the job queue depending
3844 * on the number of links. Typically called on create and delete.
3846 public function touchLinks() {
3847 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3848 $u->doUpdate();
3850 if ( $this->getNamespace() == NS_CATEGORY ) {
3851 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3852 $u->doUpdate();
3857 * Get the last touched timestamp
3859 * @param $db DatabaseBase: optional db
3860 * @return String last-touched timestamp
3862 public function getTouched( $db = null ) {
3863 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3864 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3865 return $touched;
3869 * Get the timestamp when this page was updated since the user last saw it.
3871 * @param $user User
3872 * @return String|Null
3874 public function getNotificationTimestamp( $user = null ) {
3875 global $wgUser, $wgShowUpdatedMarker;
3876 // Assume current user if none given
3877 if ( !$user ) {
3878 $user = $wgUser;
3880 // Check cache first
3881 $uid = $user->getId();
3882 // avoid isset here, as it'll return false for null entries
3883 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3884 return $this->mNotificationTimestamp[$uid];
3886 if ( !$uid || !$wgShowUpdatedMarker ) {
3887 return $this->mNotificationTimestamp[$uid] = false;
3889 // Don't cache too much!
3890 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3891 $this->mNotificationTimestamp = array();
3893 $dbr = wfGetDB( DB_SLAVE );
3894 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3895 'wl_notificationtimestamp',
3896 array( 'wl_namespace' => $this->getNamespace(),
3897 'wl_title' => $this->getDBkey(),
3898 'wl_user' => $user->getId()
3900 __METHOD__
3902 return $this->mNotificationTimestamp[$uid];
3906 * Get the trackback URL for this page
3908 * @return String Trackback URL
3910 public function trackbackURL() {
3911 global $wgScriptPath, $wgServer, $wgScriptExtension;
3913 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3914 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3918 * Get the trackback RDF for this page
3920 * @return String Trackback RDF
3922 public function trackbackRDF() {
3923 $url = htmlspecialchars( $this->getFullURL() );
3924 $title = htmlspecialchars( $this->getText() );
3925 $tburl = $this->trackbackURL();
3927 // Autodiscovery RDF is placed in comments so HTML validator
3928 // won't barf. This is a rather icky workaround, but seems
3929 // frequently used by this kind of RDF thingy.
3931 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3932 return "<!--
3933 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3934 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3935 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3936 <rdf:Description
3937 rdf:about=\"$url\"
3938 dc:identifier=\"$url\"
3939 dc:title=\"$title\"
3940 trackback:ping=\"$tburl\" />
3941 </rdf:RDF>
3942 -->";
3946 * Generate strings used for xml 'id' names in monobook tabs
3948 * @param $prepend string defaults to 'nstab-'
3949 * @return String XML 'id' name
3951 public function getNamespaceKey( $prepend = 'nstab-' ) {
3952 global $wgContLang;
3953 // Gets the subject namespace if this title
3954 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3955 // Checks if cononical namespace name exists for namespace
3956 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3957 // Uses canonical namespace name
3958 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3959 } else {
3960 // Uses text of namespace
3961 $namespaceKey = $this->getSubjectNsText();
3963 // Makes namespace key lowercase
3964 $namespaceKey = $wgContLang->lc( $namespaceKey );
3965 // Uses main
3966 if ( $namespaceKey == '' ) {
3967 $namespaceKey = 'main';
3969 // Changes file to image for backwards compatibility
3970 if ( $namespaceKey == 'file' ) {
3971 $namespaceKey = 'image';
3973 return $prepend . $namespaceKey;
3977 * Returns true if this is a special page.
3979 * @return boolean
3981 public function isSpecialPage() {
3982 return $this->getNamespace() == NS_SPECIAL;
3986 * Returns true if this title resolves to the named special page
3988 * @param $name String The special page name
3989 * @return boolean
3991 public function isSpecial( $name ) {
3992 if ( $this->getNamespace() == NS_SPECIAL ) {
3993 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3994 if ( $name == $thisName ) {
3995 return true;
3998 return false;
4002 * If the Title refers to a special page alias which is not the local default, resolve
4003 * the alias, and localise the name as necessary. Otherwise, return $this
4005 * @return Title
4007 public function fixSpecialName() {
4008 if ( $this->getNamespace() == NS_SPECIAL ) {
4009 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4010 if ( $canonicalName ) {
4011 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4012 if ( $localName != $this->mDbkeyform ) {
4013 return Title::makeTitle( NS_SPECIAL, $localName );
4017 return $this;
4021 * Is this Title in a namespace which contains content?
4022 * In other words, is this a content page, for the purposes of calculating
4023 * statistics, etc?
4025 * @return Boolean
4027 public function isContentPage() {
4028 return MWNamespace::isContent( $this->getNamespace() );
4032 * Get all extant redirects to this Title
4034 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4035 * @return Array of Title redirects to this title
4037 public function getRedirectsHere( $ns = null ) {
4038 $redirs = array();
4040 $dbr = wfGetDB( DB_SLAVE );
4041 $where = array(
4042 'rd_namespace' => $this->getNamespace(),
4043 'rd_title' => $this->getDBkey(),
4044 'rd_from = page_id'
4046 if ( !is_null( $ns ) ) {
4047 $where['page_namespace'] = $ns;
4050 $res = $dbr->select(
4051 array( 'redirect', 'page' ),
4052 array( 'page_namespace', 'page_title' ),
4053 $where,
4054 __METHOD__
4057 foreach ( $res as $row ) {
4058 $redirs[] = self::newFromRow( $row );
4060 return $redirs;
4064 * Check if this Title is a valid redirect target
4066 * @return Bool
4068 public function isValidRedirectTarget() {
4069 global $wgInvalidRedirectTargets;
4071 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4072 if ( $this->isSpecial( 'Userlogout' ) ) {
4073 return false;
4076 foreach ( $wgInvalidRedirectTargets as $target ) {
4077 if ( $this->isSpecial( $target ) ) {
4078 return false;
4082 return true;
4086 * Get a backlink cache object
4088 * @return object BacklinkCache
4090 function getBacklinkCache() {
4091 if ( is_null( $this->mBacklinkCache ) ) {
4092 $this->mBacklinkCache = new BacklinkCache( $this );
4094 return $this->mBacklinkCache;
4098 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4100 * @return Boolean
4102 public function canUseNoindex() {
4103 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4105 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4106 ? $wgContentNamespaces
4107 : $wgExemptFromUserRobotsControl;
4109 return !in_array( $this->mNamespace, $bannedNamespaces );
4114 * Returns restriction types for the current Title
4116 * @return array applicable restriction types
4118 public function getRestrictionTypes() {
4119 $types = self::getFilteredRestrictionTypes( $this->exists() );
4121 if ( $this->getNamespace() != NS_FILE ) {
4122 # Remove the upload restriction for non-file titles
4123 $types = array_diff( $types, array( 'upload' ) );
4126 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4128 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4129 $this->getPrefixedText() . ' are ' . implode( ',', $types ) );
4131 return $types;
4134 * Get a filtered list of all restriction types supported by this wiki.
4135 * @param bool $exists True to get all restriction types that apply to
4136 * titles that do exist, False for all restriction types that apply to
4137 * titles that do not exist
4138 * @return array
4140 public static function getFilteredRestrictionTypes( $exists = true ) {
4141 global $wgRestrictionTypes;
4142 $types = $wgRestrictionTypes;
4143 if ( $exists ) {
4144 # Remove the create restriction for existing titles
4145 $types = array_diff( $types, array( 'create' ) );
4146 } else {
4147 # Only the create and upload restrictions apply to non-existing titles
4148 $types = array_intersect( $types, array( 'create', 'upload' ) );
4150 return $types;
4154 * Returns the raw sort key to be used for categories, with the specified
4155 * prefix. This will be fed to Collation::getSortKey() to get a
4156 * binary sortkey that can be used for actual sorting.
4158 * @param $prefix string The prefix to be used, specified using
4159 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4160 * prefix.
4161 * @return string
4163 public function getCategorySortkey( $prefix = '' ) {
4164 $unprefixed = $this->getText();
4165 if ( $prefix !== '' ) {
4166 # Separate with a line feed, so the unprefixed part is only used as
4167 # a tiebreaker when two pages have the exact same prefix.
4168 # In UCA, tab is the only character that can sort above LF
4169 # so we strip both of them from the original prefix.
4170 $prefix = strtr( $prefix, "\n\t", ' ' );
4171 return "$prefix\n$unprefixed";
4173 return $unprefixed;