Fix bug that brakes the 'jquery.tabIndex > firstTabIndex' test in IE8/IE9. Some value...
[mediawiki.git] / includes / Title.php
blob441f2917dbacb179868df1f06f4c1a608cea62eb
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
7 /**
8 * Represents a title within MediaWiki.
9 * Optionally may contain an interwiki designation or namespace.
10 * @note This class can fetch various kinds of data from the database;
11 * however, it does so inefficiently.
13 * @internal documentation reviewed 15 Mar 2010
15 class Title {
16 /** @name Static cache variables */
17 // @{
18 static private $titleCache = array();
19 // @}
21 /**
22 * Title::newFromText maintains a cache to avoid expensive re-normalization of
23 * commonly used titles. On a batch operation this can become a memory leak
24 * if not bounded. After hitting this many titles reset the cache.
26 const CACHE_MAX = 1000;
28 /**
29 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
30 * to use the master DB
32 const GAID_FOR_UPDATE = 1;
35 /**
36 * @name Private member variables
37 * Please use the accessor functions instead.
38 * @private
40 // @{
42 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
43 var $mUrlform = ''; // /< URL-encoded form of the main part
44 var $mDbkeyform = ''; // /< Main part with underscores
45 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
46 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
47 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
48 var $mFragment; // /< Title fragment (i.e. the bit after the #)
49 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
50 var $mLatestID = false; // /< ID of most recent revision
51 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
52 var $mOldRestrictions = false;
53 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
54 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
55 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
56 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
57 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
58 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
59 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
60 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
61 # Don't change the following default, NS_MAIN is hardcoded in several
62 # places. See bug 696.
63 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
64 # Zero except in {{transclusion}} tags
65 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
66 var $mLength = -1; // /< The page length, 0 for special pages
67 var $mRedirect = null; // /< Is the article at this title a redirect?
68 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
69 var $mBacklinkCache = null; // /< Cache of links to this title
70 // @}
73 /**
74 * Constructor
76 /*protected*/ function __construct() { }
78 /**
79 * Create a new Title from a prefixed DB key
81 * @param $key String the database key, which has underscores
82 * instead of spaces, possibly including namespace and
83 * interwiki prefixes
84 * @return Title, or NULL on an error
86 public static function newFromDBkey( $key ) {
87 $t = new Title();
88 $t->mDbkeyform = $key;
89 if ( $t->secureAndSplit() ) {
90 return $t;
91 } else {
92 return null;
96 /**
97 * Create a new Title from text, such as what one would find in a link. De-
98 * codes any HTML entities in the text.
100 * @param $text String the link text; spaces, prefixes, and an
101 * initial ':' indicating the main namespace are accepted.
102 * @param $defaultNamespace Int the namespace to use if none is speci-
103 * fied by a prefix. If you want to force a specific namespace even if
104 * $text might begin with a namespace prefix, use makeTitle() or
105 * makeTitleSafe().
106 * @return Title, or null on an error.
108 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
109 if ( is_object( $text ) ) {
110 throw new MWException( 'Title::newFromText given an object' );
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
117 * caching them.
119 * In theory these are value objects and won't get changed...
121 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
122 return Title::$titleCache[$text];
125 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
126 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
128 $t = new Title();
129 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
130 $t->mDefaultNamespace = $defaultNamespace;
132 static $cachedcount = 0 ;
133 if ( $t->secureAndSplit() ) {
134 if ( $defaultNamespace == NS_MAIN ) {
135 if ( $cachedcount >= self::CACHE_MAX ) {
136 # Avoid memory leaks on mass operations...
137 Title::$titleCache = array();
138 $cachedcount = 0;
140 $cachedcount++;
141 Title::$titleCache[$text] =& $t;
143 return $t;
144 } else {
145 $ret = null;
146 return $ret;
151 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
153 * Example of wrong and broken code:
154 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
156 * Example of right code:
157 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
162 * @param $url String the title, as might be taken from a URL
163 * @return Title the new object, or NULL on an error
165 public static function newFromURL( $url ) {
166 global $wgLegalTitleChars;
167 $t = new Title();
169 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
170 # but some URLs used it as a space replacement and they still come
171 # from some external search tools.
172 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
173 $url = str_replace( '+', ' ', $url );
176 $t->mDbkeyform = str_replace( ' ', '_', $url );
177 if ( $t->secureAndSplit() ) {
178 return $t;
179 } else {
180 return null;
185 * Create a new Title from an article ID
187 * @param $id Int the page_id corresponding to the Title to create
188 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
189 * @return Title the new object, or NULL on an error
191 public static function newFromID( $id, $flags = 0 ) {
192 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
193 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
194 if ( $row !== false ) {
195 $title = Title::newFromRow( $row );
196 } else {
197 $title = null;
199 return $title;
203 * Make an array of titles from an array of IDs
205 * @param $ids Array of Int Array of IDs
206 * @return Array of Titles
208 public static function newFromIDs( $ids ) {
209 if ( !count( $ids ) ) {
210 return array();
212 $dbr = wfGetDB( DB_SLAVE );
214 $res = $dbr->select(
215 'page',
216 array(
217 'page_namespace', 'page_title', 'page_id',
218 'page_len', 'page_is_redirect', 'page_latest',
220 array( 'page_id' => $ids ),
221 __METHOD__
224 $titles = array();
225 foreach ( $res as $row ) {
226 $titles[] = Title::newFromRow( $row );
228 return $titles;
232 * Make a Title object from a DB row
234 * @param $row Object database row (needs at least page_title,page_namespace)
235 * @return Title corresponding Title
237 public static function newFromRow( $row ) {
238 $t = self::makeTitle( $row->page_namespace, $row->page_title );
240 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
241 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
242 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
243 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
245 return $t;
249 * Create a new Title from a namespace index and a DB key.
250 * It's assumed that $ns and $title are *valid*, for instance when
251 * they came directly from the database or a special page name.
252 * For convenience, spaces are converted to underscores so that
253 * eg user_text fields can be used directly.
255 * @param $ns Int the namespace of the article
256 * @param $title String the unprefixed database key form
257 * @param $fragment String the link fragment (after the "#")
258 * @param $interwiki String the interwiki prefix
259 * @return Title the new object
261 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
262 $t = new Title();
263 $t->mInterwiki = $interwiki;
264 $t->mFragment = $fragment;
265 $t->mNamespace = $ns = intval( $ns );
266 $t->mDbkeyform = str_replace( ' ', '_', $title );
267 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
268 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
269 $t->mTextform = str_replace( '_', ' ', $title );
270 return $t;
274 * Create a new Title from a namespace index and a DB key.
275 * The parameters will be checked for validity, which is a bit slower
276 * than makeTitle() but safer for user-provided data.
278 * @param $ns Int the namespace of the article
279 * @param $title String database key form
280 * @param $fragment String the link fragment (after the "#")
281 * @param $interwiki String interwiki prefix
282 * @return Title the new object, or NULL on an error
284 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
285 $t = new Title();
286 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
287 if ( $t->secureAndSplit() ) {
288 return $t;
289 } else {
290 return null;
295 * Create a new Title for the Main Page
297 * @return Title the new object
299 public static function newMainPage() {
300 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
301 // Don't give fatal errors if the message is broken
302 if ( !$title ) {
303 $title = Title::newFromText( 'Main Page' );
305 return $title;
309 * Extract a redirect destination from a string and return the
310 * Title, or null if the text doesn't contain a valid redirect
311 * This will only return the very next target, useful for
312 * the redirect table and other checks that don't need full recursion
314 * @param $text String: Text with possible redirect
315 * @return Title: The corresponding Title
317 public static function newFromRedirect( $text ) {
318 return self::newFromRedirectInternal( $text );
322 * Extract a redirect destination from a string and return the
323 * Title, or null if the text doesn't contain a valid redirect
324 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
325 * in order to provide (hopefully) the Title of the final destination instead of another redirect
327 * @param $text String Text with possible redirect
328 * @return Title
330 public static function newFromRedirectRecurse( $text ) {
331 $titles = self::newFromRedirectArray( $text );
332 return $titles ? array_pop( $titles ) : null;
336 * Extract a redirect destination from a string and return an
337 * array of Titles, or null if the text doesn't contain a valid redirect
338 * The last element in the array is the final destination after all redirects
339 * have been resolved (up to $wgMaxRedirects times)
341 * @param $text String Text with possible redirect
342 * @return Array of Titles, with the destination last
344 public static function newFromRedirectArray( $text ) {
345 global $wgMaxRedirects;
346 $title = self::newFromRedirectInternal( $text );
347 if ( is_null( $title ) ) {
348 return null;
350 // recursive check to follow double redirects
351 $recurse = $wgMaxRedirects;
352 $titles = array( $title );
353 while ( --$recurse > 0 ) {
354 if ( $title->isRedirect() ) {
355 $article = new Article( $title, 0 );
356 $newtitle = $article->getRedirectTarget();
357 } else {
358 break;
360 // Redirects to some special pages are not permitted
361 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
362 // the new title passes the checks, so make that our current title so that further recursion can be checked
363 $title = $newtitle;
364 $titles[] = $newtitle;
365 } else {
366 break;
369 return $titles;
373 * Really extract the redirect destination
374 * Do not call this function directly, use one of the newFromRedirect* functions above
376 * @param $text String Text with possible redirect
377 * @return Title
379 protected static function newFromRedirectInternal( $text ) {
380 global $wgMaxRedirects;
381 if ( $wgMaxRedirects < 1 ) {
382 //redirects are disabled, so quit early
383 return null;
385 $redir = MagicWord::get( 'redirect' );
386 $text = trim( $text );
387 if ( $redir->matchStartAndRemove( $text ) ) {
388 // Extract the first link and see if it's usable
389 // Ensure that it really does come directly after #REDIRECT
390 // Some older redirects included a colon, so don't freak about that!
391 $m = array();
392 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
393 // Strip preceding colon used to "escape" categories, etc.
394 // and URL-decode links
395 if ( strpos( $m[1], '%' ) !== false ) {
396 // Match behavior of inline link parsing here;
397 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
399 $title = Title::newFromText( $m[1] );
400 // If the title is a redirect to bad special pages or is invalid, return null
401 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
402 return null;
404 return $title;
407 return null;
410 # ----------------------------------------------------------------------------
411 # Static functions
412 # ----------------------------------------------------------------------------
415 * Get the prefixed DB key associated with an ID
417 * @param $id Int the page_id of the article
418 * @return Title an object representing the article, or NULL if no such article was found
420 public static function nameOf( $id ) {
421 $dbr = wfGetDB( DB_SLAVE );
423 $s = $dbr->selectRow(
424 'page',
425 array( 'page_namespace', 'page_title' ),
426 array( 'page_id' => $id ),
427 __METHOD__
429 if ( $s === false ) {
430 return null;
433 $n = self::makeName( $s->page_namespace, $s->page_title );
434 return $n;
438 * Get a regex character class describing the legal characters in a link
440 * @return String the list of characters, not delimited
442 public static function legalChars() {
443 global $wgLegalTitleChars;
444 return $wgLegalTitleChars;
448 * Get a string representation of a title suitable for
449 * including in a search index
451 * @param $ns Int a namespace index
452 * @param $title String text-form main part
453 * @return String a stripped-down title string ready for the search index
455 public static function indexTitle( $ns, $title ) {
456 global $wgContLang;
458 $lc = SearchEngine::legalSearchChars() . '&#;';
459 $t = $wgContLang->normalizeForSearch( $title );
460 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
461 $t = $wgContLang->lc( $t );
463 # Handle 's, s'
464 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
465 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
467 $t = preg_replace( "/\\s+/", ' ', $t );
469 if ( $ns == NS_FILE ) {
470 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
472 return trim( $t );
476 * Make a prefixed DB key from a DB key and a namespace index
478 * @param $ns Int numerical representation of the namespace
479 * @param $title String the DB key form the title
480 * @param $fragment String The link fragment (after the "#")
481 * @param $interwiki String The interwiki prefix
482 * @return String the prefixed form of the title
484 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
485 global $wgContLang;
487 $namespace = $wgContLang->getNsText( $ns );
488 $name = $namespace == '' ? $title : "$namespace:$title";
489 if ( strval( $interwiki ) != '' ) {
490 $name = "$interwiki:$name";
492 if ( strval( $fragment ) != '' ) {
493 $name .= '#' . $fragment;
495 return $name;
499 * Determine whether the object refers to a page within
500 * this project.
502 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
504 public function isLocal() {
505 if ( $this->mInterwiki != '' ) {
506 return Interwiki::fetch( $this->mInterwiki )->isLocal();
507 } else {
508 return true;
513 * Determine whether the object refers to a page within
514 * this project and is transcludable.
516 * @return Bool TRUE if this is transcludable
518 public function isTrans() {
519 if ( $this->mInterwiki == '' ) {
520 return false;
523 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
527 * Returns the DB name of the distant wiki which owns the object.
529 * @return String the DB name
531 public function getTransWikiID() {
532 if ( $this->mInterwiki == '' ) {
533 return false;
536 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
540 * Escape a text fragment, say from a link, for a URL
542 * @param $fragment string containing a URL or link fragment (after the "#")
543 * @return String: escaped string
545 static function escapeFragmentForURL( $fragment ) {
546 # Note that we don't urlencode the fragment. urlencoded Unicode
547 # fragments appear not to work in IE (at least up to 7) or in at least
548 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
549 # to care if they aren't encoded.
550 return Sanitizer::escapeId( $fragment, 'noninitial' );
553 # ----------------------------------------------------------------------------
554 # Other stuff
555 # ----------------------------------------------------------------------------
557 /** Simple accessors */
559 * Get the text form (spaces not underscores) of the main part
561 * @return String Main part of the title
563 public function getText() { return $this->mTextform; }
566 * Get the URL-encoded form of the main part
568 * @return String Main part of the title, URL-encoded
570 public function getPartialURL() { return $this->mUrlform; }
573 * Get the main part with underscores
575 * @return String: Main part of the title, with underscores
577 public function getDBkey() { return $this->mDbkeyform; }
580 * Get the namespace index, i.e. one of the NS_xxxx constants.
582 * @return Integer: Namespace index
584 public function getNamespace() { return $this->mNamespace; }
587 * Get the namespace text
589 * @return String: Namespace text
591 public function getNsText() {
592 global $wgContLang;
594 if ( $this->mInterwiki != '' ) {
595 // This probably shouldn't even happen. ohh man, oh yuck.
596 // But for interwiki transclusion it sometimes does.
597 // Shit. Shit shit shit.
599 // Use the canonical namespaces if possible to try to
600 // resolve a foreign namespace.
601 if ( MWNamespace::exists( $this->mNamespace ) ) {
602 return MWNamespace::getCanonicalName( $this->mNamespace );
606 if ( $wgContLang->needsGenderDistinction() &&
607 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
608 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
609 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
612 return $wgContLang->getNsText( $this->mNamespace );
616 * Get the DB key with the initial letter case as specified by the user
618 * @return String DB key
620 function getUserCaseDBKey() {
621 return $this->mUserCaseDBKey;
625 * Get the namespace text of the subject (rather than talk) page
627 * @return String Namespace text
629 public function getSubjectNsText() {
630 global $wgContLang;
631 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
635 * Get the namespace text of the talk page
637 * @return String Namespace text
639 public function getTalkNsText() {
640 global $wgContLang;
641 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
645 * Could this title have a corresponding talk page?
647 * @return Bool TRUE or FALSE
649 public function canTalk() {
650 return( MWNamespace::canTalk( $this->mNamespace ) );
654 * Get the interwiki prefix (or null string)
656 * @return String Interwiki prefix
658 public function getInterwiki() { return $this->mInterwiki; }
661 * Get the Title fragment (i.e.\ the bit after the #) in text form
663 * @return String Title fragment
665 public function getFragment() { return $this->mFragment; }
668 * Get the fragment in URL form, including the "#" character if there is one
669 * @return String Fragment in URL form
671 public function getFragmentForURL() {
672 if ( $this->mFragment == '' ) {
673 return '';
674 } else {
675 return '#' . Title::escapeFragmentForURL( $this->mFragment );
680 * Get the default namespace index, for when there is no namespace
682 * @return Int Default namespace index
684 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
687 * Get title for search index
689 * @return String a stripped-down title string ready for the
690 * search index
692 public function getIndexTitle() {
693 return Title::indexTitle( $this->mNamespace, $this->mTextform );
697 * Get the prefixed database key form
699 * @return String the prefixed title, with underscores and
700 * any interwiki and namespace prefixes
702 public function getPrefixedDBkey() {
703 $s = $this->prefix( $this->mDbkeyform );
704 $s = str_replace( ' ', '_', $s );
705 return $s;
709 * Get the prefixed title with spaces.
710 * This is the form usually used for display
712 * @return String the prefixed title, with spaces
714 public function getPrefixedText() {
715 // @todo FIXME: Bad usage of empty() ?
716 if ( empty( $this->mPrefixedText ) ) {
717 $s = $this->prefix( $this->mTextform );
718 $s = str_replace( '_', ' ', $s );
719 $this->mPrefixedText = $s;
721 return $this->mPrefixedText;
725 * Get the prefixed title with spaces, plus any fragment
726 * (part beginning with '#')
728 * @return String the prefixed title, with spaces and the fragment, including '#'
730 public function getFullText() {
731 $text = $this->getPrefixedText();
732 if ( $this->mFragment != '' ) {
733 $text .= '#' . $this->mFragment;
735 return $text;
739 * Get the base name, i.e. the leftmost parts before the /
741 * @return String Base name
743 public function getBaseText() {
744 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
745 return $this->getText();
748 $parts = explode( '/', $this->getText() );
749 # Don't discard the real title if there's no subpage involved
750 if ( count( $parts ) > 1 ) {
751 unset( $parts[count( $parts ) - 1] );
753 return implode( '/', $parts );
757 * Get the lowest-level subpage name, i.e. the rightmost part after /
759 * @return String Subpage name
761 public function getSubpageText() {
762 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
763 return( $this->mTextform );
765 $parts = explode( '/', $this->mTextform );
766 return( $parts[count( $parts ) - 1] );
770 * Get a URL-encoded form of the subpage text
772 * @return String URL-encoded subpage name
774 public function getSubpageUrlForm() {
775 $text = $this->getSubpageText();
776 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
777 return( $text );
781 * Get a URL-encoded title (not an actual URL) including interwiki
783 * @return String the URL-encoded form
785 public function getPrefixedURL() {
786 $s = $this->prefix( $this->mDbkeyform );
787 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
788 return $s;
792 * Get a real URL referring to this title, with interwiki link and
793 * fragment
795 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
796 * links. Can be specified as an associative array as well, e.g.,
797 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
798 * @param $variant String language variant of url (for sr, zh..)
799 * @return String the URL
801 public function getFullURL( $query = '', $variant = false ) {
802 global $wgServer, $wgRequest;
804 if ( is_array( $query ) ) {
805 $query = wfArrayToCGI( $query );
808 $interwiki = Interwiki::fetch( $this->mInterwiki );
809 if ( !$interwiki ) {
810 $url = $this->getLocalURL( $query, $variant );
812 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
813 // Correct fix would be to move the prepending elsewhere.
814 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
815 $url = $wgServer . $url;
817 } else {
818 $baseUrl = $interwiki->getURL();
820 $namespace = wfUrlencode( $this->getNsText() );
821 if ( $namespace != '' ) {
822 # Can this actually happen? Interwikis shouldn't be parsed.
823 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
824 $namespace .= ':';
826 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
827 $url = wfAppendQuery( $url, $query );
830 # Finally, add the fragment.
831 $url .= $this->getFragmentForURL();
833 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
834 return $url;
838 * Get a URL with no fragment or server name. If this page is generated
839 * with action=render, $wgServer is prepended.
841 * @param $query Mixed: an optional query string; if not specified,
842 * $wgArticlePath will be used. Can be specified as an associative array
843 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
844 * URL-escaped).
845 * @param $variant String language variant of url (for sr, zh..)
846 * @return String the URL
848 public function getLocalURL( $query = '', $variant = false ) {
849 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
850 global $wgVariantArticlePath, $wgContLang;
852 if ( is_array( $query ) ) {
853 $query = wfArrayToCGI( $query );
856 if ( $this->isExternal() ) {
857 $url = $this->getFullURL();
858 if ( $query ) {
859 // This is currently only used for edit section links in the
860 // context of interwiki transclusion. In theory we should
861 // append the query to the end of any existing query string,
862 // but interwiki transclusion is already broken in that case.
863 $url .= "?$query";
865 } else {
866 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
867 if ( $query == '' ) {
868 if ( $variant != false && $wgContLang->hasVariants() ) {
869 if ( !$wgVariantArticlePath ) {
870 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
871 } else {
872 $variantArticlePath = $wgVariantArticlePath;
874 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
875 $url = str_replace( '$1', $dbkey, $url );
876 } else {
877 $url = str_replace( '$1', $dbkey, $wgArticlePath );
879 } else {
880 global $wgActionPaths;
881 $url = false;
882 $matches = array();
883 if ( !empty( $wgActionPaths ) &&
884 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
886 $action = urldecode( $matches[2] );
887 if ( isset( $wgActionPaths[$action] ) ) {
888 $query = $matches[1];
889 if ( isset( $matches[4] ) ) {
890 $query .= $matches[4];
892 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
893 if ( $query != '' ) {
894 $url = wfAppendQuery( $url, $query );
899 if ( $url === false ) {
900 if ( $query == '-' ) {
901 $query = '';
903 $url = "{$wgScript}?title={$dbkey}&{$query}";
907 // @todo FIXME: This causes breakage in various places when we
908 // actually expected a local URL and end up with dupe prefixes.
909 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
910 $url = $wgServer . $url;
913 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
914 return $url;
918 * Get a URL that's the simplest URL that will be valid to link, locally,
919 * to the current Title. It includes the fragment, but does not include
920 * the server unless action=render is used (or the link is external). If
921 * there's a fragment but the prefixed text is empty, we just return a link
922 * to the fragment.
924 * The result obviously should not be URL-escaped, but does need to be
925 * HTML-escaped if it's being output in HTML.
927 * @param $query Array of Strings An associative array of key => value pairs for the
928 * query string. Keys and values will be escaped.
929 * @param $variant String language variant of URL (for sr, zh..). Ignored
930 * for external links. Default is "false" (same variant as current page,
931 * for anonymous users).
932 * @return String the URL
934 public function getLinkUrl( $query = array(), $variant = false ) {
935 wfProfileIn( __METHOD__ );
936 if ( $this->isExternal() ) {
937 $ret = $this->getFullURL( $query );
938 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
939 $ret = $this->getFragmentForURL();
940 } else {
941 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
943 wfProfileOut( __METHOD__ );
944 return $ret;
948 * Get an HTML-escaped version of the URL form, suitable for
949 * using in a link, without a server name or fragment
951 * @param $query String an optional query string
952 * @return String the URL
954 public function escapeLocalURL( $query = '' ) {
955 return htmlspecialchars( $this->getLocalURL( $query ) );
959 * Get an HTML-escaped version of the URL form, suitable for
960 * using in a link, including the server name and fragment
962 * @param $query String an optional query string
963 * @return String the URL
965 public function escapeFullURL( $query = '' ) {
966 return htmlspecialchars( $this->getFullURL( $query ) );
970 * Get the URL form for an internal link.
971 * - Used in various Squid-related code, in case we have a different
972 * internal hostname for the server from the exposed one.
974 * @param $query String an optional query string
975 * @param $variant String language variant of url (for sr, zh..)
976 * @return String the URL
978 public function getInternalURL( $query = '', $variant = false ) {
979 global $wgInternalServer, $wgServer;
980 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
981 $url = $server . $this->getLocalURL( $query, $variant );
982 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
983 return $url;
987 * Get the edit URL for this Title
989 * @return String the URL, or a null string if this is an
990 * interwiki link
992 public function getEditURL() {
993 if ( $this->mInterwiki != '' ) {
994 return '';
996 $s = $this->getLocalURL( 'action=edit' );
998 return $s;
1002 * Get the HTML-escaped displayable text form.
1003 * Used for the title field in <a> tags.
1005 * @return String the text, including any prefixes
1007 public function getEscapedText() {
1008 return htmlspecialchars( $this->getPrefixedText() );
1012 * Is this Title interwiki?
1014 * @return Bool
1016 public function isExternal() {
1017 return ( $this->mInterwiki != '' );
1021 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1023 * @param $action String Action to check (default: edit)
1024 * @return Bool
1026 public function isSemiProtected( $action = 'edit' ) {
1027 if ( $this->exists() ) {
1028 $restrictions = $this->getRestrictions( $action );
1029 if ( count( $restrictions ) > 0 ) {
1030 foreach ( $restrictions as $restriction ) {
1031 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1032 return false;
1035 } else {
1036 # Not protected
1037 return false;
1039 return true;
1040 } else {
1041 # If it doesn't exist, it can't be protected
1042 return false;
1047 * Does the title correspond to a protected article?
1049 * @param $action String the action the page is protected from,
1050 * by default checks all actions.
1051 * @return Bool
1053 public function isProtected( $action = '' ) {
1054 global $wgRestrictionLevels;
1056 $restrictionTypes = $this->getRestrictionTypes();
1058 # Special pages have inherent protection
1059 if( $this->getNamespace() == NS_SPECIAL ) {
1060 return true;
1063 # Check regular protection levels
1064 foreach ( $restrictionTypes as $type ) {
1065 if ( $action == $type || $action == '' ) {
1066 $r = $this->getRestrictions( $type );
1067 foreach ( $wgRestrictionLevels as $level ) {
1068 if ( in_array( $level, $r ) && $level != '' ) {
1069 return true;
1075 return false;
1079 * Is this a conversion table for the LanguageConverter?
1081 * @return Bool
1083 public function isConversionTable() {
1085 $this->getNamespace() == NS_MEDIAWIKI &&
1086 strpos( $this->getText(), 'Conversiontable' ) !== false
1089 return true;
1092 return false;
1096 * Is $wgUser watching this page?
1098 * @return Bool
1100 public function userIsWatching() {
1101 global $wgUser;
1103 if ( is_null( $this->mWatched ) ) {
1104 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1105 $this->mWatched = false;
1106 } else {
1107 $this->mWatched = $wgUser->isWatched( $this );
1110 return $this->mWatched;
1114 * Can $wgUser perform $action on this page?
1115 * This skips potentially expensive cascading permission checks
1116 * as well as avoids expensive error formatting
1118 * Suitable for use for nonessential UI controls in common cases, but
1119 * _not_ for functional access control.
1121 * May provide false positives, but should never provide a false negative.
1123 * @param $action String action that permission needs to be checked for
1124 * @return Bool
1126 public function quickUserCan( $action ) {
1127 return $this->userCan( $action, false );
1131 * Determines if $user is unable to edit this page because it has been protected
1132 * by $wgNamespaceProtection.
1134 * @param $user User object, $wgUser will be used if not passed
1135 * @return Bool
1137 public function isNamespaceProtected( User $user = null ) {
1138 global $wgNamespaceProtection;
1140 if ( $user === null ) {
1141 global $wgUser;
1142 $user = $wgUser;
1145 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1146 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1147 if ( $right != '' && !$user->isAllowed( $right ) ) {
1148 return true;
1152 return false;
1156 * Can $wgUser perform $action on this page?
1158 * @param $action String action that permission needs to be checked for
1159 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1160 * @return Bool
1162 public function userCan( $action, $doExpensiveQueries = true ) {
1163 global $wgUser;
1164 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1168 * Can $user perform $action on this page?
1170 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1172 * @param $action String action that permission needs to be checked for
1173 * @param $user User to check
1174 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1175 * skipping checks for cascading protections and user blocks.
1176 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1177 * @return Array of arguments to wfMsg to explain permissions problems.
1179 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1180 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1182 // Remove the errors being ignored.
1183 foreach ( $errors as $index => $error ) {
1184 $error_key = is_array( $error ) ? $error[0] : $error;
1186 if ( in_array( $error_key, $ignoreErrors ) ) {
1187 unset( $errors[$index] );
1191 return $errors;
1195 * Permissions checks that fail most often, and which are easiest to test.
1197 * @param $action String the action to check
1198 * @param $user User user to check
1199 * @param $errors Array list of current errors
1200 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1201 * @param $short Boolean short circuit on first error
1203 * @return Array list of errors
1205 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1206 if ( $action == 'create' ) {
1207 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1208 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1209 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1211 } elseif ( $action == 'move' ) {
1212 if ( !$user->isAllowed( 'move-rootuserpages' )
1213 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1214 // Show user page-specific message only if the user can move other pages
1215 $errors[] = array( 'cant-move-user-page' );
1218 // Check if user is allowed to move files if it's a file
1219 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1220 $errors[] = array( 'movenotallowedfile' );
1223 if ( !$user->isAllowed( 'move' ) ) {
1224 // User can't move anything
1225 global $wgGroupPermissions;
1226 $userCanMove = false;
1227 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1228 $userCanMove = $wgGroupPermissions['user']['move'];
1230 $autoconfirmedCanMove = false;
1231 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1232 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1234 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1235 // custom message if logged-in users without any special rights can move
1236 $errors[] = array( 'movenologintext' );
1237 } else {
1238 $errors[] = array( 'movenotallowed' );
1241 } elseif ( $action == 'move-target' ) {
1242 if ( !$user->isAllowed( 'move' ) ) {
1243 // User can't move anything
1244 $errors[] = array( 'movenotallowed' );
1245 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1246 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1247 // Show user page-specific message only if the user can move other pages
1248 $errors[] = array( 'cant-move-to-user-page' );
1250 } elseif ( !$user->isAllowed( $action ) ) {
1251 // We avoid expensive display logic for quickUserCan's and such
1252 $groups = false;
1253 if ( !$short ) {
1254 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1255 User::getGroupsWithPermission( $action ) );
1258 if ( $groups ) {
1259 global $wgLang;
1260 $return = array(
1261 'badaccess-groups',
1262 $wgLang->commaList( $groups ),
1263 count( $groups )
1265 } else {
1266 $return = array( 'badaccess-group0' );
1268 $errors[] = $return;
1271 return $errors;
1275 * Add the resulting error code to the errors array
1277 * @param $errors Array list of current errors
1278 * @param $result Mixed result of errors
1280 * @return Array list of errors
1282 private function resultToError( $errors, $result ) {
1283 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1284 // A single array representing an error
1285 $errors[] = $result;
1286 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1287 // A nested array representing multiple errors
1288 $errors = array_merge( $errors, $result );
1289 } else if ( $result !== '' && is_string( $result ) ) {
1290 // A string representing a message-id
1291 $errors[] = array( $result );
1292 } else if ( $result === false ) {
1293 // a generic "We don't want them to do that"
1294 $errors[] = array( 'badaccess-group0' );
1296 return $errors;
1300 * Check various permission hooks
1302 * @param $action String the action to check
1303 * @param $user User user to check
1304 * @param $errors Array list of current errors
1305 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1306 * @param $short Boolean short circuit on first error
1308 * @return Array list of errors
1310 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1311 // Use getUserPermissionsErrors instead
1312 $result = '';
1313 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1314 return $result ? array() : array( array( 'badaccess-group0' ) );
1316 // Check getUserPermissionsErrors hook
1317 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1318 $errors = $this->resultToError( $errors, $result );
1320 // Check getUserPermissionsErrorsExpensive hook
1321 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1322 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1323 $errors = $this->resultToError( $errors, $result );
1326 return $errors;
1330 * Check permissions on special pages & namespaces
1332 * @param $action String the action to check
1333 * @param $user User user to check
1334 * @param $errors Array list of current errors
1335 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1336 * @param $short Boolean short circuit on first error
1338 * @return Array list of errors
1340 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1341 # Only 'createaccount' and 'execute' can be performed on
1342 # special pages, which don't actually exist in the DB.
1343 $specialOKActions = array( 'createaccount', 'execute' );
1344 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1345 $errors[] = array( 'ns-specialprotected' );
1348 # Check $wgNamespaceProtection for restricted namespaces
1349 if ( $this->isNamespaceProtected( $user ) ) {
1350 $ns = $this->mNamespace == NS_MAIN ?
1351 wfMsg( 'nstab-main' ) : $this->getNsText();
1352 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1353 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1356 return $errors;
1360 * Check CSS/JS sub-page permissions
1362 * @param $action String the action to check
1363 * @param $user User user to check
1364 * @param $errors Array list of current errors
1365 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1366 * @param $short Boolean short circuit on first error
1368 * @return Array list of errors
1370 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1371 # Protect css/js subpages of user pages
1372 # XXX: this might be better using restrictions
1373 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1374 # and $this->userCanEditJsSubpage() from working
1375 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1376 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1377 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1378 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1379 $errors[] = array( 'customcssprotected' );
1380 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1381 $errors[] = array( 'customjsprotected' );
1385 return $errors;
1389 * Check against page_restrictions table requirements on this
1390 * page. The user must possess all required rights for this
1391 * action.
1393 * @param $action String the action to check
1394 * @param $user User user to check
1395 * @param $errors Array list of current errors
1396 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1397 * @param $short Boolean short circuit on first error
1399 * @return Array list of errors
1401 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1402 foreach ( $this->getRestrictions( $action ) as $right ) {
1403 // Backwards compatibility, rewrite sysop -> protect
1404 if ( $right == 'sysop' ) {
1405 $right = 'protect';
1407 if ( $right != '' && !$user->isAllowed( $right ) ) {
1408 // Users with 'editprotected' permission can edit protected pages
1409 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1410 // Users with 'editprotected' permission cannot edit protected pages
1411 // with cascading option turned on.
1412 if ( $this->mCascadeRestriction ) {
1413 $errors[] = array( 'protectedpagetext', $right );
1415 } else {
1416 $errors[] = array( 'protectedpagetext', $right );
1421 return $errors;
1425 * Check restrictions on cascading pages.
1427 * @param $action String the action to check
1428 * @param $user User to check
1429 * @param $errors Array list of current errors
1430 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1431 * @param $short Boolean short circuit on first error
1433 * @return Array list of errors
1435 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1436 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1437 # We /could/ use the protection level on the source page, but it's
1438 # fairly ugly as we have to establish a precedence hierarchy for pages
1439 # included by multiple cascade-protected pages. So just restrict
1440 # it to people with 'protect' permission, as they could remove the
1441 # protection anyway.
1442 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1443 # Cascading protection depends on more than this page...
1444 # Several cascading protected pages may include this page...
1445 # Check each cascading level
1446 # This is only for protection restrictions, not for all actions
1447 if ( isset( $restrictions[$action] ) ) {
1448 foreach ( $restrictions[$action] as $right ) {
1449 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1450 if ( $right != '' && !$user->isAllowed( $right ) ) {
1451 $pages = '';
1452 foreach ( $cascadingSources as $page )
1453 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1454 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1460 return $errors;
1464 * Check action permissions not already checked in checkQuickPermissions
1466 * @param $action String the action to check
1467 * @param $user User to check
1468 * @param $errors Array list of current errors
1469 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1470 * @param $short Boolean short circuit on first error
1472 * @return Array list of errors
1474 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1475 if ( $action == 'protect' ) {
1476 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1477 // If they can't edit, they shouldn't protect.
1478 $errors[] = array( 'protect-cantedit' );
1480 } elseif ( $action == 'create' ) {
1481 $title_protection = $this->getTitleProtection();
1482 if( $title_protection ) {
1483 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1484 $title_protection['pt_create_perm'] = 'protect'; // B/C
1486 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1487 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1490 } elseif ( $action == 'move' ) {
1491 // Check for immobile pages
1492 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1493 // Specific message for this case
1494 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1495 } elseif ( !$this->isMovable() ) {
1496 // Less specific message for rarer cases
1497 $errors[] = array( 'immobile-page' );
1499 } elseif ( $action == 'move-target' ) {
1500 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1501 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1502 } elseif ( !$this->isMovable() ) {
1503 $errors[] = array( 'immobile-target-page' );
1506 return $errors;
1510 * Check that the user isn't blocked from editting.
1512 * @param $action String the action to check
1513 * @param $user User to check
1514 * @param $errors Array list of current errors
1515 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1516 * @param $short Boolean short circuit on first error
1518 * @return Array list of errors
1520 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1521 if( !$doExpensiveQueries ) {
1522 return $errors;
1525 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1527 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1528 $errors[] = array( 'confirmedittext' );
1531 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1532 // Edit blocks should not affect reading.
1533 // Account creation blocks handled at userlogin.
1534 // Unblocking handled in SpecialUnblock
1535 } elseif( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1536 // Don't block the user from editing their own talk page unless they've been
1537 // explicitly blocked from that too.
1538 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1539 $block = $user->mBlock;
1541 // This is from OutputPage::blockedPage
1542 // Copied at r23888 by werdna
1544 $id = $user->blockedBy();
1545 $reason = $user->blockedFor();
1546 if ( $reason == '' ) {
1547 $reason = wfMsg( 'blockednoreason' );
1549 $ip = wfGetIP();
1551 if ( is_numeric( $id ) ) {
1552 $name = User::whoIs( $id );
1553 } else {
1554 $name = $id;
1557 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1558 $blockid = $block->getId();
1559 $blockExpiry = $user->mBlock->mExpiry;
1560 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1561 if ( $blockExpiry == 'infinity' ) {
1562 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1563 } else {
1564 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1567 $intended = strval( $user->mBlock->getTarget() );
1569 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1570 $blockid, $blockExpiry, $intended, $blockTimestamp );
1573 return $errors;
1577 * Can $user perform $action on this page? This is an internal function,
1578 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1579 * checks on wfReadOnly() and blocks)
1581 * @param $action String action that permission needs to be checked for
1582 * @param $user User to check
1583 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1584 * @param $short Bool Set this to true to stop after the first permission error.
1585 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1587 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1588 wfProfileIn( __METHOD__ );
1590 $errors = array();
1591 $checks = array(
1592 'checkQuickPermissions',
1593 'checkPermissionHooks',
1594 'checkSpecialsAndNSPermissions',
1595 'checkCSSandJSPermissions',
1596 'checkPageRestrictions',
1597 'checkCascadingSourcesRestrictions',
1598 'checkActionPermissions',
1599 'checkUserBlock'
1602 while( count( $checks ) > 0 &&
1603 !( $short && count( $errors ) > 0 ) ) {
1604 $method = array_shift( $checks );
1605 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1608 wfProfileOut( __METHOD__ );
1609 return $errors;
1613 * Is this title subject to title protection?
1614 * Title protection is the one applied against creation of such title.
1616 * @return Mixed An associative array representing any existent title
1617 * protection, or false if there's none.
1619 private function getTitleProtection() {
1620 // Can't protect pages in special namespaces
1621 if ( $this->getNamespace() < 0 ) {
1622 return false;
1625 // Can't protect pages that exist.
1626 if ( $this->exists() ) {
1627 return false;
1630 if ( !isset( $this->mTitleProtection ) ) {
1631 $dbr = wfGetDB( DB_SLAVE );
1632 $res = $dbr->select( 'protected_titles', '*',
1633 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1634 __METHOD__ );
1636 // fetchRow returns false if there are no rows.
1637 $this->mTitleProtection = $dbr->fetchRow( $res );
1639 return $this->mTitleProtection;
1643 * Update the title protection status
1645 * @param $create_perm String Permission required for creation
1646 * @param $reason String Reason for protection
1647 * @param $expiry String Expiry timestamp
1648 * @return boolean true
1650 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1651 global $wgUser, $wgContLang;
1653 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1654 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1655 // No change
1656 return true;
1659 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1661 $dbw = wfGetDB( DB_MASTER );
1663 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1665 $expiry_description = '';
1666 if ( $encodedExpiry != $dbw->getInfinity() ) {
1667 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1668 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1669 } else {
1670 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1673 # Update protection table
1674 if ( $create_perm != '' ) {
1675 $this->mTitleProtection = array(
1676 'pt_namespace' => $namespace,
1677 'pt_title' => $title,
1678 'pt_create_perm' => $create_perm,
1679 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1680 'pt_expiry' => $encodedExpiry,
1681 'pt_user' => $wgUser->getId(),
1682 'pt_reason' => $reason,
1684 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1685 $this->mTitleProtection, __METHOD__ );
1686 } else {
1687 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1688 'pt_title' => $title ), __METHOD__ );
1689 $this->mTitleProtection = false;
1692 # Update the protection log
1693 if ( $dbw->affectedRows() ) {
1694 $log = new LogPage( 'protect' );
1696 if ( $create_perm ) {
1697 $params = array( "[create=$create_perm] $expiry_description", '' );
1698 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1699 } else {
1700 $log->addEntry( 'unprotect', $this, $reason );
1704 return true;
1708 * Remove any title protection due to page existing
1710 public function deleteTitleProtection() {
1711 $dbw = wfGetDB( DB_MASTER );
1713 $dbw->delete(
1714 'protected_titles',
1715 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1716 __METHOD__
1718 $this->mTitleProtection = false;
1722 * Would anybody with sufficient privileges be able to move this page?
1723 * Some pages just aren't movable.
1725 * @return Bool TRUE or FALSE
1727 public function isMovable() {
1728 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1732 * Can $wgUser read this page?
1734 * @return Bool
1735 * @todo fold these checks into userCan()
1737 public function userCanRead() {
1738 global $wgUser, $wgGroupPermissions;
1740 static $useShortcut = null;
1742 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1743 if ( is_null( $useShortcut ) ) {
1744 global $wgRevokePermissions;
1745 $useShortcut = true;
1746 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1747 # Not a public wiki, so no shortcut
1748 $useShortcut = false;
1749 } elseif ( !empty( $wgRevokePermissions ) ) {
1751 * Iterate through each group with permissions being revoked (key not included since we don't care
1752 * what the group name is), then check if the read permission is being revoked. If it is, then
1753 * we don't use the shortcut below since the user might not be able to read, even though anon
1754 * reading is allowed.
1756 foreach ( $wgRevokePermissions as $perms ) {
1757 if ( !empty( $perms['read'] ) ) {
1758 # We might be removing the read right from the user, so no shortcut
1759 $useShortcut = false;
1760 break;
1766 $result = null;
1767 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1768 if ( $result !== null ) {
1769 return $result;
1772 # Shortcut for public wikis, allows skipping quite a bit of code
1773 if ( $useShortcut ) {
1774 return true;
1777 if ( $wgUser->isAllowed( 'read' ) ) {
1778 return true;
1779 } else {
1780 global $wgWhitelistRead;
1782 # Always grant access to the login page.
1783 # Even anons need to be able to log in.
1784 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'ChangePassword' ) ) {
1785 return true;
1788 # Bail out if there isn't whitelist
1789 if ( !is_array( $wgWhitelistRead ) ) {
1790 return false;
1793 # Check for explicit whitelisting
1794 $name = $this->getPrefixedText();
1795 $dbName = $this->getPrefixedDBKey();
1796 // Check with and without underscores
1797 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1798 return true;
1800 # Old settings might have the title prefixed with
1801 # a colon for main-namespace pages
1802 if ( $this->getNamespace() == NS_MAIN ) {
1803 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1804 return true;
1808 # If it's a special page, ditch the subpage bit and check again
1809 if ( $this->getNamespace() == NS_SPECIAL ) {
1810 $name = $this->getDBkey();
1811 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
1812 if ( $name === false ) {
1813 # Invalid special page, but we show standard login required message
1814 return false;
1817 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1818 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1819 return true;
1824 return false;
1828 * Is this the mainpage?
1829 * @note Title::newFromText seams to be sufficiently optimized by the title
1830 * cache that we don't need to over-optimize by doing direct comparisons and
1831 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1832 * ends up reporting something differently than $title->isMainPage();
1834 * @return Bool
1836 public function isMainPage() {
1837 return $this->equals( Title::newMainPage() );
1841 * Is this a talk page of some sort?
1843 * @return Bool
1845 public function isTalkPage() {
1846 return MWNamespace::isTalk( $this->getNamespace() );
1850 * Is this a subpage?
1852 * @return Bool
1854 public function isSubpage() {
1855 return MWNamespace::hasSubpages( $this->mNamespace )
1856 ? strpos( $this->getText(), '/' ) !== false
1857 : false;
1861 * Does this have subpages? (Warning, usually requires an extra DB query.)
1863 * @return Bool
1865 public function hasSubpages() {
1866 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1867 # Duh
1868 return false;
1871 # We dynamically add a member variable for the purpose of this method
1872 # alone to cache the result. There's no point in having it hanging
1873 # around uninitialized in every Title object; therefore we only add it
1874 # if needed and don't declare it statically.
1875 if ( isset( $this->mHasSubpages ) ) {
1876 return $this->mHasSubpages;
1879 $subpages = $this->getSubpages( 1 );
1880 if ( $subpages instanceof TitleArray ) {
1881 return $this->mHasSubpages = (bool)$subpages->count();
1883 return $this->mHasSubpages = false;
1887 * Get all subpages of this page.
1889 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1890 * @return mixed TitleArray, or empty array if this page's namespace
1891 * doesn't allow subpages
1893 public function getSubpages( $limit = -1 ) {
1894 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1895 return array();
1898 $dbr = wfGetDB( DB_SLAVE );
1899 $conds['page_namespace'] = $this->getNamespace();
1900 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1901 $options = array();
1902 if ( $limit > -1 ) {
1903 $options['LIMIT'] = $limit;
1905 return $this->mSubpages = TitleArray::newFromResult(
1906 $dbr->select( 'page',
1907 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1908 $conds,
1909 __METHOD__,
1910 $options
1916 * Could this page contain custom CSS or JavaScript, based
1917 * on the title?
1919 * @return Bool
1921 public function isCssOrJsPage() {
1922 return $this->mNamespace == NS_MEDIAWIKI
1923 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1927 * Is this a .css or .js subpage of a user page?
1928 * @return Bool
1930 public function isCssJsSubpage() {
1931 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1935 * Is this a *valid* .css or .js subpage of a user page?
1937 * @return Bool
1938 * @deprecated since 1.17
1940 public function isValidCssJsSubpage() {
1941 return $this->isCssJsSubpage();
1945 * Trim down a .css or .js subpage title to get the corresponding skin name
1947 * @return string containing skin name from .css or .js subpage title
1949 public function getSkinFromCssJsSubpage() {
1950 $subpage = explode( '/', $this->mTextform );
1951 $subpage = $subpage[ count( $subpage ) - 1 ];
1952 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1956 * Is this a .css subpage of a user page?
1958 * @return Bool
1960 public function isCssSubpage() {
1961 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1965 * Is this a .js subpage of a user page?
1967 * @return Bool
1969 public function isJsSubpage() {
1970 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1974 * Protect css subpages of user pages: can $wgUser edit
1975 * this page?
1977 * @return Bool
1978 * @todo XXX: this might be better using restrictions
1980 public function userCanEditCssSubpage() {
1981 global $wgUser;
1982 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1983 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
1987 * Protect js subpages of user pages: can $wgUser edit
1988 * this page?
1990 * @return Bool
1991 * @todo XXX: this might be better using restrictions
1993 public function userCanEditJsSubpage() {
1994 global $wgUser;
1995 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
1996 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2000 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2002 * @return Bool If the page is subject to cascading restrictions.
2004 public function isCascadeProtected() {
2005 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2006 return ( $sources > 0 );
2010 * Cascading protection: Get the source of any cascading restrictions on this page.
2012 * @param $getPages Bool Whether or not to retrieve the actual pages
2013 * that the restrictions have come from.
2014 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2015 * have come, false for none, or true if such restrictions exist, but $getPages
2016 * was not set. The restriction array is an array of each type, each of which
2017 * contains a array of unique groups.
2019 public function getCascadeProtectionSources( $getPages = true ) {
2020 global $wgContLang;
2021 $pagerestrictions = array();
2023 if ( isset( $this->mCascadeSources ) && $getPages ) {
2024 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2025 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2026 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2029 wfProfileIn( __METHOD__ );
2031 $dbr = wfGetDB( DB_SLAVE );
2033 if ( $this->getNamespace() == NS_FILE ) {
2034 $tables = array( 'imagelinks', 'page_restrictions' );
2035 $where_clauses = array(
2036 'il_to' => $this->getDBkey(),
2037 'il_from=pr_page',
2038 'pr_cascade' => 1
2040 } else {
2041 $tables = array( 'templatelinks', 'page_restrictions' );
2042 $where_clauses = array(
2043 'tl_namespace' => $this->getNamespace(),
2044 'tl_title' => $this->getDBkey(),
2045 'tl_from=pr_page',
2046 'pr_cascade' => 1
2050 if ( $getPages ) {
2051 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2052 'pr_expiry', 'pr_type', 'pr_level' );
2053 $where_clauses[] = 'page_id=pr_page';
2054 $tables[] = 'page';
2055 } else {
2056 $cols = array( 'pr_expiry' );
2059 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2061 $sources = $getPages ? array() : false;
2062 $now = wfTimestampNow();
2063 $purgeExpired = false;
2065 foreach ( $res as $row ) {
2066 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2067 if ( $expiry > $now ) {
2068 if ( $getPages ) {
2069 $page_id = $row->pr_page;
2070 $page_ns = $row->page_namespace;
2071 $page_title = $row->page_title;
2072 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2073 # Add groups needed for each restriction type if its not already there
2074 # Make sure this restriction type still exists
2076 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2077 $pagerestrictions[$row->pr_type] = array();
2080 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2081 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2082 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2084 } else {
2085 $sources = true;
2087 } else {
2088 // Trigger lazy purge of expired restrictions from the db
2089 $purgeExpired = true;
2092 if ( $purgeExpired ) {
2093 Title::purgeExpiredRestrictions();
2096 if ( $getPages ) {
2097 $this->mCascadeSources = $sources;
2098 $this->mCascadingRestrictions = $pagerestrictions;
2099 } else {
2100 $this->mHasCascadingRestrictions = $sources;
2103 wfProfileOut( __METHOD__ );
2104 return array( $sources, $pagerestrictions );
2108 * Returns cascading restrictions for the current article
2110 * @return Boolean
2112 function areRestrictionsCascading() {
2113 if ( !$this->mRestrictionsLoaded ) {
2114 $this->loadRestrictions();
2117 return $this->mCascadeRestriction;
2121 * Loads a string into mRestrictions array
2123 * @param $res Resource restrictions as an SQL result.
2124 * @param $oldFashionedRestrictions String comma-separated list of page
2125 * restrictions from page table (pre 1.10)
2127 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2128 $rows = array();
2130 foreach ( $res as $row ) {
2131 $rows[] = $row;
2134 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2138 * Compiles list of active page restrictions from both page table (pre 1.10)
2139 * and page_restrictions table for this existing page.
2140 * Public for usage by LiquidThreads.
2142 * @param $rows array of db result objects
2143 * @param $oldFashionedRestrictions string comma-separated list of page
2144 * restrictions from page table (pre 1.10)
2146 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2147 global $wgContLang;
2148 $dbr = wfGetDB( DB_SLAVE );
2150 $restrictionTypes = $this->getRestrictionTypes();
2152 foreach ( $restrictionTypes as $type ) {
2153 $this->mRestrictions[$type] = array();
2154 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2157 $this->mCascadeRestriction = false;
2159 # Backwards-compatibility: also load the restrictions from the page record (old format).
2161 if ( $oldFashionedRestrictions === null ) {
2162 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2163 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2166 if ( $oldFashionedRestrictions != '' ) {
2168 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2169 $temp = explode( '=', trim( $restrict ) );
2170 if ( count( $temp ) == 1 ) {
2171 // old old format should be treated as edit/move restriction
2172 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2173 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2174 } else {
2175 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2179 $this->mOldRestrictions = true;
2183 if ( count( $rows ) ) {
2184 # Current system - load second to make them override.
2185 $now = wfTimestampNow();
2186 $purgeExpired = false;
2188 # Cycle through all the restrictions.
2189 foreach ( $rows as $row ) {
2191 // Don't take care of restrictions types that aren't allowed
2192 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2193 continue;
2195 // This code should be refactored, now that it's being used more generally,
2196 // But I don't really see any harm in leaving it in Block for now -werdna
2197 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2199 // Only apply the restrictions if they haven't expired!
2200 if ( !$expiry || $expiry > $now ) {
2201 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2202 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2204 $this->mCascadeRestriction |= $row->pr_cascade;
2205 } else {
2206 // Trigger a lazy purge of expired restrictions
2207 $purgeExpired = true;
2211 if ( $purgeExpired ) {
2212 Title::purgeExpiredRestrictions();
2216 $this->mRestrictionsLoaded = true;
2220 * Load restrictions from the page_restrictions table
2222 * @param $oldFashionedRestrictions String comma-separated list of page
2223 * restrictions from page table (pre 1.10)
2225 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2226 global $wgContLang;
2227 if ( !$this->mRestrictionsLoaded ) {
2228 if ( $this->exists() ) {
2229 $dbr = wfGetDB( DB_SLAVE );
2231 $res = $dbr->select(
2232 'page_restrictions',
2233 '*',
2234 array( 'pr_page' => $this->getArticleId() ),
2235 __METHOD__
2238 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2239 } else {
2240 $title_protection = $this->getTitleProtection();
2242 if ( $title_protection ) {
2243 $now = wfTimestampNow();
2244 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2246 if ( !$expiry || $expiry > $now ) {
2247 // Apply the restrictions
2248 $this->mRestrictionsExpiry['create'] = $expiry;
2249 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2250 } else { // Get rid of the old restrictions
2251 Title::purgeExpiredRestrictions();
2252 $this->mTitleProtection = false;
2254 } else {
2255 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2257 $this->mRestrictionsLoaded = true;
2263 * Purge expired restrictions from the page_restrictions table
2265 static function purgeExpiredRestrictions() {
2266 $dbw = wfGetDB( DB_MASTER );
2267 $dbw->delete(
2268 'page_restrictions',
2269 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2270 __METHOD__
2273 $dbw->delete(
2274 'protected_titles',
2275 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2276 __METHOD__
2281 * Accessor/initialisation for mRestrictions
2283 * @param $action String action that permission needs to be checked for
2284 * @return Array of Strings the array of groups allowed to edit this article
2286 public function getRestrictions( $action ) {
2287 if ( !$this->mRestrictionsLoaded ) {
2288 $this->loadRestrictions();
2290 return isset( $this->mRestrictions[$action] )
2291 ? $this->mRestrictions[$action]
2292 : array();
2296 * Get the expiry time for the restriction against a given action
2298 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2299 * or not protected at all, or false if the action is not recognised.
2301 public function getRestrictionExpiry( $action ) {
2302 if ( !$this->mRestrictionsLoaded ) {
2303 $this->loadRestrictions();
2305 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2309 * Is there a version of this page in the deletion archive?
2311 * @return Int the number of archived revisions
2313 public function isDeleted() {
2314 if ( $this->getNamespace() < 0 ) {
2315 $n = 0;
2316 } else {
2317 $dbr = wfGetDB( DB_SLAVE );
2318 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2319 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2320 __METHOD__
2322 if ( $this->getNamespace() == NS_FILE ) {
2323 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2324 array( 'fa_name' => $this->getDBkey() ),
2325 __METHOD__
2329 return (int)$n;
2333 * Is there a version of this page in the deletion archive?
2335 * @return Boolean
2337 public function isDeletedQuick() {
2338 if ( $this->getNamespace() < 0 ) {
2339 return false;
2341 $dbr = wfGetDB( DB_SLAVE );
2342 $deleted = (bool)$dbr->selectField( 'archive', '1',
2343 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2344 __METHOD__
2346 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2347 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2348 array( 'fa_name' => $this->getDBkey() ),
2349 __METHOD__
2352 return $deleted;
2356 * Get the article ID for this Title from the link cache,
2357 * adding it if necessary
2359 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2360 * for update
2361 * @return Int the ID
2363 public function getArticleID( $flags = 0 ) {
2364 if ( $this->getNamespace() < 0 ) {
2365 return $this->mArticleID = 0;
2367 $linkCache = LinkCache::singleton();
2368 if ( $flags & self::GAID_FOR_UPDATE ) {
2369 $oldUpdate = $linkCache->forUpdate( true );
2370 $linkCache->clearLink( $this );
2371 $this->mArticleID = $linkCache->addLinkObj( $this );
2372 $linkCache->forUpdate( $oldUpdate );
2373 } else {
2374 if ( -1 == $this->mArticleID ) {
2375 $this->mArticleID = $linkCache->addLinkObj( $this );
2378 return $this->mArticleID;
2382 * Is this an article that is a redirect page?
2383 * Uses link cache, adding it if necessary
2385 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2386 * @return Bool
2388 public function isRedirect( $flags = 0 ) {
2389 if ( !is_null( $this->mRedirect ) ) {
2390 return $this->mRedirect;
2392 # Calling getArticleID() loads the field from cache as needed
2393 if ( !$this->getArticleID( $flags ) ) {
2394 return $this->mRedirect = false;
2396 $linkCache = LinkCache::singleton();
2397 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2399 return $this->mRedirect;
2403 * What is the length of this page?
2404 * Uses link cache, adding it if necessary
2406 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2407 * @return Int
2409 public function getLength( $flags = 0 ) {
2410 if ( $this->mLength != -1 ) {
2411 return $this->mLength;
2413 # Calling getArticleID() loads the field from cache as needed
2414 if ( !$this->getArticleID( $flags ) ) {
2415 return $this->mLength = 0;
2417 $linkCache = LinkCache::singleton();
2418 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2420 return $this->mLength;
2424 * What is the page_latest field for this page?
2426 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2427 * @return Int or 0 if the page doesn't exist
2429 public function getLatestRevID( $flags = 0 ) {
2430 if ( $this->mLatestID !== false ) {
2431 return intval( $this->mLatestID );
2433 # Calling getArticleID() loads the field from cache as needed
2434 if ( !$this->getArticleID( $flags ) ) {
2435 return $this->mLatestID = 0;
2437 $linkCache = LinkCache::singleton();
2438 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2440 return $this->mLatestID;
2444 * This clears some fields in this object, and clears any associated
2445 * keys in the "bad links" section of the link cache.
2447 * - This is called from Article::doEdit() and Article::insertOn() to allow
2448 * loading of the new page_id. It's also called from
2449 * Article::doDeleteArticle()
2451 * @param $newid Int the new Article ID
2453 public function resetArticleID( $newid ) {
2454 $linkCache = LinkCache::singleton();
2455 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2457 if ( $newid === false ) {
2458 $this->mArticleID = -1;
2459 } else {
2460 $this->mArticleID = intval( $newid );
2462 $this->mRestrictionsLoaded = false;
2463 $this->mRestrictions = array();
2464 $this->mRedirect = null;
2465 $this->mLength = -1;
2466 $this->mLatestID = false;
2470 * Updates page_touched for this page; called from LinksUpdate.php
2472 * @return Bool true if the update succeded
2474 public function invalidateCache() {
2475 if ( wfReadOnly() ) {
2476 return;
2478 $dbw = wfGetDB( DB_MASTER );
2479 $success = $dbw->update(
2480 'page',
2481 array( 'page_touched' => $dbw->timestamp() ),
2482 $this->pageCond(),
2483 __METHOD__
2485 HTMLFileCache::clearFileCache( $this );
2486 return $success;
2490 * Prefix some arbitrary text with the namespace or interwiki prefix
2491 * of this object
2493 * @param $name String the text
2494 * @return String the prefixed text
2495 * @private
2497 private function prefix( $name ) {
2498 $p = '';
2499 if ( $this->mInterwiki != '' ) {
2500 $p = $this->mInterwiki . ':';
2503 if ( 0 != $this->mNamespace ) {
2504 $p .= $this->getNsText() . ':';
2506 return $p . $name;
2510 * Returns a simple regex that will match on characters and sequences invalid in titles.
2511 * Note that this doesn't pick up many things that could be wrong with titles, but that
2512 * replacing this regex with something valid will make many titles valid.
2514 * @return String regex string
2516 static function getTitleInvalidRegex() {
2517 static $rxTc = false;
2518 if ( !$rxTc ) {
2519 # Matching titles will be held as illegal.
2520 $rxTc = '/' .
2521 # Any character not allowed is forbidden...
2522 '[^' . Title::legalChars() . ']' .
2523 # URL percent encoding sequences interfere with the ability
2524 # to round-trip titles -- you can't link to them consistently.
2525 '|%[0-9A-Fa-f]{2}' .
2526 # XML/HTML character references produce similar issues.
2527 '|&[A-Za-z0-9\x80-\xff]+;' .
2528 '|&#[0-9]+;' .
2529 '|&#x[0-9A-Fa-f]+;' .
2530 '/S';
2533 return $rxTc;
2537 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2539 * @param $text String containing title to capitalize
2540 * @param $ns int namespace index, defaults to NS_MAIN
2541 * @return String containing capitalized title
2543 public static function capitalize( $text, $ns = NS_MAIN ) {
2544 global $wgContLang;
2546 if ( MWNamespace::isCapitalized( $ns ) ) {
2547 return $wgContLang->ucfirst( $text );
2548 } else {
2549 return $text;
2554 * Secure and split - main initialisation function for this object
2556 * Assumes that mDbkeyform has been set, and is urldecoded
2557 * and uses underscores, but not otherwise munged. This function
2558 * removes illegal characters, splits off the interwiki and
2559 * namespace prefixes, sets the other forms, and canonicalizes
2560 * everything.
2562 * @return Bool true on success
2564 private function secureAndSplit() {
2565 global $wgContLang, $wgLocalInterwiki;
2567 # Initialisation
2568 $this->mInterwiki = $this->mFragment = '';
2569 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2571 $dbkey = $this->mDbkeyform;
2573 # Strip Unicode bidi override characters.
2574 # Sometimes they slip into cut-n-pasted page titles, where the
2575 # override chars get included in list displays.
2576 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2578 # Clean up whitespace
2579 # Note: use of the /u option on preg_replace here will cause
2580 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2581 # conveniently disabling them.
2582 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2583 $dbkey = trim( $dbkey, '_' );
2585 if ( $dbkey == '' ) {
2586 return false;
2589 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2590 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2591 return false;
2594 $this->mDbkeyform = $dbkey;
2596 # Initial colon indicates main namespace rather than specified default
2597 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2598 if ( ':' == $dbkey { 0 } ) {
2599 $this->mNamespace = NS_MAIN;
2600 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2601 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2604 # Namespace or interwiki prefix
2605 $firstPass = true;
2606 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2607 do {
2608 $m = array();
2609 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2610 $p = $m[1];
2611 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2612 # Ordinary namespace
2613 $dbkey = $m[2];
2614 $this->mNamespace = $ns;
2615 # For Talk:X pages, check if X has a "namespace" prefix
2616 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2617 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2618 # Disallow Talk:File:x type titles...
2619 return false;
2620 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2621 # Disallow Talk:Interwiki:x type titles...
2622 return false;
2625 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2626 if ( !$firstPass ) {
2627 # Can't make a local interwiki link to an interwiki link.
2628 # That's just crazy!
2629 return false;
2632 # Interwiki link
2633 $dbkey = $m[2];
2634 $this->mInterwiki = $wgContLang->lc( $p );
2636 # Redundant interwiki prefix to the local wiki
2637 if ( $wgLocalInterwiki !== false
2638 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2640 if ( $dbkey == '' ) {
2641 # Can't have an empty self-link
2642 return false;
2644 $this->mInterwiki = '';
2645 $firstPass = false;
2646 # Do another namespace split...
2647 continue;
2650 # If there's an initial colon after the interwiki, that also
2651 # resets the default namespace
2652 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2653 $this->mNamespace = NS_MAIN;
2654 $dbkey = substr( $dbkey, 1 );
2657 # If there's no recognized interwiki or namespace,
2658 # then let the colon expression be part of the title.
2660 break;
2661 } while ( true );
2663 # We already know that some pages won't be in the database!
2664 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2665 $this->mArticleID = 0;
2667 $fragment = strstr( $dbkey, '#' );
2668 if ( false !== $fragment ) {
2669 $this->setFragment( $fragment );
2670 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2671 # remove whitespace again: prevents "Foo_bar_#"
2672 # becoming "Foo_bar_"
2673 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2676 # Reject illegal characters.
2677 $rxTc = self::getTitleInvalidRegex();
2678 if ( preg_match( $rxTc, $dbkey ) ) {
2679 return false;
2682 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2683 # reachable due to the way web browsers deal with 'relative' URLs.
2684 # Also, they conflict with subpage syntax. Forbid them explicitly.
2685 if ( strpos( $dbkey, '.' ) !== false &&
2686 ( $dbkey === '.' || $dbkey === '..' ||
2687 strpos( $dbkey, './' ) === 0 ||
2688 strpos( $dbkey, '../' ) === 0 ||
2689 strpos( $dbkey, '/./' ) !== false ||
2690 strpos( $dbkey, '/../' ) !== false ||
2691 substr( $dbkey, -2 ) == '/.' ||
2692 substr( $dbkey, -3 ) == '/..' ) )
2694 return false;
2697 # Magic tilde sequences? Nu-uh!
2698 if ( strpos( $dbkey, '~~~' ) !== false ) {
2699 return false;
2702 # Limit the size of titles to 255 bytes. This is typically the size of the
2703 # underlying database field. We make an exception for special pages, which
2704 # don't need to be stored in the database, and may edge over 255 bytes due
2705 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2706 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2707 strlen( $dbkey ) > 512 )
2709 return false;
2712 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2713 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2714 # other site might be case-sensitive.
2715 $this->mUserCaseDBKey = $dbkey;
2716 if ( $this->mInterwiki == '' ) {
2717 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2720 # Can't make a link to a namespace alone... "empty" local links can only be
2721 # self-links with a fragment identifier.
2722 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2723 return false;
2726 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2727 // IP names are not allowed for accounts, and can only be referring to
2728 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2729 // there are numerous ways to present the same IP. Having sp:contribs scan
2730 // them all is silly and having some show the edits and others not is
2731 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2732 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2733 ? IP::sanitizeIP( $dbkey )
2734 : $dbkey;
2736 // Any remaining initial :s are illegal.
2737 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2738 return false;
2741 # Fill fields
2742 $this->mDbkeyform = $dbkey;
2743 $this->mUrlform = wfUrlencode( $dbkey );
2745 $this->mTextform = str_replace( '_', ' ', $dbkey );
2747 return true;
2751 * Set the fragment for this title. Removes the first character from the
2752 * specified fragment before setting, so it assumes you're passing it with
2753 * an initial "#".
2755 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2756 * Still in active use privately.
2758 * @param $fragment String text
2760 public function setFragment( $fragment ) {
2761 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2765 * Get a Title object associated with the talk page of this article
2767 * @return Title the object for the talk page
2769 public function getTalkPage() {
2770 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2774 * Get a title object associated with the subject page of this
2775 * talk page
2777 * @return Title the object for the subject page
2779 public function getSubjectPage() {
2780 // Is this the same title?
2781 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2782 if ( $this->getNamespace() == $subjectNS ) {
2783 return $this;
2785 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2789 * Get an array of Title objects linking to this Title
2790 * Also stores the IDs in the link cache.
2792 * WARNING: do not use this function on arbitrary user-supplied titles!
2793 * On heavily-used templates it will max out the memory.
2795 * @param $options Array: may be FOR UPDATE
2796 * @param $table String: table name
2797 * @param $prefix String: fields prefix
2798 * @return Array of Title objects linking here
2800 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2801 $linkCache = LinkCache::singleton();
2803 if ( count( $options ) > 0 ) {
2804 $db = wfGetDB( DB_MASTER );
2805 } else {
2806 $db = wfGetDB( DB_SLAVE );
2809 $res = $db->select(
2810 array( 'page', $table ),
2811 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2812 array(
2813 "{$prefix}_from=page_id",
2814 "{$prefix}_namespace" => $this->getNamespace(),
2815 "{$prefix}_title" => $this->getDBkey() ),
2816 __METHOD__,
2817 $options
2820 $retVal = array();
2821 if ( $db->numRows( $res ) ) {
2822 foreach ( $res as $row ) {
2823 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2824 if ( $titleObj ) {
2825 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2826 $retVal[] = $titleObj;
2830 return $retVal;
2834 * Get an array of Title objects using this Title as a template
2835 * Also stores the IDs in the link cache.
2837 * WARNING: do not use this function on arbitrary user-supplied titles!
2838 * On heavily-used templates it will max out the memory.
2840 * @param $options Array: may be FOR UPDATE
2841 * @return Array of Title the Title objects linking here
2843 public function getTemplateLinksTo( $options = array() ) {
2844 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2848 * Get an array of Title objects referring to non-existent articles linked from this page
2850 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2851 * @return Array of Title the Title objects
2853 public function getBrokenLinksFrom() {
2854 if ( $this->getArticleId() == 0 ) {
2855 # All links from article ID 0 are false positives
2856 return array();
2859 $dbr = wfGetDB( DB_SLAVE );
2860 $res = $dbr->select(
2861 array( 'page', 'pagelinks' ),
2862 array( 'pl_namespace', 'pl_title' ),
2863 array(
2864 'pl_from' => $this->getArticleId(),
2865 'page_namespace IS NULL'
2867 __METHOD__, array(),
2868 array(
2869 'page' => array(
2870 'LEFT JOIN',
2871 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2876 $retVal = array();
2877 foreach ( $res as $row ) {
2878 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2880 return $retVal;
2885 * Get a list of URLs to purge from the Squid cache when this
2886 * page changes
2888 * @return Array of String the URLs
2890 public function getSquidURLs() {
2891 global $wgContLang;
2893 $urls = array(
2894 $this->getInternalURL(),
2895 $this->getInternalURL( 'action=history' )
2898 // purge variant urls as well
2899 if ( $wgContLang->hasVariants() ) {
2900 $variants = $wgContLang->getVariants();
2901 foreach ( $variants as $vCode ) {
2902 $urls[] = $this->getInternalURL( '', $vCode );
2906 return $urls;
2910 * Purge all applicable Squid URLs
2912 public function purgeSquid() {
2913 global $wgUseSquid;
2914 if ( $wgUseSquid ) {
2915 $urls = $this->getSquidURLs();
2916 $u = new SquidUpdate( $urls );
2917 $u->doUpdate();
2922 * Move this page without authentication
2924 * @param $nt Title the new page Title
2925 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2927 public function moveNoAuth( &$nt ) {
2928 return $this->moveTo( $nt, false );
2932 * Check whether a given move operation would be valid.
2933 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2935 * @param $nt Title the new title
2936 * @param $auth Bool indicates whether $wgUser's permissions
2937 * should be checked
2938 * @param $reason String is the log summary of the move, used for spam checking
2939 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2941 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2942 global $wgUser;
2944 $errors = array();
2945 if ( !$nt ) {
2946 // Normally we'd add this to $errors, but we'll get
2947 // lots of syntax errors if $nt is not an object
2948 return array( array( 'badtitletext' ) );
2950 if ( $this->equals( $nt ) ) {
2951 $errors[] = array( 'selfmove' );
2953 if ( !$this->isMovable() ) {
2954 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2956 if ( $nt->getInterwiki() != '' ) {
2957 $errors[] = array( 'immobile-target-namespace-iw' );
2959 if ( !$nt->isMovable() ) {
2960 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2963 $oldid = $this->getArticleID();
2964 $newid = $nt->getArticleID();
2966 if ( strlen( $nt->getDBkey() ) < 1 ) {
2967 $errors[] = array( 'articleexists' );
2969 if ( ( $this->getDBkey() == '' ) ||
2970 ( !$oldid ) ||
2971 ( $nt->getDBkey() == '' ) ) {
2972 $errors[] = array( 'badarticleerror' );
2975 // Image-specific checks
2976 if ( $this->getNamespace() == NS_FILE ) {
2977 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2980 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
2981 $errors[] = array( 'nonfile-cannot-move-to-file' );
2984 if ( $auth ) {
2985 $errors = wfMergeErrorArrays( $errors,
2986 $this->getUserPermissionsErrors( 'move', $wgUser ),
2987 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2988 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2989 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2992 $match = EditPage::matchSummarySpamRegex( $reason );
2993 if ( $match !== false ) {
2994 // This is kind of lame, won't display nice
2995 $errors[] = array( 'spamprotectiontext' );
2998 $err = null;
2999 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3000 $errors[] = array( 'hookaborted', $err );
3003 # The move is allowed only if (1) the target doesn't exist, or
3004 # (2) the target is a redirect to the source, and has no history
3005 # (so we can undo bad moves right after they're done).
3007 if ( 0 != $newid ) { # Target exists; check for validity
3008 if ( !$this->isValidMoveTarget( $nt ) ) {
3009 $errors[] = array( 'articleexists' );
3011 } else {
3012 $tp = $nt->getTitleProtection();
3013 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3014 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3015 $errors[] = array( 'cantmove-titleprotected' );
3018 if ( empty( $errors ) ) {
3019 return true;
3021 return $errors;
3025 * Check if the requested move target is a valid file move target
3026 * @param Title $nt Target title
3027 * @return array List of errors
3029 protected function validateFileMoveOperation( $nt ) {
3030 global $wgUser;
3032 $errors = array();
3034 if ( $nt->getNamespace() != NS_FILE ) {
3035 $errors[] = array( 'imagenocrossnamespace' );
3038 $file = wfLocalFile( $this );
3039 if ( $file->exists() ) {
3040 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3041 $errors[] = array( 'imageinvalidfilename' );
3043 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3044 $errors[] = array( 'imagetypemismatch' );
3048 $destFile = wfLocalFile( $nt );
3049 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3050 $errors[] = array( 'file-exists-sharedrepo' );
3053 return $errors;
3057 * Move a title to a new location
3059 * @param $nt Title the new title
3060 * @param $auth Bool indicates whether $wgUser's permissions
3061 * should be checked
3062 * @param $reason String the reason for the move
3063 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3064 * Ignored if the user doesn't have the suppressredirect right.
3065 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3067 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3068 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3069 if ( is_array( $err ) ) {
3070 return $err;
3073 // If it is a file, move it first. It is done before all other moving stuff is
3074 // done because it's hard to revert
3075 $dbw = wfGetDB( DB_MASTER );
3076 if ( $this->getNamespace() == NS_FILE ) {
3077 $file = wfLocalFile( $this );
3078 if ( $file->exists() ) {
3079 $status = $file->move( $nt );
3080 if ( !$status->isOk() ) {
3081 return $status->getErrorsArray();
3086 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3087 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3088 $protected = $this->isProtected();
3089 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3091 // Do the actual move
3092 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3093 if ( is_array( $err ) ) {
3094 # @todo FIXME: What about the File we have already moved?
3095 $dbw->rollback();
3096 return $err;
3099 $redirid = $this->getArticleID();
3101 // Refresh the sortkey for this row. Be careful to avoid resetting
3102 // cl_timestamp, which may disturb time-based lists on some sites.
3103 $prefixes = $dbw->select(
3104 'categorylinks',
3105 array( 'cl_sortkey_prefix', 'cl_to' ),
3106 array( 'cl_from' => $pageid ),
3107 __METHOD__
3109 foreach ( $prefixes as $prefixRow ) {
3110 $prefix = $prefixRow->cl_sortkey_prefix;
3111 $catTo = $prefixRow->cl_to;
3112 $dbw->update( 'categorylinks',
3113 array(
3114 'cl_sortkey' => Collation::singleton()->getSortKey(
3115 $nt->getCategorySortkey( $prefix ) ),
3116 'cl_timestamp=cl_timestamp' ),
3117 array(
3118 'cl_from' => $pageid,
3119 'cl_to' => $catTo ),
3120 __METHOD__
3124 if ( $protected ) {
3125 # Protect the redirect title as the title used to be...
3126 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3127 array(
3128 'pr_page' => $redirid,
3129 'pr_type' => 'pr_type',
3130 'pr_level' => 'pr_level',
3131 'pr_cascade' => 'pr_cascade',
3132 'pr_user' => 'pr_user',
3133 'pr_expiry' => 'pr_expiry'
3135 array( 'pr_page' => $pageid ),
3136 __METHOD__,
3137 array( 'IGNORE' )
3139 # Update the protection log
3140 $log = new LogPage( 'protect' );
3141 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3142 if ( $reason ) {
3143 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3145 // @todo FIXME: $params?
3146 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3149 # Update watchlists
3150 $oldnamespace = $this->getNamespace() & ~1;
3151 $newnamespace = $nt->getNamespace() & ~1;
3152 $oldtitle = $this->getDBkey();
3153 $newtitle = $nt->getDBkey();
3155 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3156 WatchedItem::duplicateEntries( $this, $nt );
3159 # Update search engine
3160 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3161 $u->doUpdate();
3162 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3163 $u->doUpdate();
3165 $dbw->commit();
3167 # Update site_stats
3168 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3169 # No longer a content page
3170 # Not viewed, edited, removing
3171 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3172 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3173 # Now a content page
3174 # Not viewed, edited, adding
3175 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3176 } elseif ( $pageCountChange ) {
3177 # Redirect added
3178 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3179 } else {
3180 # Nothing special
3181 $u = false;
3183 if ( $u ) {
3184 $u->doUpdate();
3186 # Update message cache for interface messages
3187 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3188 # @bug 17860: old article can be deleted, if this the case,
3189 # delete it from message cache
3190 if ( $this->getArticleID() === 0 ) {
3191 MessageCache::singleton()->replace( $this->getDBkey(), false );
3192 } else {
3193 $oldarticle = new Article( $this );
3194 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3197 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3198 $newarticle = new Article( $nt );
3199 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3202 global $wgUser;
3203 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3204 return true;
3208 * Move page to a title which is either a redirect to the
3209 * source page or nonexistent
3211 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3212 * @param $reason String The reason for the move
3213 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3214 * if the user doesn't have the suppressredirect right
3216 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3217 global $wgUser, $wgContLang;
3219 $moveOverRedirect = $nt->exists();
3221 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3222 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3224 if ( $reason ) {
3225 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3227 # Truncate for whole multibyte characters.
3228 $comment = $wgContLang->truncate( $comment, 255 );
3230 $oldid = $this->getArticleID();
3231 $latest = $this->getLatestRevID();
3233 $oldns = $this->getNamespace();
3234 $olddbk = $this->getDBkey();
3236 $dbw = wfGetDB( DB_MASTER );
3238 if ( $moveOverRedirect ) {
3239 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3241 $newid = $nt->getArticleID();
3242 $newns = $nt->getNamespace();
3243 $newdbk = $nt->getDBkey();
3245 # Delete the old redirect. We don't save it to history since
3246 # by definition if we've got here it's rather uninteresting.
3247 # We have to remove it so that the next step doesn't trigger
3248 # a conflict on the unique namespace+title index...
3249 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3250 if ( !$dbw->cascadingDeletes() ) {
3251 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3252 global $wgUseTrackbacks;
3253 if ( $wgUseTrackbacks ) {
3254 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3256 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3257 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3258 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3259 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3260 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3261 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3262 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3264 // If the target page was recently created, it may have an entry in recentchanges still
3265 $dbw->delete( 'recentchanges',
3266 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3267 __METHOD__
3271 # Save a null revision in the page's history notifying of the move
3272 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3273 if ( !is_object( $nullRevision ) ) {
3274 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3276 $nullRevId = $nullRevision->insertOn( $dbw );
3278 # Change the name of the target page:
3279 $dbw->update( 'page',
3280 /* SET */ array(
3281 'page_touched' => $dbw->timestamp(),
3282 'page_namespace' => $nt->getNamespace(),
3283 'page_title' => $nt->getDBkey(),
3284 'page_latest' => $nullRevId,
3286 /* WHERE */ array( 'page_id' => $oldid ),
3287 __METHOD__
3289 $nt->resetArticleID( $oldid );
3291 $article = new Article( $nt );
3292 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3294 # Recreate the redirect, this time in the other direction.
3295 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3296 $mwRedir = MagicWord::get( 'redirect' );
3297 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3298 $redirectArticle = new Article( $this );
3299 $newid = $redirectArticle->insertOn( $dbw );
3300 $redirectRevision = new Revision( array(
3301 'page' => $newid,
3302 'comment' => $comment,
3303 'text' => $redirectText ) );
3304 $redirectRevision->insertOn( $dbw );
3305 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3307 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3309 # Now, we record the link from the redirect to the new title.
3310 # It should have no other outgoing links...
3311 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3312 $dbw->insert( 'pagelinks',
3313 array(
3314 'pl_from' => $newid,
3315 'pl_namespace' => $nt->getNamespace(),
3316 'pl_title' => $nt->getDBkey() ),
3317 __METHOD__ );
3318 $redirectSuppressed = false;
3319 } else {
3320 // Get rid of old new page entries in Special:NewPages and RC.
3321 // Needs to be before $this->resetArticleID( 0 ).
3322 $dbw->delete( 'recentchanges', array(
3323 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3324 'rc_namespace' => $oldns,
3325 'rc_title' => $olddbk,
3326 'rc_new' => 1
3328 __METHOD__
3331 $this->resetArticleID( 0 );
3332 $redirectSuppressed = true;
3335 # Log the move
3336 $log = new LogPage( 'move' );
3337 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3338 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3340 # Purge caches for old and new titles
3341 if ( $moveOverRedirect ) {
3342 # A simple purge is enough when moving over a redirect
3343 $nt->purgeSquid();
3344 } else {
3345 # Purge caches as per article creation, including any pages that link to this title
3346 Article::onArticleCreate( $nt );
3348 $this->purgeSquid();
3352 * Move this page's subpages to be subpages of $nt
3354 * @param $nt Title Move target
3355 * @param $auth bool Whether $wgUser's permissions should be checked
3356 * @param $reason string The reason for the move
3357 * @param $createRedirect bool Whether to create redirects from the old subpages to
3358 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3359 * @return mixed array with old page titles as keys, and strings (new page titles) or
3360 * arrays (errors) as values, or an error array with numeric indices if no pages
3361 * were moved
3363 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3364 global $wgMaximumMovedPages;
3365 // Check permissions
3366 if ( !$this->userCan( 'move-subpages' ) ) {
3367 return array( 'cant-move-subpages' );
3369 // Do the source and target namespaces support subpages?
3370 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3371 return array( 'namespace-nosubpages',
3372 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3374 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3375 return array( 'namespace-nosubpages',
3376 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3379 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3380 $retval = array();
3381 $count = 0;
3382 foreach ( $subpages as $oldSubpage ) {
3383 $count++;
3384 if ( $count > $wgMaximumMovedPages ) {
3385 $retval[$oldSubpage->getPrefixedTitle()] =
3386 array( 'movepage-max-pages',
3387 $wgMaximumMovedPages );
3388 break;
3391 // We don't know whether this function was called before
3392 // or after moving the root page, so check both
3393 // $this and $nt
3394 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3395 $oldSubpage->getArticleID() == $nt->getArticleId() )
3397 // When moving a page to a subpage of itself,
3398 // don't move it twice
3399 continue;
3401 $newPageName = preg_replace(
3402 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3403 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3404 $oldSubpage->getDBkey() );
3405 if ( $oldSubpage->isTalkPage() ) {
3406 $newNs = $nt->getTalkPage()->getNamespace();
3407 } else {
3408 $newNs = $nt->getSubjectPage()->getNamespace();
3410 # Bug 14385: we need makeTitleSafe because the new page names may
3411 # be longer than 255 characters.
3412 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3414 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3415 if ( $success === true ) {
3416 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3417 } else {
3418 $retval[$oldSubpage->getPrefixedText()] = $success;
3421 return $retval;
3425 * Checks if this page is just a one-rev redirect.
3426 * Adds lock, so don't use just for light purposes.
3428 * @return Bool
3430 public function isSingleRevRedirect() {
3431 $dbw = wfGetDB( DB_MASTER );
3432 # Is it a redirect?
3433 $row = $dbw->selectRow( 'page',
3434 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3435 $this->pageCond(),
3436 __METHOD__,
3437 array( 'FOR UPDATE' )
3439 # Cache some fields we may want
3440 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3441 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3442 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3443 if ( !$this->mRedirect ) {
3444 return false;
3446 # Does the article have a history?
3447 $row = $dbw->selectField( array( 'page', 'revision' ),
3448 'rev_id',
3449 array( 'page_namespace' => $this->getNamespace(),
3450 'page_title' => $this->getDBkey(),
3451 'page_id=rev_page',
3452 'page_latest != rev_id'
3454 __METHOD__,
3455 array( 'FOR UPDATE' )
3457 # Return true if there was no history
3458 return ( $row === false );
3462 * Checks if $this can be moved to a given Title
3463 * - Selects for update, so don't call it unless you mean business
3465 * @param $nt Title the new title to check
3466 * @return Bool
3468 public function isValidMoveTarget( $nt ) {
3469 # Is it an existing file?
3470 if ( $nt->getNamespace() == NS_FILE ) {
3471 $file = wfLocalFile( $nt );
3472 if ( $file->exists() ) {
3473 wfDebug( __METHOD__ . ": file exists\n" );
3474 return false;
3477 # Is it a redirect with no history?
3478 if ( !$nt->isSingleRevRedirect() ) {
3479 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3480 return false;
3482 # Get the article text
3483 $rev = Revision::newFromTitle( $nt );
3484 $text = $rev->getText();
3485 # Does the redirect point to the source?
3486 # Or is it a broken self-redirect, usually caused by namespace collisions?
3487 $m = array();
3488 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3489 $redirTitle = Title::newFromText( $m[1] );
3490 if ( !is_object( $redirTitle ) ||
3491 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3492 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3493 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3494 return false;
3496 } else {
3497 # Fail safe
3498 wfDebug( __METHOD__ . ": failsafe\n" );
3499 return false;
3501 return true;
3505 * Can this title be added to a user's watchlist?
3507 * @return Bool TRUE or FALSE
3509 public function isWatchable() {
3510 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3514 * Get categories to which this Title belongs and return an array of
3515 * categories' names.
3517 * @return Array of parents in the form:
3518 * $parent => $currentarticle
3520 public function getParentCategories() {
3521 global $wgContLang;
3523 $data = array();
3525 $titleKey = $this->getArticleId();
3527 if ( $titleKey === 0 ) {
3528 return $data;
3531 $dbr = wfGetDB( DB_SLAVE );
3533 $res = $dbr->select( 'categorylinks', '*',
3534 array(
3535 'cl_from' => $titleKey,
3537 __METHOD__,
3538 array()
3541 if ( $dbr->numRows( $res ) > 0 ) {
3542 foreach ( $res as $row ) {
3543 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3544 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3547 return $data;
3551 * Get a tree of parent categories
3553 * @param $children Array with the children in the keys, to check for circular refs
3554 * @return Array Tree of parent categories
3556 public function getParentCategoryTree( $children = array() ) {
3557 $stack = array();
3558 $parents = $this->getParentCategories();
3560 if ( $parents ) {
3561 foreach ( $parents as $parent => $current ) {
3562 if ( array_key_exists( $parent, $children ) ) {
3563 # Circular reference
3564 $stack[$parent] = array();
3565 } else {
3566 $nt = Title::newFromText( $parent );
3567 if ( $nt ) {
3568 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3574 return $stack;
3578 * Get an associative array for selecting this title from
3579 * the "page" table
3581 * @return Array suitable for the $where parameter of DB::select()
3583 public function pageCond() {
3584 if ( $this->mArticleID > 0 ) {
3585 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3586 return array( 'page_id' => $this->mArticleID );
3587 } else {
3588 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3593 * Get the revision ID of the previous revision
3595 * @param $revId Int Revision ID. Get the revision that was before this one.
3596 * @param $flags Int Title::GAID_FOR_UPDATE
3597 * @return Int|Bool Old revision ID, or FALSE if none exists
3599 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3600 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3601 return $db->selectField( 'revision', 'rev_id',
3602 array(
3603 'rev_page' => $this->getArticleId( $flags ),
3604 'rev_id < ' . intval( $revId )
3606 __METHOD__,
3607 array( 'ORDER BY' => 'rev_id DESC' )
3612 * Get the revision ID of the next revision
3614 * @param $revId Int Revision ID. Get the revision that was after this one.
3615 * @param $flags Int Title::GAID_FOR_UPDATE
3616 * @return Int|Bool Next revision ID, or FALSE if none exists
3618 public function getNextRevisionID( $revId, $flags = 0 ) {
3619 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3620 return $db->selectField( 'revision', 'rev_id',
3621 array(
3622 'rev_page' => $this->getArticleId( $flags ),
3623 'rev_id > ' . intval( $revId )
3625 __METHOD__,
3626 array( 'ORDER BY' => 'rev_id' )
3631 * Get the first revision of the page
3633 * @param $flags Int Title::GAID_FOR_UPDATE
3634 * @return Revision|Null if page doesn't exist
3636 public function getFirstRevision( $flags = 0 ) {
3637 $pageId = $this->getArticleId( $flags );
3638 if ( $pageId ) {
3639 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3640 $row = $db->selectRow( 'revision', '*',
3641 array( 'rev_page' => $pageId ),
3642 __METHOD__,
3643 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3645 if ( $row ) {
3646 return new Revision( $row );
3649 return null;
3653 * Get the oldest revision timestamp of this page
3655 * @param $flags Int Title::GAID_FOR_UPDATE
3656 * @return String: MW timestamp
3658 public function getEarliestRevTime( $flags = 0 ) {
3659 $rev = $this->getFirstRevision( $flags );
3660 return $rev ? $rev->getTimestamp() : null;
3664 * Check if this is a new page
3666 * @return bool
3668 public function isNewPage() {
3669 $dbr = wfGetDB( DB_SLAVE );
3670 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3674 * Get the number of revisions between the given revision.
3675 * Used for diffs and other things that really need it.
3677 * @param $old int|Revision Old revision or rev ID (first before range)
3678 * @param $new int|Revision New revision or rev ID (first after range)
3679 * @return Int Number of revisions between these revisions.
3681 public function countRevisionsBetween( $old, $new ) {
3682 if ( !( $old instanceof Revision ) ) {
3683 $old = Revision::newFromTitle( $this, (int)$old );
3685 if ( !( $new instanceof Revision ) ) {
3686 $new = Revision::newFromTitle( $this, (int)$new );
3688 if ( !$old || !$new ) {
3689 return 0; // nothing to compare
3691 $dbr = wfGetDB( DB_SLAVE );
3692 return (int)$dbr->selectField( 'revision', 'count(*)',
3693 array(
3694 'rev_page' => $this->getArticleId(),
3695 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3696 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3698 __METHOD__
3703 * Get the number of authors between the given revision IDs.
3704 * Used for diffs and other things that really need it.
3706 * @param $old int|Revision Old revision or rev ID (first before range)
3707 * @param $new int|Revision New revision or rev ID (first after range)
3708 * @param $limit Int Maximum number of authors
3709 * @return Int Number of revision authors between these revisions.
3711 public function countAuthorsBetween( $old, $new, $limit ) {
3712 if ( !( $old instanceof Revision ) ) {
3713 $old = Revision::newFromTitle( $this, (int)$old );
3715 if ( !( $new instanceof Revision ) ) {
3716 $new = Revision::newFromTitle( $this, (int)$new );
3718 if ( !$old || !$new ) {
3719 return 0; // nothing to compare
3721 $dbr = wfGetDB( DB_SLAVE );
3722 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3723 array(
3724 'rev_page' => $this->getArticleID(),
3725 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3726 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3727 ), __METHOD__,
3728 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
3730 return (int)$dbr->numRows( $res );
3734 * Compare with another title.
3736 * @param $title Title
3737 * @return Bool
3739 public function equals( Title $title ) {
3740 // Note: === is necessary for proper matching of number-like titles.
3741 return $this->getInterwiki() === $title->getInterwiki()
3742 && $this->getNamespace() == $title->getNamespace()
3743 && $this->getDBkey() === $title->getDBkey();
3747 * Callback for usort() to do title sorts by (namespace, title)
3749 * @param $a Title
3750 * @param $b Title
3752 * @return Integer: result of string comparison, or namespace comparison
3754 public static function compare( $a, $b ) {
3755 if ( $a->getNamespace() == $b->getNamespace() ) {
3756 return strcmp( $a->getText(), $b->getText() );
3757 } else {
3758 return $a->getNamespace() - $b->getNamespace();
3763 * Return a string representation of this title
3765 * @return String representation of this title
3767 public function __toString() {
3768 return $this->getPrefixedText();
3772 * Check if page exists. For historical reasons, this function simply
3773 * checks for the existence of the title in the page table, and will
3774 * thus return false for interwiki links, special pages and the like.
3775 * If you want to know if a title can be meaningfully viewed, you should
3776 * probably call the isKnown() method instead.
3778 * @return Bool
3780 public function exists() {
3781 return $this->getArticleId() != 0;
3785 * Should links to this title be shown as potentially viewable (i.e. as
3786 * "bluelinks"), even if there's no record by this title in the page
3787 * table?
3789 * This function is semi-deprecated for public use, as well as somewhat
3790 * misleadingly named. You probably just want to call isKnown(), which
3791 * calls this function internally.
3793 * (ISSUE: Most of these checks are cheap, but the file existence check
3794 * can potentially be quite expensive. Including it here fixes a lot of
3795 * existing code, but we might want to add an optional parameter to skip
3796 * it and any other expensive checks.)
3798 * @return Bool
3800 public function isAlwaysKnown() {
3801 if ( $this->mInterwiki != '' ) {
3802 return true; // any interwiki link might be viewable, for all we know
3804 switch( $this->mNamespace ) {
3805 case NS_MEDIA:
3806 case NS_FILE:
3807 // file exists, possibly in a foreign repo
3808 return (bool)wfFindFile( $this );
3809 case NS_SPECIAL:
3810 // valid special page
3811 return SpecialPageFactory::exists( $this->getDBkey() );
3812 case NS_MAIN:
3813 // selflink, possibly with fragment
3814 return $this->mDbkeyform == '';
3815 case NS_MEDIAWIKI:
3816 // known system message
3817 return $this->getDefaultMessageText() !== false;
3818 default:
3819 return false;
3824 * Does this title refer to a page that can (or might) be meaningfully
3825 * viewed? In particular, this function may be used to determine if
3826 * links to the title should be rendered as "bluelinks" (as opposed to
3827 * "redlinks" to non-existent pages).
3829 * @return Bool
3831 public function isKnown() {
3832 return $this->isAlwaysKnown() || $this->exists();
3836 * Does this page have source text?
3838 * @return Boolean
3840 public function hasSourceText() {
3841 if ( $this->exists() ) {
3842 return true;
3845 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3846 // If the page doesn't exist but is a known system message, default
3847 // message content will be displayed, same for language subpages
3848 return $this->getDefaultMessageText() !== false;
3851 return false;
3855 * Get the default message text or false if the message doesn't exist
3857 * @return String or false
3859 public function getDefaultMessageText() {
3860 global $wgContLang;
3862 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3863 return false;
3866 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3867 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3869 if ( $message->exists() ) {
3870 return $message->plain();
3871 } else {
3872 return false;
3877 * Is this in a namespace that allows actual pages?
3879 * @return Bool
3880 * @internal note -- uses hardcoded namespace index instead of constants
3882 public function canExist() {
3883 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3887 * Update page_touched timestamps and send squid purge messages for
3888 * pages linking to this title. May be sent to the job queue depending
3889 * on the number of links. Typically called on create and delete.
3891 public function touchLinks() {
3892 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3893 $u->doUpdate();
3895 if ( $this->getNamespace() == NS_CATEGORY ) {
3896 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3897 $u->doUpdate();
3902 * Get the last touched timestamp
3904 * @param $db DatabaseBase: optional db
3905 * @return String last-touched timestamp
3907 public function getTouched( $db = null ) {
3908 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3909 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3910 return $touched;
3914 * Get the timestamp when this page was updated since the user last saw it.
3916 * @param $user User
3917 * @return String|Null
3919 public function getNotificationTimestamp( $user = null ) {
3920 global $wgUser, $wgShowUpdatedMarker;
3921 // Assume current user if none given
3922 if ( !$user ) {
3923 $user = $wgUser;
3925 // Check cache first
3926 $uid = $user->getId();
3927 // avoid isset here, as it'll return false for null entries
3928 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3929 return $this->mNotificationTimestamp[$uid];
3931 if ( !$uid || !$wgShowUpdatedMarker ) {
3932 return $this->mNotificationTimestamp[$uid] = false;
3934 // Don't cache too much!
3935 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3936 $this->mNotificationTimestamp = array();
3938 $dbr = wfGetDB( DB_SLAVE );
3939 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3940 'wl_notificationtimestamp',
3941 array( 'wl_namespace' => $this->getNamespace(),
3942 'wl_title' => $this->getDBkey(),
3943 'wl_user' => $user->getId()
3945 __METHOD__
3947 return $this->mNotificationTimestamp[$uid];
3951 * Get the trackback URL for this page
3953 * @return String Trackback URL
3955 public function trackbackURL() {
3956 global $wgScriptPath, $wgServer, $wgScriptExtension;
3958 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3959 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3963 * Get the trackback RDF for this page
3965 * @return String Trackback RDF
3967 public function trackbackRDF() {
3968 $url = htmlspecialchars( $this->getFullURL() );
3969 $title = htmlspecialchars( $this->getText() );
3970 $tburl = $this->trackbackURL();
3972 // Autodiscovery RDF is placed in comments so HTML validator
3973 // won't barf. This is a rather icky workaround, but seems
3974 // frequently used by this kind of RDF thingy.
3976 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3977 return "<!--
3978 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3979 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3980 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3981 <rdf:Description
3982 rdf:about=\"$url\"
3983 dc:identifier=\"$url\"
3984 dc:title=\"$title\"
3985 trackback:ping=\"$tburl\" />
3986 </rdf:RDF>
3987 -->";
3991 * Generate strings used for xml 'id' names in monobook tabs
3993 * @param $prepend string defaults to 'nstab-'
3994 * @return String XML 'id' name
3996 public function getNamespaceKey( $prepend = 'nstab-' ) {
3997 global $wgContLang;
3998 // Gets the subject namespace if this title
3999 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4000 // Checks if cononical namespace name exists for namespace
4001 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4002 // Uses canonical namespace name
4003 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4004 } else {
4005 // Uses text of namespace
4006 $namespaceKey = $this->getSubjectNsText();
4008 // Makes namespace key lowercase
4009 $namespaceKey = $wgContLang->lc( $namespaceKey );
4010 // Uses main
4011 if ( $namespaceKey == '' ) {
4012 $namespaceKey = 'main';
4014 // Changes file to image for backwards compatibility
4015 if ( $namespaceKey == 'file' ) {
4016 $namespaceKey = 'image';
4018 return $prepend . $namespaceKey;
4022 * Returns true if this is a special page.
4024 * @return boolean
4026 public function isSpecialPage() {
4027 return $this->getNamespace() == NS_SPECIAL;
4031 * Returns true if this title resolves to the named special page
4033 * @param $name String The special page name
4034 * @return boolean
4036 public function isSpecial( $name ) {
4037 if ( $this->getNamespace() == NS_SPECIAL ) {
4038 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
4039 if ( $name == $thisName ) {
4040 return true;
4043 return false;
4047 * If the Title refers to a special page alias which is not the local default, resolve
4048 * the alias, and localise the name as necessary. Otherwise, return $this
4050 * @return Title
4052 public function fixSpecialName() {
4053 if ( $this->getNamespace() == NS_SPECIAL ) {
4054 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
4055 if ( $canonicalName ) {
4056 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName );
4057 if ( $localName != $this->mDbkeyform ) {
4058 return Title::makeTitle( NS_SPECIAL, $localName );
4062 return $this;
4066 * Is this Title in a namespace which contains content?
4067 * In other words, is this a content page, for the purposes of calculating
4068 * statistics, etc?
4070 * @return Boolean
4072 public function isContentPage() {
4073 return MWNamespace::isContent( $this->getNamespace() );
4077 * Get all extant redirects to this Title
4079 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4080 * @return Array of Title redirects to this title
4082 public function getRedirectsHere( $ns = null ) {
4083 $redirs = array();
4085 $dbr = wfGetDB( DB_SLAVE );
4086 $where = array(
4087 'rd_namespace' => $this->getNamespace(),
4088 'rd_title' => $this->getDBkey(),
4089 'rd_from = page_id'
4091 if ( !is_null( $ns ) ) {
4092 $where['page_namespace'] = $ns;
4095 $res = $dbr->select(
4096 array( 'redirect', 'page' ),
4097 array( 'page_namespace', 'page_title' ),
4098 $where,
4099 __METHOD__
4102 foreach ( $res as $row ) {
4103 $redirs[] = self::newFromRow( $row );
4105 return $redirs;
4109 * Check if this Title is a valid redirect target
4111 * @return Bool
4113 public function isValidRedirectTarget() {
4114 global $wgInvalidRedirectTargets;
4116 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4117 if ( $this->isSpecial( 'Userlogout' ) ) {
4118 return false;
4121 foreach ( $wgInvalidRedirectTargets as $target ) {
4122 if ( $this->isSpecial( $target ) ) {
4123 return false;
4127 return true;
4131 * Get a backlink cache object
4133 * @return object BacklinkCache
4135 function getBacklinkCache() {
4136 if ( is_null( $this->mBacklinkCache ) ) {
4137 $this->mBacklinkCache = new BacklinkCache( $this );
4139 return $this->mBacklinkCache;
4143 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4145 * @return Boolean
4147 public function canUseNoindex() {
4148 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4150 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4151 ? $wgContentNamespaces
4152 : $wgExemptFromUserRobotsControl;
4154 return !in_array( $this->mNamespace, $bannedNamespaces );
4159 * Returns restriction types for the current Title
4161 * @return array applicable restriction types
4163 public function getRestrictionTypes() {
4164 if ( $this->getNamespace() == NS_SPECIAL ) {
4165 return array();
4168 $types = self::getFilteredRestrictionTypes( $this->exists() );
4170 if ( $this->getNamespace() != NS_FILE ) {
4171 # Remove the upload restriction for non-file titles
4172 $types = array_diff( $types, array( 'upload' ) );
4175 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4177 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4178 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4180 return $types;
4183 * Get a filtered list of all restriction types supported by this wiki.
4184 * @param bool $exists True to get all restriction types that apply to
4185 * titles that do exist, False for all restriction types that apply to
4186 * titles that do not exist
4187 * @return array
4189 public static function getFilteredRestrictionTypes( $exists = true ) {
4190 global $wgRestrictionTypes;
4191 $types = $wgRestrictionTypes;
4192 if ( $exists ) {
4193 # Remove the create restriction for existing titles
4194 $types = array_diff( $types, array( 'create' ) );
4195 } else {
4196 # Only the create and upload restrictions apply to non-existing titles
4197 $types = array_intersect( $types, array( 'create', 'upload' ) );
4199 return $types;
4203 * Returns the raw sort key to be used for categories, with the specified
4204 * prefix. This will be fed to Collation::getSortKey() to get a
4205 * binary sortkey that can be used for actual sorting.
4207 * @param $prefix string The prefix to be used, specified using
4208 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4209 * prefix.
4210 * @return string
4212 public function getCategorySortkey( $prefix = '' ) {
4213 $unprefixed = $this->getText();
4214 if ( $prefix !== '' ) {
4215 # Separate with a line feed, so the unprefixed part is only used as
4216 # a tiebreaker when two pages have the exact same prefix.
4217 # In UCA, tab is the only character that can sort above LF
4218 # so we strip both of them from the original prefix.
4219 $prefix = strtr( $prefix, "\n\t", ' ' );
4220 return "$prefix\n$unprefixed";
4222 return $unprefixed;
4227 * A BadTitle is generated in MediaWiki::parseTitle() if the title is invalid; the
4228 * software uses this to display an error page. Internally it's basically a Title
4229 * for an empty special page
4231 class BadTitle extends Title {
4232 public function __construct(){
4233 $this->mTextform = '';
4234 $this->mUrlform = '';
4235 $this->mDbkeyform = '';
4236 $this->mNamespace = NS_SPECIAL; // Stops talk page link, etc, being shown
4239 public function exists(){
4240 return false;
4243 public function getPrefixedText(){
4244 return '';
4247 public function getText(){
4248 return '';
4251 public function getPrefixedURL(){
4252 return '';
4255 public function getPrefixedDBKey(){
4256 return '';