Quick fix for bug 15892: intermittent SQL-based cache failures during parser test...
[mediawiki.git] / includes / Title.php
blob3e6690212ca0693bfa1a48a8e799393f46101269
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
7 /**
8 * @deprecated This used to be a define, but was moved to
9 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
11 define( 'GAID_FOR_UPDATE', Title::GAID_FOR_UPDATE );
13 /**
14 * Represents a title within MediaWiki.
15 * Optionally may contain an interwiki designation or namespace.
16 * @note This class can fetch various kinds of data from the database;
17 * however, it does so inefficiently.
19 * @internal documentation reviewed 15 Mar 2010
21 class Title {
22 /** @name Static cache variables */
23 // @{
24 static private $titleCache = array();
25 // @}
27 /**
28 * Title::newFromText maintains a cache to avoid expensive re-normalization of
29 * commonly used titles. On a batch operation this can become a memory leak
30 * if not bounded. After hitting this many titles reset the cache.
32 const CACHE_MAX = 1000;
34 /**
35 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
36 * to use the master DB
38 const GAID_FOR_UPDATE = 1;
41 /**
42 * @name Private member variables
43 * Please use the accessor functions instead.
44 * @private
46 // @{
48 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; // /< URL-encoded form of the main part
50 var $mDbkeyform = ''; // /< Main part with underscores
51 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
54 var $mFragment; // /< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; // /< ID of most recent revision
57 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
61 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
62 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
63 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
64 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
65 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
66 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
67 # Don't change the following default, NS_MAIN is hardcoded in several
68 # places. See bug 696.
69 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
70 # Zero except in {{transclusion}} tags
71 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
72 var $mLength = -1; // /< The page length, 0 for special pages
73 var $mRedirect = null; // /< Is the article at this title a redirect?
74 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
75 var $mBacklinkCache = null; // /< Cache of links to this title
76 // @}
79 /**
80 * Constructor
81 * @private
83 /* private */ function __construct() { }
85 /**
86 * Create a new Title from a prefixed DB key
88 * @param $key String the database key, which has underscores
89 * instead of spaces, possibly including namespace and
90 * interwiki prefixes
91 * @return Title, or NULL on an error
93 public static function newFromDBkey( $key ) {
94 $t = new Title();
95 $t->mDbkeyform = $key;
96 if ( $t->secureAndSplit() ) {
97 return $t;
98 } else {
99 return null;
104 * Create a new Title from text, such as what one would find in a link. De-
105 * codes any HTML entities in the text.
107 * @param $text String the link text; spaces, prefixes, and an
108 * initial ':' indicating the main namespace are accepted.
109 * @param $defaultNamespace Int the namespace to use if none is speci-
110 * fied by a prefix. If you want to force a specific namespace even if
111 * $text might begin with a namespace prefix, use makeTitle() or
112 * makeTitleSafe().
113 * @return Title, or null on an error.
115 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
116 if ( is_object( $text ) ) {
117 throw new MWException( 'Title::newFromText given an object' );
121 * Wiki pages often contain multiple links to the same page.
122 * Title normalization and parsing can become expensive on
123 * pages with many links, so we can save a little time by
124 * caching them.
126 * In theory these are value objects and won't get changed...
128 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
129 return Title::$titleCache[$text];
132 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
133 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
135 $t = new Title();
136 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
137 $t->mDefaultNamespace = $defaultNamespace;
139 static $cachedcount = 0 ;
140 if ( $t->secureAndSplit() ) {
141 if ( $defaultNamespace == NS_MAIN ) {
142 if ( $cachedcount >= self::CACHE_MAX ) {
143 # Avoid memory leaks on mass operations...
144 Title::$titleCache = array();
145 $cachedcount = 0;
147 $cachedcount++;
148 Title::$titleCache[$text] =& $t;
150 return $t;
151 } else {
152 $ret = null;
153 return $ret;
158 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
160 * Example of wrong and broken code:
161 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
163 * Example of right code:
164 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
166 * Create a new Title from URL-encoded text. Ensures that
167 * the given title's length does not exceed the maximum.
169 * @param $url String the title, as might be taken from a URL
170 * @return Title the new object, or NULL on an error
172 public static function newFromURL( $url ) {
173 global $wgLegalTitleChars;
174 $t = new Title();
176 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
177 # but some URLs used it as a space replacement and they still come
178 # from some external search tools.
179 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
180 $url = str_replace( '+', ' ', $url );
183 $t->mDbkeyform = str_replace( ' ', '_', $url );
184 if ( $t->secureAndSplit() ) {
185 return $t;
186 } else {
187 return null;
192 * Create a new Title from an article ID
194 * @param $id Int the page_id corresponding to the Title to create
195 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
196 * @return Title the new object, or NULL on an error
198 public static function newFromID( $id, $flags = 0 ) {
199 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
200 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
201 if ( $row !== false ) {
202 $title = Title::newFromRow( $row );
203 } else {
204 $title = null;
206 return $title;
210 * Make an array of titles from an array of IDs
212 * @param $ids Array of Int Array of IDs
213 * @return Array of Titles
215 public static function newFromIDs( $ids ) {
216 if ( !count( $ids ) ) {
217 return array();
219 $dbr = wfGetDB( DB_SLAVE );
221 $res = $dbr->select(
222 'page',
223 array(
224 'page_namespace', 'page_title', 'page_id',
225 'page_len', 'page_is_redirect', 'page_latest',
227 array( 'page_id' => $ids ),
228 __METHOD__
231 $titles = array();
232 foreach ( $res as $row ) {
233 $titles[] = Title::newFromRow( $row );
235 return $titles;
239 * Make a Title object from a DB row
241 * @param $row Object database row (needs at least page_title,page_namespace)
242 * @return Title corresponding Title
244 public static function newFromRow( $row ) {
245 $t = self::makeTitle( $row->page_namespace, $row->page_title );
247 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
248 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
249 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
250 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
252 return $t;
256 * Create a new Title from a namespace index and a DB key.
257 * It's assumed that $ns and $title are *valid*, for instance when
258 * they came directly from the database or a special page name.
259 * For convenience, spaces are converted to underscores so that
260 * eg user_text fields can be used directly.
262 * @param $ns Int the namespace of the article
263 * @param $title String the unprefixed database key form
264 * @param $fragment String the link fragment (after the "#")
265 * @param $interwiki String the interwiki prefix
266 * @return Title the new object
268 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
269 $t = new Title();
270 $t->mInterwiki = $interwiki;
271 $t->mFragment = $fragment;
272 $t->mNamespace = $ns = intval( $ns );
273 $t->mDbkeyform = str_replace( ' ', '_', $title );
274 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
275 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
276 $t->mTextform = str_replace( '_', ' ', $title );
277 return $t;
281 * Create a new Title from a namespace index and a DB key.
282 * The parameters will be checked for validity, which is a bit slower
283 * than makeTitle() but safer for user-provided data.
285 * @param $ns Int the namespace of the article
286 * @param $title String database key form
287 * @param $fragment String the link fragment (after the "#")
288 * @param $interwiki String interwiki prefix
289 * @return Title the new object, or NULL on an error
291 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
292 $t = new Title();
293 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
294 if ( $t->secureAndSplit() ) {
295 return $t;
296 } else {
297 return null;
302 * Create a new Title for the Main Page
304 * @return Title the new object
306 public static function newMainPage() {
307 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
308 // Don't give fatal errors if the message is broken
309 if ( !$title ) {
310 $title = Title::newFromText( 'Main Page' );
312 return $title;
316 * Extract a redirect destination from a string and return the
317 * Title, or null if the text doesn't contain a valid redirect
318 * This will only return the very next target, useful for
319 * the redirect table and other checks that don't need full recursion
321 * @param $text String: Text with possible redirect
322 * @return Title: The corresponding Title
324 public static function newFromRedirect( $text ) {
325 return self::newFromRedirectInternal( $text );
329 * Extract a redirect destination from a string and return the
330 * Title, or null if the text doesn't contain a valid redirect
331 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
332 * in order to provide (hopefully) the Title of the final destination instead of another redirect
334 * @param $text String Text with possible redirect
335 * @return Title
337 public static function newFromRedirectRecurse( $text ) {
338 $titles = self::newFromRedirectArray( $text );
339 return $titles ? array_pop( $titles ) : null;
343 * Extract a redirect destination from a string and return an
344 * array of Titles, or null if the text doesn't contain a valid redirect
345 * The last element in the array is the final destination after all redirects
346 * have been resolved (up to $wgMaxRedirects times)
348 * @param $text String Text with possible redirect
349 * @return Array of Titles, with the destination last
351 public static function newFromRedirectArray( $text ) {
352 global $wgMaxRedirects;
353 $title = self::newFromRedirectInternal( $text );
354 if ( is_null( $title ) ) {
355 return null;
357 // recursive check to follow double redirects
358 $recurse = $wgMaxRedirects;
359 $titles = array( $title );
360 while ( --$recurse > 0 ) {
361 if ( $title->isRedirect() ) {
362 $article = new Article( $title, 0 );
363 $newtitle = $article->getRedirectTarget();
364 } else {
365 break;
367 // Redirects to some special pages are not permitted
368 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
369 // the new title passes the checks, so make that our current title so that further recursion can be checked
370 $title = $newtitle;
371 $titles[] = $newtitle;
372 } else {
373 break;
376 return $titles;
380 * Really extract the redirect destination
381 * Do not call this function directly, use one of the newFromRedirect* functions above
383 * @param $text String Text with possible redirect
384 * @return Title
386 protected static function newFromRedirectInternal( $text ) {
387 global $wgMaxRedirects;
388 if ( $wgMaxRedirects < 1 ) {
389 //redirects are disabled, so quit early
390 return null;
392 $redir = MagicWord::get( 'redirect' );
393 $text = trim( $text );
394 if ( $redir->matchStartAndRemove( $text ) ) {
395 // Extract the first link and see if it's usable
396 // Ensure that it really does come directly after #REDIRECT
397 // Some older redirects included a colon, so don't freak about that!
398 $m = array();
399 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
400 // Strip preceding colon used to "escape" categories, etc.
401 // and URL-decode links
402 if ( strpos( $m[1], '%' ) !== false ) {
403 // Match behavior of inline link parsing here;
404 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
406 $title = Title::newFromText( $m[1] );
407 // If the title is a redirect to bad special pages or is invalid, return null
408 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
409 return null;
411 return $title;
414 return null;
417 # ----------------------------------------------------------------------------
418 # Static functions
419 # ----------------------------------------------------------------------------
422 * Get the prefixed DB key associated with an ID
424 * @param $id Int the page_id of the article
425 * @return Title an object representing the article, or NULL if no such article was found
427 public static function nameOf( $id ) {
428 $dbr = wfGetDB( DB_SLAVE );
430 $s = $dbr->selectRow(
431 'page',
432 array( 'page_namespace', 'page_title' ),
433 array( 'page_id' => $id ),
434 __METHOD__
436 if ( $s === false ) {
437 return null;
440 $n = self::makeName( $s->page_namespace, $s->page_title );
441 return $n;
445 * Get a regex character class describing the legal characters in a link
447 * @return String the list of characters, not delimited
449 public static function legalChars() {
450 global $wgLegalTitleChars;
451 return $wgLegalTitleChars;
455 * Get a string representation of a title suitable for
456 * including in a search index
458 * @param $ns Int a namespace index
459 * @param $title String text-form main part
460 * @return String a stripped-down title string ready for the search index
462 public static function indexTitle( $ns, $title ) {
463 global $wgContLang;
465 $lc = SearchEngine::legalSearchChars() . '&#;';
466 $t = $wgContLang->normalizeForSearch( $title );
467 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
468 $t = $wgContLang->lc( $t );
470 # Handle 's, s'
471 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
472 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
474 $t = preg_replace( "/\\s+/", ' ', $t );
476 if ( $ns == NS_FILE ) {
477 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
479 return trim( $t );
483 * Make a prefixed DB key from a DB key and a namespace index
485 * @param $ns Int numerical representation of the namespace
486 * @param $title String the DB key form the title
487 * @param $fragment String The link fragment (after the "#")
488 * @param $interwiki String The interwiki prefix
489 * @return String the prefixed form of the title
491 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
492 global $wgContLang;
494 $namespace = $wgContLang->getNsText( $ns );
495 $name = $namespace == '' ? $title : "$namespace:$title";
496 if ( strval( $interwiki ) != '' ) {
497 $name = "$interwiki:$name";
499 if ( strval( $fragment ) != '' ) {
500 $name .= '#' . $fragment;
502 return $name;
506 * Determine whether the object refers to a page within
507 * this project.
509 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
511 public function isLocal() {
512 if ( $this->mInterwiki != '' ) {
513 return Interwiki::fetch( $this->mInterwiki )->isLocal();
514 } else {
515 return true;
520 * Determine whether the object refers to a page within
521 * this project and is transcludable.
523 * @return Bool TRUE if this is transcludable
525 public function isTrans() {
526 if ( $this->mInterwiki == '' ) {
527 return false;
530 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
534 * Returns the DB name of the distant wiki which owns the object.
536 * @return String the DB name
538 public function getTransWikiID() {
539 if ( $this->mInterwiki == '' ) {
540 return false;
543 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
547 * Escape a text fragment, say from a link, for a URL
549 * @param $fragment string containing a URL or link fragment (after the "#")
550 * @return String: escaped string
552 static function escapeFragmentForURL( $fragment ) {
553 # Note that we don't urlencode the fragment. urlencoded Unicode
554 # fragments appear not to work in IE (at least up to 7) or in at least
555 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
556 # to care if they aren't encoded.
557 return Sanitizer::escapeId( $fragment, 'noninitial' );
560 # ----------------------------------------------------------------------------
561 # Other stuff
562 # ----------------------------------------------------------------------------
564 /** Simple accessors */
566 * Get the text form (spaces not underscores) of the main part
568 * @return String Main part of the title
570 public function getText() { return $this->mTextform; }
573 * Get the URL-encoded form of the main part
575 * @return String Main part of the title, URL-encoded
577 public function getPartialURL() { return $this->mUrlform; }
580 * Get the main part with underscores
582 * @return String: Main part of the title, with underscores
584 public function getDBkey() { return $this->mDbkeyform; }
587 * Get the namespace index, i.e. one of the NS_xxxx constants.
589 * @return Integer: Namespace index
591 public function getNamespace() { return $this->mNamespace; }
594 * Get the namespace text
596 * @return String: Namespace text
598 public function getNsText() {
599 global $wgContLang;
601 if ( $this->mInterwiki != '' ) {
602 // This probably shouldn't even happen. ohh man, oh yuck.
603 // But for interwiki transclusion it sometimes does.
604 // Shit. Shit shit shit.
606 // Use the canonical namespaces if possible to try to
607 // resolve a foreign namespace.
608 if ( MWNamespace::exists( $this->mNamespace ) ) {
609 return MWNamespace::getCanonicalName( $this->mNamespace );
613 if ( $wgContLang->needsGenderDistinction() &&
614 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
615 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
616 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
619 return $wgContLang->getNsText( $this->mNamespace );
623 * Get the DB key with the initial letter case as specified by the user
625 * @return String DB key
627 function getUserCaseDBKey() {
628 return $this->mUserCaseDBKey;
632 * Get the namespace text of the subject (rather than talk) page
634 * @return String Namespace text
636 public function getSubjectNsText() {
637 global $wgContLang;
638 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
642 * Get the namespace text of the talk page
644 * @return String Namespace text
646 public function getTalkNsText() {
647 global $wgContLang;
648 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
652 * Could this title have a corresponding talk page?
654 * @return Bool TRUE or FALSE
656 public function canTalk() {
657 return( MWNamespace::canTalk( $this->mNamespace ) );
661 * Get the interwiki prefix (or null string)
663 * @return String Interwiki prefix
665 public function getInterwiki() { return $this->mInterwiki; }
668 * Get the Title fragment (i.e.\ the bit after the #) in text form
670 * @return String Title fragment
672 public function getFragment() { return $this->mFragment; }
675 * Get the fragment in URL form, including the "#" character if there is one
676 * @return String Fragment in URL form
678 public function getFragmentForURL() {
679 if ( $this->mFragment == '' ) {
680 return '';
681 } else {
682 return '#' . Title::escapeFragmentForURL( $this->mFragment );
687 * Get the default namespace index, for when there is no namespace
689 * @return Int Default namespace index
691 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
694 * Get title for search index
696 * @return String a stripped-down title string ready for the
697 * search index
699 public function getIndexTitle() {
700 return Title::indexTitle( $this->mNamespace, $this->mTextform );
704 * Get the prefixed database key form
706 * @return String the prefixed title, with underscores and
707 * any interwiki and namespace prefixes
709 public function getPrefixedDBkey() {
710 $s = $this->prefix( $this->mDbkeyform );
711 $s = str_replace( ' ', '_', $s );
712 return $s;
716 * Get the prefixed title with spaces.
717 * This is the form usually used for display
719 * @return String the prefixed title, with spaces
721 public function getPrefixedText() {
722 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
723 $s = $this->prefix( $this->mTextform );
724 $s = str_replace( '_', ' ', $s );
725 $this->mPrefixedText = $s;
727 return $this->mPrefixedText;
731 * Get the prefixed title with spaces, plus any fragment
732 * (part beginning with '#')
734 * @return String the prefixed title, with spaces and the fragment, including '#'
736 public function getFullText() {
737 $text = $this->getPrefixedText();
738 if ( $this->mFragment != '' ) {
739 $text .= '#' . $this->mFragment;
741 return $text;
745 * Get the base name, i.e. the leftmost parts before the /
747 * @return String Base name
749 public function getBaseText() {
750 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
751 return $this->getText();
754 $parts = explode( '/', $this->getText() );
755 # Don't discard the real title if there's no subpage involved
756 if ( count( $parts ) > 1 ) {
757 unset( $parts[count( $parts ) - 1] );
759 return implode( '/', $parts );
763 * Get the lowest-level subpage name, i.e. the rightmost part after /
765 * @return String Subpage name
767 public function getSubpageText() {
768 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
769 return( $this->mTextform );
771 $parts = explode( '/', $this->mTextform );
772 return( $parts[count( $parts ) - 1] );
776 * Get a URL-encoded form of the subpage text
778 * @return String URL-encoded subpage name
780 public function getSubpageUrlForm() {
781 $text = $this->getSubpageText();
782 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
783 return( $text );
787 * Get a URL-encoded title (not an actual URL) including interwiki
789 * @return String the URL-encoded form
791 public function getPrefixedURL() {
792 $s = $this->prefix( $this->mDbkeyform );
793 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
794 return $s;
798 * Get a real URL referring to this title, with interwiki link and
799 * fragment
801 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
802 * links. Can be specified as an associative array as well, e.g.,
803 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
804 * @param $variant String language variant of url (for sr, zh..)
805 * @return String the URL
807 public function getFullURL( $query = '', $variant = false ) {
808 global $wgServer, $wgRequest;
810 if ( is_array( $query ) ) {
811 $query = wfArrayToCGI( $query );
814 $interwiki = Interwiki::fetch( $this->mInterwiki );
815 if ( !$interwiki ) {
816 $url = $this->getLocalURL( $query, $variant );
818 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
819 // Correct fix would be to move the prepending elsewhere.
820 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
821 $url = $wgServer . $url;
823 } else {
824 $baseUrl = $interwiki->getURL();
826 $namespace = wfUrlencode( $this->getNsText() );
827 if ( $namespace != '' ) {
828 # Can this actually happen? Interwikis shouldn't be parsed.
829 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
830 $namespace .= ':';
832 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
833 $url = wfAppendQuery( $url, $query );
836 # Finally, add the fragment.
837 $url .= $this->getFragmentForURL();
839 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
840 return $url;
844 * Get a URL with no fragment or server name. If this page is generated
845 * with action=render, $wgServer is prepended.
847 * @param $query Mixed: an optional query string; if not specified,
848 * $wgArticlePath will be used. Can be specified as an associative array
849 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
850 * URL-escaped).
851 * @param $variant String language variant of url (for sr, zh..)
852 * @return String the URL
854 public function getLocalURL( $query = '', $variant = false ) {
855 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
856 global $wgVariantArticlePath, $wgContLang;
858 if ( is_array( $query ) ) {
859 $query = wfArrayToCGI( $query );
862 if ( $this->isExternal() ) {
863 $url = $this->getFullURL();
864 if ( $query ) {
865 // This is currently only used for edit section links in the
866 // context of interwiki transclusion. In theory we should
867 // append the query to the end of any existing query string,
868 // but interwiki transclusion is already broken in that case.
869 $url .= "?$query";
871 } else {
872 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
873 if ( $query == '' ) {
874 if ( $variant != false && $wgContLang->hasVariants() ) {
875 if ( !$wgVariantArticlePath ) {
876 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
877 } else {
878 $variantArticlePath = $wgVariantArticlePath;
880 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
881 $url = str_replace( '$1', $dbkey, $url );
882 } else {
883 $url = str_replace( '$1', $dbkey, $wgArticlePath );
885 } else {
886 global $wgActionPaths;
887 $url = false;
888 $matches = array();
889 if ( !empty( $wgActionPaths ) &&
890 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
892 $action = urldecode( $matches[2] );
893 if ( isset( $wgActionPaths[$action] ) ) {
894 $query = $matches[1];
895 if ( isset( $matches[4] ) ) {
896 $query .= $matches[4];
898 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
899 if ( $query != '' ) {
900 $url = wfAppendQuery( $url, $query );
904 if ( $url === false ) {
905 if ( $query == '-' ) {
906 $query = '';
908 $url = "{$wgScript}?title={$dbkey}&{$query}";
912 // FIXME: this causes breakage in various places when we
913 // actually expected a local URL and end up with dupe prefixes.
914 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
915 $url = $wgServer . $url;
918 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
919 return $url;
923 * Get a URL that's the simplest URL that will be valid to link, locally,
924 * to the current Title. It includes the fragment, but does not include
925 * the server unless action=render is used (or the link is external). If
926 * there's a fragment but the prefixed text is empty, we just return a link
927 * to the fragment.
929 * The result obviously should not be URL-escaped, but does need to be
930 * HTML-escaped if it's being output in HTML.
932 * @param $query Array of Strings An associative array of key => value pairs for the
933 * query string. Keys and values will be escaped.
934 * @param $variant String language variant of URL (for sr, zh..). Ignored
935 * for external links. Default is "false" (same variant as current page,
936 * for anonymous users).
937 * @return String the URL
939 public function getLinkUrl( $query = array(), $variant = false ) {
940 wfProfileIn( __METHOD__ );
941 if ( $this->isExternal() ) {
942 $ret = $this->getFullURL( $query );
943 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
944 $ret = $this->getFragmentForURL();
945 } else {
946 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
948 wfProfileOut( __METHOD__ );
949 return $ret;
953 * Get an HTML-escaped version of the URL form, suitable for
954 * using in a link, without a server name or fragment
956 * @param $query String an optional query string
957 * @return String the URL
959 public function escapeLocalURL( $query = '' ) {
960 return htmlspecialchars( $this->getLocalURL( $query ) );
964 * Get an HTML-escaped version of the URL form, suitable for
965 * using in a link, including the server name and fragment
967 * @param $query String an optional query string
968 * @return String the URL
970 public function escapeFullURL( $query = '' ) {
971 return htmlspecialchars( $this->getFullURL( $query ) );
975 * Get the URL form for an internal link.
976 * - Used in various Squid-related code, in case we have a different
977 * internal hostname for the server from the exposed one.
979 * @param $query String an optional query string
980 * @param $variant String language variant of url (for sr, zh..)
981 * @return String the URL
983 public function getInternalURL( $query = '', $variant = false ) {
984 global $wgInternalServer, $wgServer;
985 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
986 $url = $server . $this->getLocalURL( $query, $variant );
987 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
988 return $url;
992 * Get the edit URL for this Title
994 * @return String the URL, or a null string if this is an
995 * interwiki link
997 public function getEditURL() {
998 if ( $this->mInterwiki != '' ) {
999 return '';
1001 $s = $this->getLocalURL( 'action=edit' );
1003 return $s;
1007 * Get the HTML-escaped displayable text form.
1008 * Used for the title field in <a> tags.
1010 * @return String the text, including any prefixes
1012 public function getEscapedText() {
1013 return htmlspecialchars( $this->getPrefixedText() );
1017 * Is this Title interwiki?
1019 * @return Bool
1021 public function isExternal() {
1022 return ( $this->mInterwiki != '' );
1026 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1028 * @param $action String Action to check (default: edit)
1029 * @return Bool
1031 public function isSemiProtected( $action = 'edit' ) {
1032 if ( $this->exists() ) {
1033 $restrictions = $this->getRestrictions( $action );
1034 if ( count( $restrictions ) > 0 ) {
1035 foreach ( $restrictions as $restriction ) {
1036 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1037 return false;
1040 } else {
1041 # Not protected
1042 return false;
1044 return true;
1045 } else {
1046 # If it doesn't exist, it can't be protected
1047 return false;
1052 * Does the title correspond to a protected article?
1054 * @param $action String the action the page is protected from,
1055 * by default checks all actions.
1056 * @return Bool
1058 public function isProtected( $action = '' ) {
1059 global $wgRestrictionLevels;
1061 $restrictionTypes = $this->getRestrictionTypes();
1063 # Special pages have inherent protection
1064 if( $this->getNamespace() == NS_SPECIAL ) {
1065 return true;
1068 # Check regular protection levels
1069 foreach ( $restrictionTypes as $type ) {
1070 if ( $action == $type || $action == '' ) {
1071 $r = $this->getRestrictions( $type );
1072 foreach ( $wgRestrictionLevels as $level ) {
1073 if ( in_array( $level, $r ) && $level != '' ) {
1074 return true;
1080 return false;
1084 * Is this a conversion table for the LanguageConverter?
1086 * @return Bool
1088 public function isConversionTable() {
1090 $this->getNamespace() == NS_MEDIAWIKI &&
1091 strpos( $this->getText(), 'Conversiontable' ) !== false
1094 return true;
1097 return false;
1101 * Is $wgUser watching this page?
1103 * @return Bool
1105 public function userIsWatching() {
1106 global $wgUser;
1108 if ( is_null( $this->mWatched ) ) {
1109 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1110 $this->mWatched = false;
1111 } else {
1112 $this->mWatched = $wgUser->isWatched( $this );
1115 return $this->mWatched;
1119 * Can $wgUser perform $action on this page?
1120 * This skips potentially expensive cascading permission checks
1121 * as well as avoids expensive error formatting
1123 * Suitable for use for nonessential UI controls in common cases, but
1124 * _not_ for functional access control.
1126 * May provide false positives, but should never provide a false negative.
1128 * @param $action String action that permission needs to be checked for
1129 * @return Bool
1131 public function quickUserCan( $action ) {
1132 return $this->userCan( $action, false );
1136 * Determines if $user is unable to edit this page because it has been protected
1137 * by $wgNamespaceProtection.
1139 * @param $user User object, $wgUser will be used if not passed
1140 * @return Bool
1142 public function isNamespaceProtected( User $user = null ) {
1143 global $wgNamespaceProtection;
1145 if ( $user === null ) {
1146 global $wgUser;
1147 $user = $wgUser;
1150 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1151 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1152 if ( $right != '' && !$user->isAllowed( $right ) ) {
1153 return true;
1157 return false;
1161 * Can $wgUser perform $action on this page?
1163 * @param $action String action that permission needs to be checked for
1164 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1165 * @return Bool
1167 public function userCan( $action, $doExpensiveQueries = true ) {
1168 global $wgUser;
1169 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1173 * Can $user perform $action on this page?
1175 * FIXME: This *does not* check throttles (User::pingLimiter()).
1177 * @param $action String action that permission needs to be checked for
1178 * @param $user User to check
1179 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1180 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1181 * @return Array of arguments to wfMsg to explain permissions problems.
1183 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1184 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1186 // Remove the errors being ignored.
1187 foreach ( $errors as $index => $error ) {
1188 $error_key = is_array( $error ) ? $error[0] : $error;
1190 if ( in_array( $error_key, $ignoreErrors ) ) {
1191 unset( $errors[$index] );
1195 return $errors;
1199 * Permissions checks that fail most often, and which are easiest to test.
1201 * @param $action String the action to check
1202 * @param $user User user to check
1203 * @param $errors Array list of current errors
1204 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1205 * @param $short Boolean short circuit on first error
1207 * @return Array list of errors
1209 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1210 if ( $action == 'create' ) {
1211 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1212 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1213 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1215 } elseif ( $action == 'move' ) {
1216 if ( !$user->isAllowed( 'move-rootuserpages' )
1217 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1218 // Show user page-specific message only if the user can move other pages
1219 $errors[] = array( 'cant-move-user-page' );
1222 // Check if user is allowed to move files if it's a file
1223 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1224 $errors[] = array( 'movenotallowedfile' );
1227 if ( !$user->isAllowed( 'move' ) ) {
1228 // User can't move anything
1229 global $wgGroupPermissions;
1230 $userCanMove = false;
1231 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1232 $userCanMove = $wgGroupPermissions['user']['move'];
1234 $autoconfirmedCanMove = false;
1235 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1236 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1238 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1239 // custom message if logged-in users without any special rights can move
1240 $errors[] = array( 'movenologintext' );
1241 } else {
1242 $errors[] = array( 'movenotallowed' );
1245 } elseif ( $action == 'move-target' ) {
1246 if ( !$user->isAllowed( 'move' ) ) {
1247 // User can't move anything
1248 $errors[] = array( 'movenotallowed' );
1249 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1250 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1251 // Show user page-specific message only if the user can move other pages
1252 $errors[] = array( 'cant-move-to-user-page' );
1254 } elseif ( !$user->isAllowed( $action ) ) {
1255 // We avoid expensive display logic for quickUserCan's and such
1256 $groups = false;
1257 if ( !$short ) {
1258 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1259 User::getGroupsWithPermission( $action ) );
1262 if ( $groups ) {
1263 global $wgLang;
1264 $return = array(
1265 'badaccess-groups',
1266 $wgLang->commaList( $groups ),
1267 count( $groups )
1269 } else {
1270 $return = array( 'badaccess-group0' );
1272 $errors[] = $return;
1275 return $errors;
1279 * Add the resulting error code to the errors array
1281 * @param $errors Array list of current errors
1282 * @param $result Mixed result of errors
1284 * @return Array list of errors
1286 private function resultToError( $errors, $result ) {
1287 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1288 // A single array representing an error
1289 $errors[] = $result;
1290 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1291 // A nested array representing multiple errors
1292 $errors = array_merge( $errors, $result );
1293 } else if ( $result !== '' && is_string( $result ) ) {
1294 // A string representing a message-id
1295 $errors[] = array( $result );
1296 } else if ( $result === false ) {
1297 // a generic "We don't want them to do that"
1298 $errors[] = array( 'badaccess-group0' );
1300 return $errors;
1304 * Check various permission hooks
1306 * @param $action String the action to check
1307 * @param $user User user to check
1308 * @param $errors Array list of current errors
1309 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1310 * @param $short Boolean short circuit on first error
1312 * @return Array list of errors
1314 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1315 // Use getUserPermissionsErrors instead
1316 $result = '';
1317 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1318 return $result ? array() : array( array( 'badaccess-group0' ) );
1320 // Check getUserPermissionsErrors hook
1321 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1322 $errors = $this->resultToError( $errors, $result );
1324 // Check getUserPermissionsErrorsExpensive hook
1325 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1326 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1327 $errors = $this->resultToError( $errors, $result );
1330 return $errors;
1334 * Check permissions on special pages & namespaces
1336 * @param $action String the action to check
1337 * @param $user User user to check
1338 * @param $errors Array list of current errors
1339 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1340 * @param $short Boolean short circuit on first error
1342 * @return Array list of errors
1344 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1345 # Only 'createaccount' and 'execute' can be performed on
1346 # special pages, which don't actually exist in the DB.
1347 $specialOKActions = array( 'createaccount', 'execute' );
1348 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1349 $errors[] = array( 'ns-specialprotected' );
1352 # Check $wgNamespaceProtection for restricted namespaces
1353 if ( $this->isNamespaceProtected( $user ) ) {
1354 $ns = $this->mNamespace == NS_MAIN ?
1355 wfMsg( 'nstab-main' ) : $this->getNsText();
1356 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1357 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1360 return $errors;
1364 * Check CSS/JS sub-page permissions
1366 * @param $action String the action to check
1367 * @param $user User user to check
1368 * @param $errors Array list of current errors
1369 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1370 * @param $short Boolean short circuit on first error
1372 * @return Array list of errors
1374 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1375 # Protect css/js subpages of user pages
1376 # XXX: this might be better using restrictions
1377 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1378 # and $this->userCanEditJsSubpage() from working
1379 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1380 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1381 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1382 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1383 $errors[] = array( 'customcssjsprotected' );
1384 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1385 $errors[] = array( 'customcssjsprotected' );
1389 return $errors;
1393 * Check against page_restrictions table requirements on this
1394 * page. The user must possess all required rights for this
1395 * action.
1397 * @param $action String the action to check
1398 * @param $user User user to check
1399 * @param $errors Array list of current errors
1400 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1401 * @param $short Boolean short circuit on first error
1403 * @return Array list of errors
1405 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1406 foreach ( $this->getRestrictions( $action ) as $right ) {
1407 // Backwards compatibility, rewrite sysop -> protect
1408 if ( $right == 'sysop' ) {
1409 $right = 'protect';
1411 if ( $right != '' && !$user->isAllowed( $right ) ) {
1412 // Users with 'editprotected' permission can edit protected pages
1413 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1414 // Users with 'editprotected' permission cannot edit protected pages
1415 // with cascading option turned on.
1416 if ( $this->mCascadeRestriction ) {
1417 $errors[] = array( 'protectedpagetext', $right );
1419 } else {
1420 $errors[] = array( 'protectedpagetext', $right );
1425 return $errors;
1429 * Check restrictions on cascading pages.
1431 * @param $action String the action to check
1432 * @param $user User to check
1433 * @param $errors Array list of current errors
1434 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1435 * @param $short Boolean short circuit on first error
1437 * @return Array list of errors
1439 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1440 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1441 # We /could/ use the protection level on the source page, but it's
1442 # fairly ugly as we have to establish a precedence hierarchy for pages
1443 # included by multiple cascade-protected pages. So just restrict
1444 # it to people with 'protect' permission, as they could remove the
1445 # protection anyway.
1446 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1447 # Cascading protection depends on more than this page...
1448 # Several cascading protected pages may include this page...
1449 # Check each cascading level
1450 # This is only for protection restrictions, not for all actions
1451 if ( isset( $restrictions[$action] ) ) {
1452 foreach ( $restrictions[$action] as $right ) {
1453 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1454 if ( $right != '' && !$user->isAllowed( $right ) ) {
1455 $pages = '';
1456 foreach ( $cascadingSources as $page )
1457 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1458 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1464 return $errors;
1468 * Check action permissions not already checked in checkQuickPermissions
1470 * @param $action String the action to check
1471 * @param $user User to check
1472 * @param $errors Array list of current errors
1473 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1474 * @param $short Boolean short circuit on first error
1476 * @return Array list of errors
1478 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1479 if ( $action == 'protect' ) {
1480 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1481 // If they can't edit, they shouldn't protect.
1482 $errors[] = array( 'protect-cantedit' );
1484 } elseif ( $action == 'create' ) {
1485 $title_protection = $this->getTitleProtection();
1486 if( $title_protection ) {
1487 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1488 $title_protection['pt_create_perm'] = 'protect'; // B/C
1490 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1491 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1494 } elseif ( $action == 'move' ) {
1495 // Check for immobile pages
1496 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1497 // Specific message for this case
1498 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1499 } elseif ( !$this->isMovable() ) {
1500 // Less specific message for rarer cases
1501 $errors[] = array( 'immobile-page' );
1503 } elseif ( $action == 'move-target' ) {
1504 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1505 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1506 } elseif ( !$this->isMovable() ) {
1507 $errors[] = array( 'immobile-target-page' );
1510 return $errors;
1514 * Check that the user isn't blocked from editting.
1516 * @param $action String the action to check
1517 * @param $user User to check
1518 * @param $errors Array list of current errors
1519 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1520 * @param $short Boolean short circuit on first error
1522 * @return Array list of errors
1524 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1525 if( $short && count( $errors ) > 0 ) {
1526 return $errors;
1529 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1531 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1532 $errors[] = array( 'confirmedittext' );
1535 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1536 // Edit blocks should not affect reading.
1537 // Account creation blocks handled at userlogin.
1538 // Unblocking handled in SpecialUnblock
1539 } elseif( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1540 // Don't block the user from editing their own talk page unless they've been
1541 // explicitly blocked from that too.
1542 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1543 $block = $user->mBlock;
1545 // This is from OutputPage::blockedPage
1546 // Copied at r23888 by werdna
1548 $id = $user->blockedBy();
1549 $reason = $user->blockedFor();
1550 if ( $reason == '' ) {
1551 $reason = wfMsg( 'blockednoreason' );
1553 $ip = wfGetIP();
1555 if ( is_numeric( $id ) ) {
1556 $name = User::whoIs( $id );
1557 } else {
1558 $name = $id;
1561 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1562 $blockid = $block->getId();
1563 $blockExpiry = $user->mBlock->mExpiry;
1564 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1565 if ( $blockExpiry == 'infinity' ) {
1566 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1567 } else {
1568 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1571 $intended = strval( $user->mBlock->getTarget() );
1573 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1574 $blockid, $blockExpiry, $intended, $blockTimestamp );
1577 return $errors;
1581 * Can $user perform $action on this page? This is an internal function,
1582 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1583 * checks on wfReadOnly() and blocks)
1585 * @param $action String action that permission needs to be checked for
1586 * @param $user User to check
1587 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1588 * @param $short Bool Set this to true to stop after the first permission error.
1589 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1591 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1592 wfProfileIn( __METHOD__ );
1594 $errors = array();
1595 $checks = array(
1596 'checkQuickPermissions',
1597 'checkPermissionHooks',
1598 'checkSpecialsAndNSPermissions',
1599 'checkCSSandJSPermissions',
1600 'checkPageRestrictions',
1601 'checkCascadingSourcesRestrictions',
1602 'checkActionPermissions',
1603 'checkUserBlock'
1606 while( count( $checks ) > 0 &&
1607 !( $short && count( $errors ) > 0 ) ) {
1608 $method = array_shift( $checks );
1609 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1612 wfProfileOut( __METHOD__ );
1613 return $errors;
1617 * Is this title subject to title protection?
1618 * Title protection is the one applied against creation of such title.
1620 * @return Mixed An associative array representing any existent title
1621 * protection, or false if there's none.
1623 private function getTitleProtection() {
1624 // Can't protect pages in special namespaces
1625 if ( $this->getNamespace() < 0 ) {
1626 return false;
1629 // Can't protect pages that exist.
1630 if ( $this->exists() ) {
1631 return false;
1634 if ( !isset( $this->mTitleProtection ) ) {
1635 $dbr = wfGetDB( DB_SLAVE );
1636 $res = $dbr->select( 'protected_titles', '*',
1637 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1638 __METHOD__ );
1640 // fetchRow returns false if there are no rows.
1641 $this->mTitleProtection = $dbr->fetchRow( $res );
1643 return $this->mTitleProtection;
1647 * Update the title protection status
1649 * @param $create_perm String Permission required for creation
1650 * @param $reason String Reason for protection
1651 * @param $expiry String Expiry timestamp
1652 * @return boolean true
1654 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1655 global $wgUser, $wgContLang;
1657 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1658 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1659 // No change
1660 return true;
1663 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1665 $dbw = wfGetDB( DB_MASTER );
1667 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1669 $expiry_description = '';
1670 if ( $encodedExpiry != $dbw->getInfinity() ) {
1671 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1672 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1673 } else {
1674 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1677 # Update protection table
1678 if ( $create_perm != '' ) {
1679 $this->mTitleProtection = array(
1680 'pt_namespace' => $namespace,
1681 'pt_title' => $title,
1682 'pt_create_perm' => $create_perm,
1683 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1684 'pt_expiry' => $encodedExpiry,
1685 'pt_user' => $wgUser->getId(),
1686 'pt_reason' => $reason,
1688 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1689 $this->mTitleProtection, __METHOD__ );
1690 } else {
1691 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1692 'pt_title' => $title ), __METHOD__ );
1693 $this->mTitleProtection = false;
1696 # Update the protection log
1697 if ( $dbw->affectedRows() ) {
1698 $log = new LogPage( 'protect' );
1700 if ( $create_perm ) {
1701 $params = array( "[create=$create_perm] $expiry_description", '' );
1702 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1703 } else {
1704 $log->addEntry( 'unprotect', $this, $reason );
1708 return true;
1712 * Remove any title protection due to page existing
1714 public function deleteTitleProtection() {
1715 $dbw = wfGetDB( DB_MASTER );
1717 $dbw->delete(
1718 'protected_titles',
1719 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1720 __METHOD__
1722 $this->mTitleProtection = false;
1726 * Would anybody with sufficient privileges be able to move this page?
1727 * Some pages just aren't movable.
1729 * @return Bool TRUE or FALSE
1731 public function isMovable() {
1732 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1736 * Can $wgUser read this page?
1738 * @return Bool
1739 * @todo fold these checks into userCan()
1741 public function userCanRead() {
1742 global $wgUser, $wgGroupPermissions;
1744 static $useShortcut = null;
1746 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1747 if ( is_null( $useShortcut ) ) {
1748 global $wgRevokePermissions;
1749 $useShortcut = true;
1750 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1751 # Not a public wiki, so no shortcut
1752 $useShortcut = false;
1753 } elseif ( !empty( $wgRevokePermissions ) ) {
1755 * Iterate through each group with permissions being revoked (key not included since we don't care
1756 * what the group name is), then check if the read permission is being revoked. If it is, then
1757 * we don't use the shortcut below since the user might not be able to read, even though anon
1758 * reading is allowed.
1760 foreach ( $wgRevokePermissions as $perms ) {
1761 if ( !empty( $perms['read'] ) ) {
1762 # We might be removing the read right from the user, so no shortcut
1763 $useShortcut = false;
1764 break;
1770 $result = null;
1771 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1772 if ( $result !== null ) {
1773 return $result;
1776 # Shortcut for public wikis, allows skipping quite a bit of code
1777 if ( $useShortcut ) {
1778 return true;
1781 if ( $wgUser->isAllowed( 'read' ) ) {
1782 return true;
1783 } else {
1784 global $wgWhitelistRead;
1786 # Always grant access to the login page.
1787 # Even anons need to be able to log in.
1788 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1789 return true;
1792 # Bail out if there isn't whitelist
1793 if ( !is_array( $wgWhitelistRead ) ) {
1794 return false;
1797 # Check for explicit whitelisting
1798 $name = $this->getPrefixedText();
1799 $dbName = $this->getPrefixedDBKey();
1800 // Check with and without underscores
1801 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1802 return true;
1804 # Old settings might have the title prefixed with
1805 # a colon for main-namespace pages
1806 if ( $this->getNamespace() == NS_MAIN ) {
1807 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1808 return true;
1812 # If it's a special page, ditch the subpage bit and check again
1813 if ( $this->getNamespace() == NS_SPECIAL ) {
1814 $name = $this->getDBkey();
1815 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1816 if ( $name === false ) {
1817 # Invalid special page, but we show standard login required message
1818 return false;
1821 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1822 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1823 return true;
1828 return false;
1832 * Is this the mainpage?
1833 * @note Title::newFromText seams to be sufficiently optimized by the title
1834 * cache that we don't need to over-optimize by doing direct comparisons and
1835 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1836 * ends up reporting something differently than $title->isMainPage();
1838 * @return Bool
1840 public function isMainPage() {
1841 return $this->equals( Title::newMainPage() );
1845 * Is this a talk page of some sort?
1847 * @return Bool
1849 public function isTalkPage() {
1850 return MWNamespace::isTalk( $this->getNamespace() );
1854 * Is this a subpage?
1856 * @return Bool
1858 public function isSubpage() {
1859 return MWNamespace::hasSubpages( $this->mNamespace )
1860 ? strpos( $this->getText(), '/' ) !== false
1861 : false;
1865 * Does this have subpages? (Warning, usually requires an extra DB query.)
1867 * @return Bool
1869 public function hasSubpages() {
1870 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1871 # Duh
1872 return false;
1875 # We dynamically add a member variable for the purpose of this method
1876 # alone to cache the result. There's no point in having it hanging
1877 # around uninitialized in every Title object; therefore we only add it
1878 # if needed and don't declare it statically.
1879 if ( isset( $this->mHasSubpages ) ) {
1880 return $this->mHasSubpages;
1883 $subpages = $this->getSubpages( 1 );
1884 if ( $subpages instanceof TitleArray ) {
1885 return $this->mHasSubpages = (bool)$subpages->count();
1887 return $this->mHasSubpages = false;
1891 * Get all subpages of this page.
1893 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1894 * @return mixed TitleArray, or empty array if this page's namespace
1895 * doesn't allow subpages
1897 public function getSubpages( $limit = -1 ) {
1898 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1899 return array();
1902 $dbr = wfGetDB( DB_SLAVE );
1903 $conds['page_namespace'] = $this->getNamespace();
1904 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1905 $options = array();
1906 if ( $limit > -1 ) {
1907 $options['LIMIT'] = $limit;
1909 return $this->mSubpages = TitleArray::newFromResult(
1910 $dbr->select( 'page',
1911 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1912 $conds,
1913 __METHOD__,
1914 $options
1920 * Could this page contain custom CSS or JavaScript, based
1921 * on the title?
1923 * @return Bool
1925 public function isCssOrJsPage() {
1926 return $this->mNamespace == NS_MEDIAWIKI
1927 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1931 * Is this a .css or .js subpage of a user page?
1932 * @return Bool
1934 public function isCssJsSubpage() {
1935 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1939 * Is this a *valid* .css or .js subpage of a user page?
1941 * @return Bool
1942 * @deprecated since 1.17
1944 public function isValidCssJsSubpage() {
1945 return $this->isCssJsSubpage();
1949 * Trim down a .css or .js subpage title to get the corresponding skin name
1951 * @return string containing skin name from .css or .js subpage title
1953 public function getSkinFromCssJsSubpage() {
1954 $subpage = explode( '/', $this->mTextform );
1955 $subpage = $subpage[ count( $subpage ) - 1 ];
1956 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1960 * Is this a .css subpage of a user page?
1962 * @return Bool
1964 public function isCssSubpage() {
1965 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1969 * Is this a .js subpage of a user page?
1971 * @return Bool
1973 public function isJsSubpage() {
1974 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1978 * Protect css subpages of user pages: can $wgUser edit
1979 * this page?
1981 * @return Bool
1982 * @todo XXX: this might be better using restrictions
1984 public function userCanEditCssSubpage() {
1985 global $wgUser;
1986 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1987 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
1991 * Protect js subpages of user pages: can $wgUser edit
1992 * this page?
1994 * @return Bool
1995 * @todo XXX: this might be better using restrictions
1997 public function userCanEditJsSubpage() {
1998 global $wgUser;
1999 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2000 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2004 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2006 * @return Bool If the page is subject to cascading restrictions.
2008 public function isCascadeProtected() {
2009 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2010 return ( $sources > 0 );
2014 * Cascading protection: Get the source of any cascading restrictions on this page.
2016 * @param $getPages Bool Whether or not to retrieve the actual pages
2017 * that the restrictions have come from.
2018 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2019 * have come, false for none, or true if such restrictions exist, but $getPages
2020 * was not set. The restriction array is an array of each type, each of which
2021 * contains a array of unique groups.
2023 public function getCascadeProtectionSources( $getPages = true ) {
2024 global $wgContLang;
2025 $pagerestrictions = array();
2027 if ( isset( $this->mCascadeSources ) && $getPages ) {
2028 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2029 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2030 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2033 wfProfileIn( __METHOD__ );
2035 $dbr = wfGetDB( DB_SLAVE );
2037 if ( $this->getNamespace() == NS_FILE ) {
2038 $tables = array( 'imagelinks', 'page_restrictions' );
2039 $where_clauses = array(
2040 'il_to' => $this->getDBkey(),
2041 'il_from=pr_page',
2042 'pr_cascade' => 1
2044 } else {
2045 $tables = array( 'templatelinks', 'page_restrictions' );
2046 $where_clauses = array(
2047 'tl_namespace' => $this->getNamespace(),
2048 'tl_title' => $this->getDBkey(),
2049 'tl_from=pr_page',
2050 'pr_cascade' => 1
2054 if ( $getPages ) {
2055 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2056 'pr_expiry', 'pr_type', 'pr_level' );
2057 $where_clauses[] = 'page_id=pr_page';
2058 $tables[] = 'page';
2059 } else {
2060 $cols = array( 'pr_expiry' );
2063 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2065 $sources = $getPages ? array() : false;
2066 $now = wfTimestampNow();
2067 $purgeExpired = false;
2069 foreach ( $res as $row ) {
2070 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2071 if ( $expiry > $now ) {
2072 if ( $getPages ) {
2073 $page_id = $row->pr_page;
2074 $page_ns = $row->page_namespace;
2075 $page_title = $row->page_title;
2076 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2077 # Add groups needed for each restriction type if its not already there
2078 # Make sure this restriction type still exists
2080 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2081 $pagerestrictions[$row->pr_type] = array();
2084 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2085 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2086 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2088 } else {
2089 $sources = true;
2091 } else {
2092 // Trigger lazy purge of expired restrictions from the db
2093 $purgeExpired = true;
2096 if ( $purgeExpired ) {
2097 Title::purgeExpiredRestrictions();
2100 if ( $getPages ) {
2101 $this->mCascadeSources = $sources;
2102 $this->mCascadingRestrictions = $pagerestrictions;
2103 } else {
2104 $this->mHasCascadingRestrictions = $sources;
2107 wfProfileOut( __METHOD__ );
2108 return array( $sources, $pagerestrictions );
2112 * Returns cascading restrictions for the current article
2114 * @return Boolean
2116 function areRestrictionsCascading() {
2117 if ( !$this->mRestrictionsLoaded ) {
2118 $this->loadRestrictions();
2121 return $this->mCascadeRestriction;
2125 * Loads a string into mRestrictions array
2127 * @param $res Resource restrictions as an SQL result.
2128 * @param $oldFashionedRestrictions String comma-separated list of page
2129 * restrictions from page table (pre 1.10)
2131 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2132 $rows = array();
2134 foreach ( $res as $row ) {
2135 $rows[] = $row;
2138 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2142 * Compiles list of active page restrictions from both page table (pre 1.10)
2143 * and page_restrictions table for this existing page.
2144 * Public for usage by LiquidThreads.
2146 * @param $rows array of db result objects
2147 * @param $oldFashionedRestrictions string comma-separated list of page
2148 * restrictions from page table (pre 1.10)
2150 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2151 global $wgContLang;
2152 $dbr = wfGetDB( DB_SLAVE );
2154 $restrictionTypes = $this->getRestrictionTypes();
2156 foreach ( $restrictionTypes as $type ) {
2157 $this->mRestrictions[$type] = array();
2158 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2161 $this->mCascadeRestriction = false;
2163 # Backwards-compatibility: also load the restrictions from the page record (old format).
2165 if ( $oldFashionedRestrictions === null ) {
2166 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2167 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2170 if ( $oldFashionedRestrictions != '' ) {
2172 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2173 $temp = explode( '=', trim( $restrict ) );
2174 if ( count( $temp ) == 1 ) {
2175 // old old format should be treated as edit/move restriction
2176 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2177 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2178 } else {
2179 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2183 $this->mOldRestrictions = true;
2187 if ( count( $rows ) ) {
2188 # Current system - load second to make them override.
2189 $now = wfTimestampNow();
2190 $purgeExpired = false;
2192 # Cycle through all the restrictions.
2193 foreach ( $rows as $row ) {
2195 // Don't take care of restrictions types that aren't allowed
2196 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2197 continue;
2199 // This code should be refactored, now that it's being used more generally,
2200 // But I don't really see any harm in leaving it in Block for now -werdna
2201 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2203 // Only apply the restrictions if they haven't expired!
2204 if ( !$expiry || $expiry > $now ) {
2205 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2206 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2208 $this->mCascadeRestriction |= $row->pr_cascade;
2209 } else {
2210 // Trigger a lazy purge of expired restrictions
2211 $purgeExpired = true;
2215 if ( $purgeExpired ) {
2216 Title::purgeExpiredRestrictions();
2220 $this->mRestrictionsLoaded = true;
2224 * Load restrictions from the page_restrictions table
2226 * @param $oldFashionedRestrictions String comma-separated list of page
2227 * restrictions from page table (pre 1.10)
2229 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2230 global $wgContLang;
2231 if ( !$this->mRestrictionsLoaded ) {
2232 if ( $this->exists() ) {
2233 $dbr = wfGetDB( DB_SLAVE );
2235 $res = $dbr->select(
2236 'page_restrictions',
2237 '*',
2238 array( 'pr_page' => $this->getArticleId() ),
2239 __METHOD__
2242 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2243 } else {
2244 $title_protection = $this->getTitleProtection();
2246 if ( $title_protection ) {
2247 $now = wfTimestampNow();
2248 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2250 if ( !$expiry || $expiry > $now ) {
2251 // Apply the restrictions
2252 $this->mRestrictionsExpiry['create'] = $expiry;
2253 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2254 } else { // Get rid of the old restrictions
2255 Title::purgeExpiredRestrictions();
2256 $this->mTitleProtection = false;
2258 } else {
2259 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2261 $this->mRestrictionsLoaded = true;
2267 * Purge expired restrictions from the page_restrictions table
2269 static function purgeExpiredRestrictions() {
2270 $dbw = wfGetDB( DB_MASTER );
2271 $dbw->delete(
2272 'page_restrictions',
2273 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2274 __METHOD__
2277 $dbw->delete(
2278 'protected_titles',
2279 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2280 __METHOD__
2285 * Accessor/initialisation for mRestrictions
2287 * @param $action String action that permission needs to be checked for
2288 * @return Array of Strings the array of groups allowed to edit this article
2290 public function getRestrictions( $action ) {
2291 if ( !$this->mRestrictionsLoaded ) {
2292 $this->loadRestrictions();
2294 return isset( $this->mRestrictions[$action] )
2295 ? $this->mRestrictions[$action]
2296 : array();
2300 * Get the expiry time for the restriction against a given action
2302 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2303 * or not protected at all, or false if the action is not recognised.
2305 public function getRestrictionExpiry( $action ) {
2306 if ( !$this->mRestrictionsLoaded ) {
2307 $this->loadRestrictions();
2309 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2313 * Is there a version of this page in the deletion archive?
2315 * @return Int the number of archived revisions
2317 public function isDeleted() {
2318 if ( $this->getNamespace() < 0 ) {
2319 $n = 0;
2320 } else {
2321 $dbr = wfGetDB( DB_SLAVE );
2322 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2323 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2324 __METHOD__
2326 if ( $this->getNamespace() == NS_FILE ) {
2327 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2328 array( 'fa_name' => $this->getDBkey() ),
2329 __METHOD__
2333 return (int)$n;
2337 * Is there a version of this page in the deletion archive?
2339 * @return Boolean
2341 public function isDeletedQuick() {
2342 if ( $this->getNamespace() < 0 ) {
2343 return false;
2345 $dbr = wfGetDB( DB_SLAVE );
2346 $deleted = (bool)$dbr->selectField( 'archive', '1',
2347 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2348 __METHOD__
2350 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2351 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2352 array( 'fa_name' => $this->getDBkey() ),
2353 __METHOD__
2356 return $deleted;
2360 * Get the article ID for this Title from the link cache,
2361 * adding it if necessary
2363 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2364 * for update
2365 * @return Int the ID
2367 public function getArticleID( $flags = 0 ) {
2368 if ( $this->getNamespace() < 0 ) {
2369 return $this->mArticleID = 0;
2371 $linkCache = LinkCache::singleton();
2372 if ( $flags & self::GAID_FOR_UPDATE ) {
2373 $oldUpdate = $linkCache->forUpdate( true );
2374 $linkCache->clearLink( $this );
2375 $this->mArticleID = $linkCache->addLinkObj( $this );
2376 $linkCache->forUpdate( $oldUpdate );
2377 } else {
2378 if ( -1 == $this->mArticleID ) {
2379 $this->mArticleID = $linkCache->addLinkObj( $this );
2382 return $this->mArticleID;
2386 * Is this an article that is a redirect page?
2387 * Uses link cache, adding it if necessary
2389 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2390 * @return Bool
2392 public function isRedirect( $flags = 0 ) {
2393 if ( !is_null( $this->mRedirect ) ) {
2394 return $this->mRedirect;
2396 # Calling getArticleID() loads the field from cache as needed
2397 if ( !$this->getArticleID( $flags ) ) {
2398 return $this->mRedirect = false;
2400 $linkCache = LinkCache::singleton();
2401 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2403 return $this->mRedirect;
2407 * What is the length of this page?
2408 * Uses link cache, adding it if necessary
2410 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2411 * @return Int
2413 public function getLength( $flags = 0 ) {
2414 if ( $this->mLength != -1 ) {
2415 return $this->mLength;
2417 # Calling getArticleID() loads the field from cache as needed
2418 if ( !$this->getArticleID( $flags ) ) {
2419 return $this->mLength = 0;
2421 $linkCache = LinkCache::singleton();
2422 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2424 return $this->mLength;
2428 * What is the page_latest field for this page?
2430 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2431 * @return Int or 0 if the page doesn't exist
2433 public function getLatestRevID( $flags = 0 ) {
2434 if ( $this->mLatestID !== false ) {
2435 return intval( $this->mLatestID );
2437 # Calling getArticleID() loads the field from cache as needed
2438 if ( !$this->getArticleID( $flags ) ) {
2439 return $this->mLatestID = 0;
2441 $linkCache = LinkCache::singleton();
2442 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2444 return $this->mLatestID;
2448 * This clears some fields in this object, and clears any associated
2449 * keys in the "bad links" section of the link cache.
2451 * - This is called from Article::doEdit() and Article::insertOn() to allow
2452 * loading of the new page_id. It's also called from
2453 * Article::doDeleteArticle()
2455 * @param $newid Int the new Article ID
2457 public function resetArticleID( $newid ) {
2458 $linkCache = LinkCache::singleton();
2459 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2461 if ( $newid === false ) {
2462 $this->mArticleID = -1;
2463 } else {
2464 $this->mArticleID = intval( $newid );
2466 $this->mRestrictionsLoaded = false;
2467 $this->mRestrictions = array();
2468 $this->mRedirect = null;
2469 $this->mLength = -1;
2470 $this->mLatestID = false;
2474 * Updates page_touched for this page; called from LinksUpdate.php
2476 * @return Bool true if the update succeded
2478 public function invalidateCache() {
2479 if ( wfReadOnly() ) {
2480 return;
2482 $dbw = wfGetDB( DB_MASTER );
2483 $success = $dbw->update(
2484 'page',
2485 array( 'page_touched' => $dbw->timestamp() ),
2486 $this->pageCond(),
2487 __METHOD__
2489 HTMLFileCache::clearFileCache( $this );
2490 return $success;
2494 * Prefix some arbitrary text with the namespace or interwiki prefix
2495 * of this object
2497 * @param $name String the text
2498 * @return String the prefixed text
2499 * @private
2501 /* private */ function prefix( $name ) {
2502 $p = '';
2503 if ( $this->mInterwiki != '' ) {
2504 $p = $this->mInterwiki . ':';
2507 if ( 0 != $this->mNamespace ) {
2508 $p .= $this->getNsText() . ':';
2510 return $p . $name;
2514 * Returns a simple regex that will match on characters and sequences invalid in titles.
2515 * Note that this doesn't pick up many things that could be wrong with titles, but that
2516 * replacing this regex with something valid will make many titles valid.
2518 * @return String regex string
2520 static function getTitleInvalidRegex() {
2521 static $rxTc = false;
2522 if ( !$rxTc ) {
2523 # Matching titles will be held as illegal.
2524 $rxTc = '/' .
2525 # Any character not allowed is forbidden...
2526 '[^' . Title::legalChars() . ']' .
2527 # URL percent encoding sequences interfere with the ability
2528 # to round-trip titles -- you can't link to them consistently.
2529 '|%[0-9A-Fa-f]{2}' .
2530 # XML/HTML character references produce similar issues.
2531 '|&[A-Za-z0-9\x80-\xff]+;' .
2532 '|&#[0-9]+;' .
2533 '|&#x[0-9A-Fa-f]+;' .
2534 '/S';
2537 return $rxTc;
2541 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2543 * @param $text String containing title to capitalize
2544 * @param $ns int namespace index, defaults to NS_MAIN
2545 * @return String containing capitalized title
2547 public static function capitalize( $text, $ns = NS_MAIN ) {
2548 global $wgContLang;
2550 if ( MWNamespace::isCapitalized( $ns ) ) {
2551 return $wgContLang->ucfirst( $text );
2552 } else {
2553 return $text;
2558 * Secure and split - main initialisation function for this object
2560 * Assumes that mDbkeyform has been set, and is urldecoded
2561 * and uses underscores, but not otherwise munged. This function
2562 * removes illegal characters, splits off the interwiki and
2563 * namespace prefixes, sets the other forms, and canonicalizes
2564 * everything.
2566 * @return Bool true on success
2568 private function secureAndSplit() {
2569 global $wgContLang, $wgLocalInterwiki;
2571 # Initialisation
2572 $rxTc = self::getTitleInvalidRegex();
2574 $this->mInterwiki = $this->mFragment = '';
2575 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2577 $dbkey = $this->mDbkeyform;
2579 # Strip Unicode bidi override characters.
2580 # Sometimes they slip into cut-n-pasted page titles, where the
2581 # override chars get included in list displays.
2582 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2584 # Clean up whitespace
2585 # Note: use of the /u option on preg_replace here will cause
2586 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2587 # conveniently disabling them.
2588 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2589 $dbkey = trim( $dbkey, '_' );
2591 if ( $dbkey == '' ) {
2592 return false;
2595 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2596 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2597 return false;
2600 $this->mDbkeyform = $dbkey;
2602 # Initial colon indicates main namespace rather than specified default
2603 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2604 if ( ':' == $dbkey { 0 } ) {
2605 $this->mNamespace = NS_MAIN;
2606 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2607 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2610 # Namespace or interwiki prefix
2611 $firstPass = true;
2612 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2613 do {
2614 $m = array();
2615 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2616 $p = $m[1];
2617 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2618 # Ordinary namespace
2619 $dbkey = $m[2];
2620 $this->mNamespace = $ns;
2621 # For Talk:X pages, check if X has a "namespace" prefix
2622 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2623 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2624 # Disallow Talk:File:x type titles...
2625 return false;
2626 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2627 # Disallow Talk:Interwiki:x type titles...
2628 return false;
2631 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2632 if ( !$firstPass ) {
2633 # Can't make a local interwiki link to an interwiki link.
2634 # That's just crazy!
2635 return false;
2638 # Interwiki link
2639 $dbkey = $m[2];
2640 $this->mInterwiki = $wgContLang->lc( $p );
2642 # Redundant interwiki prefix to the local wiki
2643 if ( $wgLocalInterwiki !== false
2644 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2646 if ( $dbkey == '' ) {
2647 # Can't have an empty self-link
2648 return false;
2650 $this->mInterwiki = '';
2651 $firstPass = false;
2652 # Do another namespace split...
2653 continue;
2656 # If there's an initial colon after the interwiki, that also
2657 # resets the default namespace
2658 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2659 $this->mNamespace = NS_MAIN;
2660 $dbkey = substr( $dbkey, 1 );
2663 # If there's no recognized interwiki or namespace,
2664 # then let the colon expression be part of the title.
2666 break;
2667 } while ( true );
2669 # We already know that some pages won't be in the database!
2670 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2671 $this->mArticleID = 0;
2673 $fragment = strstr( $dbkey, '#' );
2674 if ( false !== $fragment ) {
2675 $this->setFragment( $fragment );
2676 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2677 # remove whitespace again: prevents "Foo_bar_#"
2678 # becoming "Foo_bar_"
2679 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2682 # Reject illegal characters.
2683 if ( preg_match( $rxTc, $dbkey ) ) {
2684 return false;
2687 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2688 # reachable due to the way web browsers deal with 'relative' URLs.
2689 # Also, they conflict with subpage syntax. Forbid them explicitly.
2690 if ( strpos( $dbkey, '.' ) !== false &&
2691 ( $dbkey === '.' || $dbkey === '..' ||
2692 strpos( $dbkey, './' ) === 0 ||
2693 strpos( $dbkey, '../' ) === 0 ||
2694 strpos( $dbkey, '/./' ) !== false ||
2695 strpos( $dbkey, '/../' ) !== false ||
2696 substr( $dbkey, -2 ) == '/.' ||
2697 substr( $dbkey, -3 ) == '/..' ) )
2699 return false;
2702 # Magic tilde sequences? Nu-uh!
2703 if ( strpos( $dbkey, '~~~' ) !== false ) {
2704 return false;
2707 # Limit the size of titles to 255 bytes. This is typically the size of the
2708 # underlying database field. We make an exception for special pages, which
2709 # don't need to be stored in the database, and may edge over 255 bytes due
2710 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2711 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2712 strlen( $dbkey ) > 512 )
2714 return false;
2717 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2718 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2719 # other site might be case-sensitive.
2720 $this->mUserCaseDBKey = $dbkey;
2721 if ( $this->mInterwiki == '' ) {
2722 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2725 # Can't make a link to a namespace alone... "empty" local links can only be
2726 # self-links with a fragment identifier.
2727 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2728 return false;
2731 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2732 // IP names are not allowed for accounts, and can only be referring to
2733 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2734 // there are numerous ways to present the same IP. Having sp:contribs scan
2735 // them all is silly and having some show the edits and others not is
2736 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2737 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2738 ? IP::sanitizeIP( $dbkey )
2739 : $dbkey;
2741 // Any remaining initial :s are illegal.
2742 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2743 return false;
2746 # Fill fields
2747 $this->mDbkeyform = $dbkey;
2748 $this->mUrlform = wfUrlencode( $dbkey );
2750 $this->mTextform = str_replace( '_', ' ', $dbkey );
2752 return true;
2756 * Set the fragment for this title. Removes the first character from the
2757 * specified fragment before setting, so it assumes you're passing it with
2758 * an initial "#".
2760 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2761 * Still in active use privately.
2763 * @param $fragment String text
2765 public function setFragment( $fragment ) {
2766 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2770 * Get a Title object associated with the talk page of this article
2772 * @return Title the object for the talk page
2774 public function getTalkPage() {
2775 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2779 * Get a title object associated with the subject page of this
2780 * talk page
2782 * @return Title the object for the subject page
2784 public function getSubjectPage() {
2785 // Is this the same title?
2786 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2787 if ( $this->getNamespace() == $subjectNS ) {
2788 return $this;
2790 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2794 * Get an array of Title objects linking to this Title
2795 * Also stores the IDs in the link cache.
2797 * WARNING: do not use this function on arbitrary user-supplied titles!
2798 * On heavily-used templates it will max out the memory.
2800 * @param $options Array: may be FOR UPDATE
2801 * @param $table String: table name
2802 * @param $prefix String: fields prefix
2803 * @return Array of Title objects linking here
2805 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2806 $linkCache = LinkCache::singleton();
2808 if ( count( $options ) > 0 ) {
2809 $db = wfGetDB( DB_MASTER );
2810 } else {
2811 $db = wfGetDB( DB_SLAVE );
2814 $res = $db->select(
2815 array( 'page', $table ),
2816 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2817 array(
2818 "{$prefix}_from=page_id",
2819 "{$prefix}_namespace" => $this->getNamespace(),
2820 "{$prefix}_title" => $this->getDBkey() ),
2821 __METHOD__,
2822 $options
2825 $retVal = array();
2826 if ( $db->numRows( $res ) ) {
2827 foreach ( $res as $row ) {
2828 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2829 if ( $titleObj ) {
2830 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2831 $retVal[] = $titleObj;
2835 return $retVal;
2839 * Get an array of Title objects using this Title as a template
2840 * Also stores the IDs in the link cache.
2842 * WARNING: do not use this function on arbitrary user-supplied titles!
2843 * On heavily-used templates it will max out the memory.
2845 * @param $options Array: may be FOR UPDATE
2846 * @return Array of Title the Title objects linking here
2848 public function getTemplateLinksTo( $options = array() ) {
2849 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2853 * Get an array of Title objects referring to non-existent articles linked from this page
2855 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2856 * @return Array of Title the Title objects
2858 public function getBrokenLinksFrom() {
2859 if ( $this->getArticleId() == 0 ) {
2860 # All links from article ID 0 are false positives
2861 return array();
2864 $dbr = wfGetDB( DB_SLAVE );
2865 $res = $dbr->select(
2866 array( 'page', 'pagelinks' ),
2867 array( 'pl_namespace', 'pl_title' ),
2868 array(
2869 'pl_from' => $this->getArticleId(),
2870 'page_namespace IS NULL'
2872 __METHOD__, array(),
2873 array(
2874 'page' => array(
2875 'LEFT JOIN',
2876 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2881 $retVal = array();
2882 foreach ( $res as $row ) {
2883 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2885 return $retVal;
2890 * Get a list of URLs to purge from the Squid cache when this
2891 * page changes
2893 * @return Array of String the URLs
2895 public function getSquidURLs() {
2896 global $wgContLang;
2898 $urls = array(
2899 $this->getInternalURL(),
2900 $this->getInternalURL( 'action=history' )
2903 // purge variant urls as well
2904 if ( $wgContLang->hasVariants() ) {
2905 $variants = $wgContLang->getVariants();
2906 foreach ( $variants as $vCode ) {
2907 $urls[] = $this->getInternalURL( '', $vCode );
2911 return $urls;
2915 * Purge all applicable Squid URLs
2917 public function purgeSquid() {
2918 global $wgUseSquid;
2919 if ( $wgUseSquid ) {
2920 $urls = $this->getSquidURLs();
2921 $u = new SquidUpdate( $urls );
2922 $u->doUpdate();
2927 * Move this page without authentication
2929 * @param $nt Title the new page Title
2930 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2932 public function moveNoAuth( &$nt ) {
2933 return $this->moveTo( $nt, false );
2937 * Check whether a given move operation would be valid.
2938 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2940 * @param $nt Title the new title
2941 * @param $auth Bool indicates whether $wgUser's permissions
2942 * should be checked
2943 * @param $reason String is the log summary of the move, used for spam checking
2944 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2946 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2947 global $wgUser;
2949 $errors = array();
2950 if ( !$nt ) {
2951 // Normally we'd add this to $errors, but we'll get
2952 // lots of syntax errors if $nt is not an object
2953 return array( array( 'badtitletext' ) );
2955 if ( $this->equals( $nt ) ) {
2956 $errors[] = array( 'selfmove' );
2958 if ( !$this->isMovable() ) {
2959 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2961 if ( $nt->getInterwiki() != '' ) {
2962 $errors[] = array( 'immobile-target-namespace-iw' );
2964 if ( !$nt->isMovable() ) {
2965 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2968 $oldid = $this->getArticleID();
2969 $newid = $nt->getArticleID();
2971 if ( strlen( $nt->getDBkey() ) < 1 ) {
2972 $errors[] = array( 'articleexists' );
2974 if ( ( $this->getDBkey() == '' ) ||
2975 ( !$oldid ) ||
2976 ( $nt->getDBkey() == '' ) ) {
2977 $errors[] = array( 'badarticleerror' );
2980 // Image-specific checks
2981 if ( $this->getNamespace() == NS_FILE ) {
2982 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2985 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
2986 $errors[] = array( 'nonfile-cannot-move-to-file' );
2989 if ( $auth ) {
2990 $errors = wfMergeErrorArrays( $errors,
2991 $this->getUserPermissionsErrors( 'move', $wgUser ),
2992 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2993 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2994 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2997 $match = EditPage::matchSummarySpamRegex( $reason );
2998 if ( $match !== false ) {
2999 // This is kind of lame, won't display nice
3000 $errors[] = array( 'spamprotectiontext' );
3003 $err = null;
3004 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3005 $errors[] = array( 'hookaborted', $err );
3008 # The move is allowed only if (1) the target doesn't exist, or
3009 # (2) the target is a redirect to the source, and has no history
3010 # (so we can undo bad moves right after they're done).
3012 if ( 0 != $newid ) { # Target exists; check for validity
3013 if ( !$this->isValidMoveTarget( $nt ) ) {
3014 $errors[] = array( 'articleexists' );
3016 } else {
3017 $tp = $nt->getTitleProtection();
3018 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3019 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3020 $errors[] = array( 'cantmove-titleprotected' );
3023 if ( empty( $errors ) ) {
3024 return true;
3026 return $errors;
3030 * Check if the requested move target is a valid file move target
3031 * @param Title $nt Target title
3032 * @return array List of errors
3034 protected function validateFileMoveOperation( $nt ) {
3035 global $wgUser;
3037 $errors = array();
3039 if ( $nt->getNamespace() != NS_FILE ) {
3040 $errors[] = array( 'imagenocrossnamespace' );
3043 $file = wfLocalFile( $this );
3044 if ( $file->exists() ) {
3045 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3046 $errors[] = array( 'imageinvalidfilename' );
3048 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3049 $errors[] = array( 'imagetypemismatch' );
3053 $destFile = wfLocalFile( $nt );
3054 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3055 $errors[] = array( 'file-exists-sharedrepo' );
3058 return $errors;
3062 * Move a title to a new location
3064 * @param $nt Title the new title
3065 * @param $auth Bool indicates whether $wgUser's permissions
3066 * should be checked
3067 * @param $reason String the reason for the move
3068 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3069 * Ignored if the user doesn't have the suppressredirect right.
3070 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3072 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3073 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3074 if ( is_array( $err ) ) {
3075 return $err;
3078 // If it is a file, move it first. It is done before all other moving stuff is
3079 // done because it's hard to revert
3080 $dbw = wfGetDB( DB_MASTER );
3081 if ( $this->getNamespace() == NS_FILE ) {
3082 $file = wfLocalFile( $this );
3083 if ( $file->exists() ) {
3084 $status = $file->move( $nt );
3085 if ( !$status->isOk() ) {
3086 return $status->getErrorsArray();
3091 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3092 $pageid = $this->getArticleID( GAID_FOR_UPDATE );
3093 $protected = $this->isProtected();
3094 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3096 // Do the actual move
3097 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3098 if ( is_array( $err ) ) {
3099 # FIXME: What about the File we have already moved?
3100 $dbw->rollback();
3101 return $err;
3104 $redirid = $this->getArticleID();
3106 // Refresh the sortkey for this row. Be careful to avoid resetting
3107 // cl_timestamp, which may disturb time-based lists on some sites.
3108 $prefixes = $dbw->select(
3109 'categorylinks',
3110 array( 'cl_sortkey_prefix', 'cl_to' ),
3111 array( 'cl_from' => $pageid ),
3112 __METHOD__
3114 foreach ( $prefixes as $prefixRow ) {
3115 $prefix = $prefixRow->cl_sortkey_prefix;
3116 $catTo = $prefixRow->cl_to;
3117 $dbw->update( 'categorylinks',
3118 array(
3119 'cl_sortkey' => Collation::singleton()->getSortKey(
3120 $nt->getCategorySortkey( $prefix ) ),
3121 'cl_timestamp=cl_timestamp' ),
3122 array(
3123 'cl_from' => $pageid,
3124 'cl_to' => $catTo ),
3125 __METHOD__
3129 if ( $protected ) {
3130 # Protect the redirect title as the title used to be...
3131 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3132 array(
3133 'pr_page' => $redirid,
3134 'pr_type' => 'pr_type',
3135 'pr_level' => 'pr_level',
3136 'pr_cascade' => 'pr_cascade',
3137 'pr_user' => 'pr_user',
3138 'pr_expiry' => 'pr_expiry'
3140 array( 'pr_page' => $pageid ),
3141 __METHOD__,
3142 array( 'IGNORE' )
3144 # Update the protection log
3145 $log = new LogPage( 'protect' );
3146 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3147 if ( $reason ) {
3148 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3150 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3153 # Update watchlists
3154 $oldnamespace = $this->getNamespace() & ~1;
3155 $newnamespace = $nt->getNamespace() & ~1;
3156 $oldtitle = $this->getDBkey();
3157 $newtitle = $nt->getDBkey();
3159 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3160 WatchedItem::duplicateEntries( $this, $nt );
3163 # Update search engine
3164 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3165 $u->doUpdate();
3166 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3167 $u->doUpdate();
3169 $dbw->commit();
3171 # Update site_stats
3172 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3173 # No longer a content page
3174 # Not viewed, edited, removing
3175 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3176 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3177 # Now a content page
3178 # Not viewed, edited, adding
3179 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3180 } elseif ( $pageCountChange ) {
3181 # Redirect added
3182 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3183 } else {
3184 # Nothing special
3185 $u = false;
3187 if ( $u ) {
3188 $u->doUpdate();
3190 # Update message cache for interface messages
3191 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3192 # @bug 17860: old article can be deleted, if this the case,
3193 # delete it from message cache
3194 if ( $this->getArticleID() === 0 ) {
3195 MessageCache::singleton()->replace( $this->getDBkey(), false );
3196 } else {
3197 $oldarticle = new Article( $this );
3198 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3201 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3202 $newarticle = new Article( $nt );
3203 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3206 global $wgUser;
3207 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3208 return true;
3212 * Move page to a title which is either a redirect to the
3213 * source page or nonexistent
3215 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3216 * @param $reason String The reason for the move
3217 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3218 * if the user doesn't have the suppressredirect right
3220 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3221 global $wgUser, $wgContLang;
3223 $moveOverRedirect = $nt->exists();
3225 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3226 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3228 if ( $reason ) {
3229 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3231 # Truncate for whole multibyte characters.
3232 $comment = $wgContLang->truncate( $comment, 255 );
3234 $oldid = $this->getArticleID();
3235 $latest = $this->getLatestRevID();
3237 $oldns = $this->getNamespace();
3238 $olddbk = $this->getDBkey();
3240 $dbw = wfGetDB( DB_MASTER );
3242 if ( $moveOverRedirect ) {
3243 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3245 $newid = $nt->getArticleID();
3246 $newns = $nt->getNamespace();
3247 $newdbk = $nt->getDBkey();
3249 # Delete the old redirect. We don't save it to history since
3250 # by definition if we've got here it's rather uninteresting.
3251 # We have to remove it so that the next step doesn't trigger
3252 # a conflict on the unique namespace+title index...
3253 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3254 if ( !$dbw->cascadingDeletes() ) {
3255 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3256 global $wgUseTrackbacks;
3257 if ( $wgUseTrackbacks ) {
3258 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3260 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3261 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3262 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3263 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3264 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3265 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3266 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3268 // If the target page was recently created, it may have an entry in recentchanges still
3269 $dbw->delete( 'recentchanges',
3270 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3271 __METHOD__
3275 # Save a null revision in the page's history notifying of the move
3276 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3277 if ( !is_object( $nullRevision ) ) {
3278 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3280 $nullRevId = $nullRevision->insertOn( $dbw );
3282 $article = new Article( $this );
3283 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3285 # Change the name of the target page:
3286 $dbw->update( 'page',
3287 /* SET */ array(
3288 'page_touched' => $dbw->timestamp(),
3289 'page_namespace' => $nt->getNamespace(),
3290 'page_title' => $nt->getDBkey(),
3291 'page_latest' => $nullRevId,
3293 /* WHERE */ array( 'page_id' => $oldid ),
3294 __METHOD__
3296 $nt->resetArticleID( $oldid );
3298 # Recreate the redirect, this time in the other direction.
3299 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3300 $mwRedir = MagicWord::get( 'redirect' );
3301 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3302 $redirectArticle = new Article( $this );
3303 $newid = $redirectArticle->insertOn( $dbw );
3304 $redirectRevision = new Revision( array(
3305 'page' => $newid,
3306 'comment' => $comment,
3307 'text' => $redirectText ) );
3308 $redirectRevision->insertOn( $dbw );
3309 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3311 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3313 # Now, we record the link from the redirect to the new title.
3314 # It should have no other outgoing links...
3315 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3316 $dbw->insert( 'pagelinks',
3317 array(
3318 'pl_from' => $newid,
3319 'pl_namespace' => $nt->getNamespace(),
3320 'pl_title' => $nt->getDBkey() ),
3321 __METHOD__ );
3322 $redirectSuppressed = false;
3323 } else {
3324 // Get rid of old new page entries in Special:NewPages and RC.
3325 // Needs to be before $this->resetArticleID( 0 ).
3326 $dbw->delete( 'recentchanges', array(
3327 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3328 'rc_namespace' => $oldns,
3329 'rc_title' => $olddbk,
3330 'rc_new' => 1
3332 __METHOD__
3335 $this->resetArticleID( 0 );
3336 $redirectSuppressed = true;
3339 # Log the move
3340 $log = new LogPage( 'move' );
3341 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3342 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3344 # Purge caches for old and new titles
3345 if ( $moveOverRedirect ) {
3346 # A simple purge is enough when moving over a redirect
3347 $nt->purgeSquid();
3348 } else {
3349 # Purge caches as per article creation, including any pages that link to this title
3350 Article::onArticleCreate( $nt );
3352 $this->purgeSquid();
3356 * Move this page's subpages to be subpages of $nt
3358 * @param $nt Title Move target
3359 * @param $auth bool Whether $wgUser's permissions should be checked
3360 * @param $reason string The reason for the move
3361 * @param $createRedirect bool Whether to create redirects from the old subpages to
3362 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3363 * @return mixed array with old page titles as keys, and strings (new page titles) or
3364 * arrays (errors) as values, or an error array with numeric indices if no pages
3365 * were moved
3367 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3368 global $wgMaximumMovedPages;
3369 // Check permissions
3370 if ( !$this->userCan( 'move-subpages' ) ) {
3371 return array( 'cant-move-subpages' );
3373 // Do the source and target namespaces support subpages?
3374 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3375 return array( 'namespace-nosubpages',
3376 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3378 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3379 return array( 'namespace-nosubpages',
3380 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3383 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3384 $retval = array();
3385 $count = 0;
3386 foreach ( $subpages as $oldSubpage ) {
3387 $count++;
3388 if ( $count > $wgMaximumMovedPages ) {
3389 $retval[$oldSubpage->getPrefixedTitle()] =
3390 array( 'movepage-max-pages',
3391 $wgMaximumMovedPages );
3392 break;
3395 // We don't know whether this function was called before
3396 // or after moving the root page, so check both
3397 // $this and $nt
3398 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3399 $oldSubpage->getArticleID() == $nt->getArticleId() )
3401 // When moving a page to a subpage of itself,
3402 // don't move it twice
3403 continue;
3405 $newPageName = preg_replace(
3406 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3407 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3408 $oldSubpage->getDBkey() );
3409 if ( $oldSubpage->isTalkPage() ) {
3410 $newNs = $nt->getTalkPage()->getNamespace();
3411 } else {
3412 $newNs = $nt->getSubjectPage()->getNamespace();
3414 # Bug 14385: we need makeTitleSafe because the new page names may
3415 # be longer than 255 characters.
3416 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3418 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3419 if ( $success === true ) {
3420 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3421 } else {
3422 $retval[$oldSubpage->getPrefixedText()] = $success;
3425 return $retval;
3429 * Checks if this page is just a one-rev redirect.
3430 * Adds lock, so don't use just for light purposes.
3432 * @return Bool
3434 public function isSingleRevRedirect() {
3435 $dbw = wfGetDB( DB_MASTER );
3436 # Is it a redirect?
3437 $row = $dbw->selectRow( 'page',
3438 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3439 $this->pageCond(),
3440 __METHOD__,
3441 array( 'FOR UPDATE' )
3443 # Cache some fields we may want
3444 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3445 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3446 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3447 if ( !$this->mRedirect ) {
3448 return false;
3450 # Does the article have a history?
3451 $row = $dbw->selectField( array( 'page', 'revision' ),
3452 'rev_id',
3453 array( 'page_namespace' => $this->getNamespace(),
3454 'page_title' => $this->getDBkey(),
3455 'page_id=rev_page',
3456 'page_latest != rev_id'
3458 __METHOD__,
3459 array( 'FOR UPDATE' )
3461 # Return true if there was no history
3462 return ( $row === false );
3466 * Checks if $this can be moved to a given Title
3467 * - Selects for update, so don't call it unless you mean business
3469 * @param $nt Title the new title to check
3470 * @return Bool
3472 public function isValidMoveTarget( $nt ) {
3473 # Is it an existing file?
3474 if ( $nt->getNamespace() == NS_FILE ) {
3475 $file = wfLocalFile( $nt );
3476 if ( $file->exists() ) {
3477 wfDebug( __METHOD__ . ": file exists\n" );
3478 return false;
3481 # Is it a redirect with no history?
3482 if ( !$nt->isSingleRevRedirect() ) {
3483 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3484 return false;
3486 # Get the article text
3487 $rev = Revision::newFromTitle( $nt );
3488 $text = $rev->getText();
3489 # Does the redirect point to the source?
3490 # Or is it a broken self-redirect, usually caused by namespace collisions?
3491 $m = array();
3492 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3493 $redirTitle = Title::newFromText( $m[1] );
3494 if ( !is_object( $redirTitle ) ||
3495 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3496 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3497 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3498 return false;
3500 } else {
3501 # Fail safe
3502 wfDebug( __METHOD__ . ": failsafe\n" );
3503 return false;
3505 return true;
3509 * Can this title be added to a user's watchlist?
3511 * @return Bool TRUE or FALSE
3513 public function isWatchable() {
3514 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3518 * Get categories to which this Title belongs and return an array of
3519 * categories' names.
3521 * @return Array of parents in the form:
3522 * $parent => $currentarticle
3524 public function getParentCategories() {
3525 global $wgContLang;
3527 $data = array();
3529 $titleKey = $this->getArticleId();
3531 if ( $titleKey === 0 ) {
3532 return $data;
3535 $dbr = wfGetDB( DB_SLAVE );
3537 $res = $dbr->select( 'categorylinks', '*',
3538 array(
3539 'cl_from' => $titleKey,
3541 __METHOD__,
3542 array()
3545 if ( $dbr->numRows( $res ) > 0 ) {
3546 foreach ( $res as $row ) {
3547 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3548 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3551 return $data;
3555 * Get a tree of parent categories
3557 * @param $children Array with the children in the keys, to check for circular refs
3558 * @return Array Tree of parent categories
3560 public function getParentCategoryTree( $children = array() ) {
3561 $stack = array();
3562 $parents = $this->getParentCategories();
3564 if ( $parents ) {
3565 foreach ( $parents as $parent => $current ) {
3566 if ( array_key_exists( $parent, $children ) ) {
3567 # Circular reference
3568 $stack[$parent] = array();
3569 } else {
3570 $nt = Title::newFromText( $parent );
3571 if ( $nt ) {
3572 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3578 return $stack;
3582 * Get an associative array for selecting this title from
3583 * the "page" table
3585 * @return Array suitable for the $where parameter of DB::select()
3587 public function pageCond() {
3588 if ( $this->mArticleID > 0 ) {
3589 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3590 return array( 'page_id' => $this->mArticleID );
3591 } else {
3592 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3597 * Get the revision ID of the previous revision
3599 * @param $revId Int Revision ID. Get the revision that was before this one.
3600 * @param $flags Int Title::GAID_FOR_UPDATE
3601 * @return Int|Bool Old revision ID, or FALSE if none exists
3603 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3604 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3605 return $db->selectField( 'revision', 'rev_id',
3606 array(
3607 'rev_page' => $this->getArticleId( $flags ),
3608 'rev_id < ' . intval( $revId )
3610 __METHOD__,
3611 array( 'ORDER BY' => 'rev_id DESC' )
3616 * Get the revision ID of the next revision
3618 * @param $revId Int Revision ID. Get the revision that was after this one.
3619 * @param $flags Int Title::GAID_FOR_UPDATE
3620 * @return Int|Bool Next revision ID, or FALSE if none exists
3622 public function getNextRevisionID( $revId, $flags = 0 ) {
3623 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3624 return $db->selectField( 'revision', 'rev_id',
3625 array(
3626 'rev_page' => $this->getArticleId( $flags ),
3627 'rev_id > ' . intval( $revId )
3629 __METHOD__,
3630 array( 'ORDER BY' => 'rev_id' )
3635 * Get the first revision of the page
3637 * @param $flags Int Title::GAID_FOR_UPDATE
3638 * @return Revision|Null if page doesn't exist
3640 public function getFirstRevision( $flags = 0 ) {
3641 $pageId = $this->getArticleId( $flags );
3642 if ( $pageId ) {
3643 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3644 $row = $db->selectRow( 'revision', '*',
3645 array( 'rev_page' => $pageId ),
3646 __METHOD__,
3647 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3649 if ( $row ) {
3650 return new Revision( $row );
3653 return null;
3657 * Get the oldest revision timestamp of this page
3659 * @param $flags Int Title::GAID_FOR_UPDATE
3660 * @return String: MW timestamp
3662 public function getEarliestRevTime( $flags = 0 ) {
3663 $rev = $this->getFirstRevision( $flags );
3664 return $rev ? $rev->getTimestamp() : null;
3668 * Check if this is a new page
3670 * @return bool
3672 public function isNewPage() {
3673 $dbr = wfGetDB( DB_SLAVE );
3674 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3678 * Get the number of revisions between the given revision.
3679 * Used for diffs and other things that really need it.
3681 * @param $old int|Revision Old revision or rev ID (first before range)
3682 * @param $new int|Revision New revision or rev ID (first after range)
3683 * @return Int Number of revisions between these revisions.
3685 public function countRevisionsBetween( $old, $new ) {
3686 if ( !( $old instanceof Revision ) ) {
3687 $old = Revision::newFromTitle( $this, (int)$old );
3689 if ( !( $new instanceof Revision ) ) {
3690 $new = Revision::newFromTitle( $this, (int)$new );
3692 if ( !$old || !$new ) {
3693 return 0; // nothing to compare
3695 $dbr = wfGetDB( DB_SLAVE );
3696 return (int)$dbr->selectField( 'revision', 'count(*)',
3697 array(
3698 'rev_page' => $this->getArticleId(),
3699 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3700 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3702 __METHOD__
3707 * Get the number of authors between the given revision IDs.
3708 * Used for diffs and other things that really need it.
3710 * @param $old int|Revision Old revision or rev ID (first before range)
3711 * @param $new int|Revision New revision or rev ID (first after range)
3712 * @param $limit Int Maximum number of authors
3713 * @return Int Number of revision authors between these revisions.
3715 public function countAuthorsBetween( $old, $new, $limit ) {
3716 if ( !( $old instanceof Revision ) ) {
3717 $old = Revision::newFromTitle( $this, (int)$old );
3719 if ( !( $new instanceof Revision ) ) {
3720 $new = Revision::newFromTitle( $this, (int)$new );
3722 if ( !$old || !$new ) {
3723 return 0; // nothing to compare
3725 $dbr = wfGetDB( DB_SLAVE );
3726 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3727 array(
3728 'rev_page' => $this->getArticleID(),
3729 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3730 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3731 ), __METHOD__,
3732 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
3734 return (int)$dbr->numRows( $res );
3738 * Compare with another title.
3740 * @param $title Title
3741 * @return Bool
3743 public function equals( Title $title ) {
3744 // Note: === is necessary for proper matching of number-like titles.
3745 return $this->getInterwiki() === $title->getInterwiki()
3746 && $this->getNamespace() == $title->getNamespace()
3747 && $this->getDBkey() === $title->getDBkey();
3751 * Callback for usort() to do title sorts by (namespace, title)
3753 * @param $a Title
3754 * @param $b Title
3756 * @return Integer: result of string comparison, or namespace comparison
3758 public static function compare( $a, $b ) {
3759 if ( $a->getNamespace() == $b->getNamespace() ) {
3760 return strcmp( $a->getText(), $b->getText() );
3761 } else {
3762 return $a->getNamespace() - $b->getNamespace();
3767 * Return a string representation of this title
3769 * @return String representation of this title
3771 public function __toString() {
3772 return $this->getPrefixedText();
3776 * Check if page exists. For historical reasons, this function simply
3777 * checks for the existence of the title in the page table, and will
3778 * thus return false for interwiki links, special pages and the like.
3779 * If you want to know if a title can be meaningfully viewed, you should
3780 * probably call the isKnown() method instead.
3782 * @return Bool
3784 public function exists() {
3785 return $this->getArticleId() != 0;
3789 * Should links to this title be shown as potentially viewable (i.e. as
3790 * "bluelinks"), even if there's no record by this title in the page
3791 * table?
3793 * This function is semi-deprecated for public use, as well as somewhat
3794 * misleadingly named. You probably just want to call isKnown(), which
3795 * calls this function internally.
3797 * (ISSUE: Most of these checks are cheap, but the file existence check
3798 * can potentially be quite expensive. Including it here fixes a lot of
3799 * existing code, but we might want to add an optional parameter to skip
3800 * it and any other expensive checks.)
3802 * @return Bool
3804 public function isAlwaysKnown() {
3805 if ( $this->mInterwiki != '' ) {
3806 return true; // any interwiki link might be viewable, for all we know
3808 switch( $this->mNamespace ) {
3809 case NS_MEDIA:
3810 case NS_FILE:
3811 // file exists, possibly in a foreign repo
3812 return (bool)wfFindFile( $this );
3813 case NS_SPECIAL:
3814 // valid special page
3815 return SpecialPage::exists( $this->getDBkey() );
3816 case NS_MAIN:
3817 // selflink, possibly with fragment
3818 return $this->mDbkeyform == '';
3819 case NS_MEDIAWIKI:
3820 // known system message
3821 return $this->getDefaultMessageText() !== false;
3822 default:
3823 return false;
3828 * Does this title refer to a page that can (or might) be meaningfully
3829 * viewed? In particular, this function may be used to determine if
3830 * links to the title should be rendered as "bluelinks" (as opposed to
3831 * "redlinks" to non-existent pages).
3833 * @return Bool
3835 public function isKnown() {
3836 return $this->isAlwaysKnown() || $this->exists();
3840 * Does this page have source text?
3842 * @return Boolean
3844 public function hasSourceText() {
3845 if ( $this->exists() ) {
3846 return true;
3849 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3850 // If the page doesn't exist but is a known system message, default
3851 // message content will be displayed, same for language subpages
3852 return $this->getDefaultMessageText() !== false;
3855 return false;
3859 * Get the default message text or false if the message doesn't exist
3861 * @return String or false
3863 public function getDefaultMessageText() {
3864 global $wgContLang;
3866 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3867 return false;
3870 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3871 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3873 if ( $message->exists() ) {
3874 return $message->plain();
3875 } else {
3876 return false;
3881 * Is this in a namespace that allows actual pages?
3883 * @return Bool
3884 * @internal note -- uses hardcoded namespace index instead of constants
3886 public function canExist() {
3887 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3891 * Update page_touched timestamps and send squid purge messages for
3892 * pages linking to this title. May be sent to the job queue depending
3893 * on the number of links. Typically called on create and delete.
3895 public function touchLinks() {
3896 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3897 $u->doUpdate();
3899 if ( $this->getNamespace() == NS_CATEGORY ) {
3900 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3901 $u->doUpdate();
3906 * Get the last touched timestamp
3908 * @param $db DatabaseBase: optional db
3909 * @return String last-touched timestamp
3911 public function getTouched( $db = null ) {
3912 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3913 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3914 return $touched;
3918 * Get the timestamp when this page was updated since the user last saw it.
3920 * @param $user User
3921 * @return String|Null
3923 public function getNotificationTimestamp( $user = null ) {
3924 global $wgUser, $wgShowUpdatedMarker;
3925 // Assume current user if none given
3926 if ( !$user ) {
3927 $user = $wgUser;
3929 // Check cache first
3930 $uid = $user->getId();
3931 // avoid isset here, as it'll return false for null entries
3932 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3933 return $this->mNotificationTimestamp[$uid];
3935 if ( !$uid || !$wgShowUpdatedMarker ) {
3936 return $this->mNotificationTimestamp[$uid] = false;
3938 // Don't cache too much!
3939 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3940 $this->mNotificationTimestamp = array();
3942 $dbr = wfGetDB( DB_SLAVE );
3943 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3944 'wl_notificationtimestamp',
3945 array( 'wl_namespace' => $this->getNamespace(),
3946 'wl_title' => $this->getDBkey(),
3947 'wl_user' => $user->getId()
3949 __METHOD__
3951 return $this->mNotificationTimestamp[$uid];
3955 * Get the trackback URL for this page
3957 * @return String Trackback URL
3959 public function trackbackURL() {
3960 global $wgScriptPath, $wgServer, $wgScriptExtension;
3962 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3963 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3967 * Get the trackback RDF for this page
3969 * @return String Trackback RDF
3971 public function trackbackRDF() {
3972 $url = htmlspecialchars( $this->getFullURL() );
3973 $title = htmlspecialchars( $this->getText() );
3974 $tburl = $this->trackbackURL();
3976 // Autodiscovery RDF is placed in comments so HTML validator
3977 // won't barf. This is a rather icky workaround, but seems
3978 // frequently used by this kind of RDF thingy.
3980 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3981 return "<!--
3982 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3983 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3984 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3985 <rdf:Description
3986 rdf:about=\"$url\"
3987 dc:identifier=\"$url\"
3988 dc:title=\"$title\"
3989 trackback:ping=\"$tburl\" />
3990 </rdf:RDF>
3991 -->";
3995 * Generate strings used for xml 'id' names in monobook tabs
3997 * @param $prepend string defaults to 'nstab-'
3998 * @return String XML 'id' name
4000 public function getNamespaceKey( $prepend = 'nstab-' ) {
4001 global $wgContLang;
4002 // Gets the subject namespace if this title
4003 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4004 // Checks if cononical namespace name exists for namespace
4005 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4006 // Uses canonical namespace name
4007 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4008 } else {
4009 // Uses text of namespace
4010 $namespaceKey = $this->getSubjectNsText();
4012 // Makes namespace key lowercase
4013 $namespaceKey = $wgContLang->lc( $namespaceKey );
4014 // Uses main
4015 if ( $namespaceKey == '' ) {
4016 $namespaceKey = 'main';
4018 // Changes file to image for backwards compatibility
4019 if ( $namespaceKey == 'file' ) {
4020 $namespaceKey = 'image';
4022 return $prepend . $namespaceKey;
4026 * Returns true if this is a special page.
4028 * @return boolean
4030 public function isSpecialPage() {
4031 return $this->getNamespace() == NS_SPECIAL;
4035 * Returns true if this title resolves to the named special page
4037 * @param $name String The special page name
4038 * @return boolean
4040 public function isSpecial( $name ) {
4041 if ( $this->getNamespace() == NS_SPECIAL ) {
4042 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
4043 if ( $name == $thisName ) {
4044 return true;
4047 return false;
4051 * If the Title refers to a special page alias which is not the local default, resolve
4052 * the alias, and localise the name as necessary. Otherwise, return $this
4054 * @return Title
4056 public function fixSpecialName() {
4057 if ( $this->getNamespace() == NS_SPECIAL ) {
4058 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4059 if ( $canonicalName ) {
4060 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4061 if ( $localName != $this->mDbkeyform ) {
4062 return Title::makeTitle( NS_SPECIAL, $localName );
4066 return $this;
4070 * Is this Title in a namespace which contains content?
4071 * In other words, is this a content page, for the purposes of calculating
4072 * statistics, etc?
4074 * @return Boolean
4076 public function isContentPage() {
4077 return MWNamespace::isContent( $this->getNamespace() );
4081 * Get all extant redirects to this Title
4083 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4084 * @return Array of Title redirects to this title
4086 public function getRedirectsHere( $ns = null ) {
4087 $redirs = array();
4089 $dbr = wfGetDB( DB_SLAVE );
4090 $where = array(
4091 'rd_namespace' => $this->getNamespace(),
4092 'rd_title' => $this->getDBkey(),
4093 'rd_from = page_id'
4095 if ( !is_null( $ns ) ) {
4096 $where['page_namespace'] = $ns;
4099 $res = $dbr->select(
4100 array( 'redirect', 'page' ),
4101 array( 'page_namespace', 'page_title' ),
4102 $where,
4103 __METHOD__
4106 foreach ( $res as $row ) {
4107 $redirs[] = self::newFromRow( $row );
4109 return $redirs;
4113 * Check if this Title is a valid redirect target
4115 * @return Bool
4117 public function isValidRedirectTarget() {
4118 global $wgInvalidRedirectTargets;
4120 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4121 if ( $this->isSpecial( 'Userlogout' ) ) {
4122 return false;
4125 foreach ( $wgInvalidRedirectTargets as $target ) {
4126 if ( $this->isSpecial( $target ) ) {
4127 return false;
4131 return true;
4135 * Get a backlink cache object
4137 * @return object BacklinkCache
4139 function getBacklinkCache() {
4140 if ( is_null( $this->mBacklinkCache ) ) {
4141 $this->mBacklinkCache = new BacklinkCache( $this );
4143 return $this->mBacklinkCache;
4147 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4149 * @return Boolean
4151 public function canUseNoindex() {
4152 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4154 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4155 ? $wgContentNamespaces
4156 : $wgExemptFromUserRobotsControl;
4158 return !in_array( $this->mNamespace, $bannedNamespaces );
4163 * Returns restriction types for the current Title
4165 * @return array applicable restriction types
4167 public function getRestrictionTypes() {
4168 if ( $this->getNamespace() == NS_SPECIAL ) {
4169 return array();
4172 $types = self::getFilteredRestrictionTypes( $this->exists() );
4174 if ( $this->getNamespace() != NS_FILE ) {
4175 # Remove the upload restriction for non-file titles
4176 $types = array_diff( $types, array( 'upload' ) );
4179 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4181 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4182 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4184 return $types;
4187 * Get a filtered list of all restriction types supported by this wiki.
4188 * @param bool $exists True to get all restriction types that apply to
4189 * titles that do exist, False for all restriction types that apply to
4190 * titles that do not exist
4191 * @return array
4193 public static function getFilteredRestrictionTypes( $exists = true ) {
4194 global $wgRestrictionTypes;
4195 $types = $wgRestrictionTypes;
4196 if ( $exists ) {
4197 # Remove the create restriction for existing titles
4198 $types = array_diff( $types, array( 'create' ) );
4199 } else {
4200 # Only the create and upload restrictions apply to non-existing titles
4201 $types = array_intersect( $types, array( 'create', 'upload' ) );
4203 return $types;
4207 * Returns the raw sort key to be used for categories, with the specified
4208 * prefix. This will be fed to Collation::getSortKey() to get a
4209 * binary sortkey that can be used for actual sorting.
4211 * @param $prefix string The prefix to be used, specified using
4212 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4213 * prefix.
4214 * @return string
4216 public function getCategorySortkey( $prefix = '' ) {
4217 $unprefixed = $this->getText();
4218 if ( $prefix !== '' ) {
4219 # Separate with a line feed, so the unprefixed part is only used as
4220 # a tiebreaker when two pages have the exact same prefix.
4221 # In UCA, tab is the only character that can sort above LF
4222 # so we strip both of them from the original prefix.
4223 $prefix = strtr( $prefix, "\n\t", ' ' );
4224 return "$prefix\n$unprefixed";
4226 return $unprefixed;
4231 * A BadTitle is generated in MediaWiki::parseTitle() if the title is invalid; the
4232 * software uses this to display an error page. Internally it's basically a Title
4233 * for an empty special page
4235 class BadTitle extends Title {
4236 public function __construct(){
4237 $this->mTextform = '';
4238 $this->mUrlform = '';
4239 $this->mDbkeyform = '';
4240 $this->mNamespace = NS_SPECIAL; // Stops talk page link, etc, being shown
4243 public function exists(){
4244 return false;
4247 public function getPrefixedText(){
4248 return '';
4251 public function getText(){
4252 return '';
4255 public function getPrefixedURL(){
4256 return '';
4259 public function getPrefixedDBKey(){
4260 return '';