Followup r81034, remove the global statements
[mediawiki.git] / includes / Title.php
blob421be43fbfece3482254e34bee2594d882d0d10b
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
7 /**
8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname( __FILE__ ) . '/normal/UtfNormal.php' );
16 /**
17 * @deprecated This used to be a define, but was moved to
18 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
20 define( 'GAID_FOR_UPDATE', Title::GAID_FOR_UPDATE );
22 /**
23 * Represents a title within MediaWiki.
24 * Optionally may contain an interwiki designation or namespace.
25 * @note This class can fetch various kinds of data from the database;
26 * however, it does so inefficiently.
28 * @internal documentation reviewed 15 Mar 2010
30 class Title {
31 /** @name Static cache variables */
32 // @{
33 static private $titleCache = array();
34 // @}
36 /**
37 * Title::newFromText maintains a cache to avoid expensive re-normalization of
38 * commonly used titles. On a batch operation this can become a memory leak
39 * if not bounded. After hitting this many titles reset the cache.
41 const CACHE_MAX = 1000;
43 /**
44 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
45 * to use the master DB
47 const GAID_FOR_UPDATE = 1;
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
55 // @{
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
67 var $mOldRestrictions = false;
68 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
69 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
70 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
71 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
72 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
73 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
74 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
75 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
76 # Don't change the following default, NS_MAIN is hardcoded in several
77 # places. See bug 696.
78 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
79 # Zero except in {{transclusion}} tags
80 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
81 var $mLength = -1; // /< The page length, 0 for special pages
82 var $mRedirect = null; // /< Is the article at this title a redirect?
83 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
84 var $mBacklinkCache = null; // /< Cache of links to this title
85 // @}
88 /**
89 * Constructor
90 * @private
92 /* private */ function __construct() { }
94 /**
95 * Create a new Title from a prefixed DB key
97 * @param $key String The database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return Title the new object, or NULL on an error
102 public static function newFromDBkey( $key ) {
103 $t = new Title();
104 $t->mDbkeyform = $key;
105 if ( $t->secureAndSplit() ) {
106 return $t;
107 } else {
108 return null;
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String The link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace int The namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
121 * makeTitleSafe().
122 * @return Title The new object, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
133 * caching them.
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
138 return Title::$titleCache[$text];
142 * Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
144 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
146 $t = new Title();
147 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
148 $t->mDefaultNamespace = $defaultNamespace;
150 static $cachedcount = 0 ;
151 if ( $t->secureAndSplit() ) {
152 if ( $defaultNamespace == NS_MAIN ) {
153 if ( $cachedcount >= self::CACHE_MAX ) {
154 # Avoid memory leaks on mass operations...
155 Title::$titleCache = array();
156 $cachedcount = 0;
158 $cachedcount++;
159 Title::$titleCache[$text] =& $t;
161 return $t;
162 } else {
163 $ret = null;
164 return $ret;
169 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
171 * Example of wrong and broken code:
172 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
174 * Example of right code:
175 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
177 * Create a new Title from URL-encoded text. Ensures that
178 * the given title's length does not exceed the maximum.
180 * @param $url String the title, as might be taken from a URL
181 * @return Title the new object, or NULL on an error
183 public static function newFromURL( $url ) {
184 global $wgLegalTitleChars;
185 $t = new Title();
187 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
188 # but some URLs used it as a space replacement and they still come
189 # from some external search tools.
190 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
191 $url = str_replace( '+', ' ', $url );
194 $t->mDbkeyform = str_replace( ' ', '_', $url );
195 if ( $t->secureAndSplit() ) {
196 return $t;
197 } else {
198 return null;
203 * Create a new Title from an article ID
205 * @param $id Int the page_id corresponding to the Title to create
206 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
207 * @return Title the new object, or NULL on an error
209 public static function newFromID( $id, $flags = 0 ) {
210 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
211 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
212 if ( $row !== false ) {
213 $title = Title::newFromRow( $row );
214 } else {
215 $title = null;
217 return $title;
221 * Make an array of titles from an array of IDs
223 * @param $ids Array of Int Array of IDs
224 * @return Array of Titles
226 public static function newFromIDs( $ids ) {
227 if ( !count( $ids ) ) {
228 return array();
230 $dbr = wfGetDB( DB_SLAVE );
232 $res = $dbr->select(
233 'page',
234 array(
235 'page_namespace', 'page_title', 'page_id',
236 'page_len', 'page_is_redirect', 'page_latest',
238 array( 'page_id' => $ids ),
239 __METHOD__
242 $titles = array();
243 foreach ( $res as $row ) {
244 $titles[] = Title::newFromRow( $row );
246 return $titles;
250 * Make a Title object from a DB row
252 * @param $row Object database row (needs at least page_title,page_namespace)
253 * @return Title corresponding Title
255 public static function newFromRow( $row ) {
256 $t = self::makeTitle( $row->page_namespace, $row->page_title );
258 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
259 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
260 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
261 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
263 return $t;
267 * Create a new Title from a namespace index and a DB key.
268 * It's assumed that $ns and $title are *valid*, for instance when
269 * they came directly from the database or a special page name.
270 * For convenience, spaces are converted to underscores so that
271 * eg user_text fields can be used directly.
273 * @param $ns Int the namespace of the article
274 * @param $title String the unprefixed database key form
275 * @param $fragment String The link fragment (after the "#")
276 * @param $interwiki String The interwiki prefix
277 * @return Title the new object
279 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
280 $t = new Title();
281 $t->mInterwiki = $interwiki;
282 $t->mFragment = $fragment;
283 $t->mNamespace = $ns = intval( $ns );
284 $t->mDbkeyform = str_replace( ' ', '_', $title );
285 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
286 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
287 $t->mTextform = str_replace( '_', ' ', $title );
288 return $t;
292 * Create a new Title from a namespace index and a DB key.
293 * The parameters will be checked for validity, which is a bit slower
294 * than makeTitle() but safer for user-provided data.
296 * @param $ns Int the namespace of the article
297 * @param $title String the database key form
298 * @param $fragment String The link fragment (after the "#")
299 * @param $interwiki String The interwiki prefix
300 * @return Title the new object, or NULL on an error
302 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
303 $t = new Title();
304 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
305 if ( $t->secureAndSplit() ) {
306 return $t;
307 } else {
308 return null;
313 * Create a new Title for the Main Page
315 * @return Title the new object
317 public static function newMainPage() {
318 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
319 // Don't give fatal errors if the message is broken
320 if ( !$title ) {
321 $title = Title::newFromText( 'Main Page' );
323 return $title;
327 * Extract a redirect destination from a string and return the
328 * Title, or null if the text doesn't contain a valid redirect
329 * This will only return the very next target, useful for
330 * the redirect table and other checks that don't need full recursion
332 * @param $text String: Text with possible redirect
333 * @return Title: The corresponding Title
335 public static function newFromRedirect( $text ) {
336 return self::newFromRedirectInternal( $text );
340 * Extract a redirect destination from a string and return the
341 * Title, or null if the text doesn't contain a valid redirect
342 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
343 * in order to provide (hopefully) the Title of the final destination instead of another redirect
345 * @param $text String Text with possible redirect
346 * @return Title The corresponding Title
348 public static function newFromRedirectRecurse( $text ) {
349 $titles = self::newFromRedirectArray( $text );
350 return $titles ? array_pop( $titles ) : null;
354 * Extract a redirect destination from a string and return an
355 * array of Titles, or null if the text doesn't contain a valid redirect
356 * The last element in the array is the final destination after all redirects
357 * have been resolved (up to $wgMaxRedirects times)
359 * @param $text String Text with possible redirect
360 * @return Array of Titles, with the destination last
362 public static function newFromRedirectArray( $text ) {
363 global $wgMaxRedirects;
364 // are redirects disabled?
365 if ( $wgMaxRedirects < 1 ) {
366 return null;
368 $title = self::newFromRedirectInternal( $text );
369 if ( is_null( $title ) ) {
370 return null;
372 // recursive check to follow double redirects
373 $recurse = $wgMaxRedirects;
374 $titles = array( $title );
375 while ( --$recurse > 0 ) {
376 if ( $title->isRedirect() ) {
377 $article = new Article( $title, 0 );
378 $newtitle = $article->getRedirectTarget();
379 } else {
380 break;
382 // Redirects to some special pages are not permitted
383 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
384 // the new title passes the checks, so make that our current title so that further recursion can be checked
385 $title = $newtitle;
386 $titles[] = $newtitle;
387 } else {
388 break;
391 return $titles;
395 * Really extract the redirect destination
396 * Do not call this function directly, use one of the newFromRedirect* functions above
398 * @param $text String Text with possible redirect
399 * @return Title The corresponding Title
401 protected static function newFromRedirectInternal( $text ) {
402 $redir = MagicWord::get( 'redirect' );
403 $text = trim( $text );
404 if ( $redir->matchStartAndRemove( $text ) ) {
405 // Extract the first link and see if it's usable
406 // Ensure that it really does come directly after #REDIRECT
407 // Some older redirects included a colon, so don't freak about that!
408 $m = array();
409 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
410 // Strip preceding colon used to "escape" categories, etc.
411 // and URL-decode links
412 if ( strpos( $m[1], '%' ) !== false ) {
413 // Match behavior of inline link parsing here;
414 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
416 $title = Title::newFromText( $m[1] );
417 // If the title is a redirect to bad special pages or is invalid, return null
418 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
419 return null;
421 return $title;
424 return null;
427 # ----------------------------------------------------------------------------
428 # Static functions
429 # ----------------------------------------------------------------------------
432 * Get the prefixed DB key associated with an ID
434 * @param $id Int the page_id of the article
435 * @return Title an object representing the article, or NULL
436 * if no such article was found
438 public static function nameOf( $id ) {
439 $dbr = wfGetDB( DB_SLAVE );
441 $s = $dbr->selectRow(
442 'page',
443 array( 'page_namespace', 'page_title' ),
444 array( 'page_id' => $id ),
445 __METHOD__
447 if ( $s === false ) {
448 return null;
451 $n = self::makeName( $s->page_namespace, $s->page_title );
452 return $n;
456 * Get a regex character class describing the legal characters in a link
458 * @return String the list of characters, not delimited
460 public static function legalChars() {
461 global $wgLegalTitleChars;
462 return $wgLegalTitleChars;
466 * Get a string representation of a title suitable for
467 * including in a search index
469 * @param $ns Int a namespace index
470 * @param $title String text-form main part
471 * @return String a stripped-down title string ready for the
472 * search index
474 public static function indexTitle( $ns, $title ) {
475 global $wgContLang;
477 $lc = SearchEngine::legalSearchChars() . '&#;';
478 $t = $wgContLang->normalizeForSearch( $title );
479 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
480 $t = $wgContLang->lc( $t );
482 # Handle 's, s'
483 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
484 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
486 $t = preg_replace( "/\\s+/", ' ', $t );
488 if ( $ns == NS_FILE ) {
489 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
491 return trim( $t );
495 * Make a prefixed DB key from a DB key and a namespace index
497 * @param $ns Int numerical representation of the namespace
498 * @param $title String the DB key form the title
499 * @param $fragment String The link fragment (after the "#")
500 * @param $interwiki String The interwiki prefix
501 * @return String the prefixed form of the title
503 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
504 global $wgContLang;
506 $namespace = $wgContLang->getNsText( $ns );
507 $name = $namespace == '' ? $title : "$namespace:$title";
508 if ( strval( $interwiki ) != '' ) {
509 $name = "$interwiki:$name";
511 if ( strval( $fragment ) != '' ) {
512 $name .= '#' . $fragment;
514 return $name;
518 * Determine whether the object refers to a page within
519 * this project.
521 * @return Bool TRUE if this is an in-project interwiki link
522 * or a wikilink, FALSE otherwise
524 public function isLocal() {
525 if ( $this->mInterwiki != '' ) {
526 return Interwiki::fetch( $this->mInterwiki )->isLocal();
527 } else {
528 return true;
533 * Determine whether the object refers to a page within
534 * this project and is transcludable.
536 * @return Bool TRUE if this is transcludable
538 public function isTrans() {
539 if ( $this->mInterwiki == '' ) {
540 return false;
543 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
547 * Returns the DB name of the distant wiki
548 * which owns the object.
550 * @return String the DB name
552 public function getTransWikiID() {
553 if ( $this->mInterwiki == '' ) {
554 return false;
557 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
561 * Escape a text fragment, say from a link, for a URL
563 * @param $fragment string containing a URL or link fragment (after the "#")
564 * @return String: escaped string
566 static function escapeFragmentForURL( $fragment ) {
567 # Note that we don't urlencode the fragment. urlencoded Unicode
568 # fragments appear not to work in IE (at least up to 7) or in at least
569 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
570 # to care if they aren't encoded.
571 return Sanitizer::escapeId( $fragment, 'noninitial' );
574 # ----------------------------------------------------------------------------
575 # Other stuff
576 # ----------------------------------------------------------------------------
578 /** Simple accessors */
580 * Get the text form (spaces not underscores) of the main part
582 * @return String Main part of the title
584 public function getText() { return $this->mTextform; }
587 * Get the URL-encoded form of the main part
589 * @return String Main part of the title, URL-encoded
591 public function getPartialURL() { return $this->mUrlform; }
594 * Get the main part with underscores
596 * @return String: Main part of the title, with underscores
598 public function getDBkey() { return $this->mDbkeyform; }
601 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
603 * @return Integer: Namespace index
605 public function getNamespace() { return $this->mNamespace; }
608 * Get the namespace text
610 * @return String: Namespace text
612 public function getNsText() {
613 global $wgContLang;
615 if ( $this->mInterwiki != '' ) {
616 // This probably shouldn't even happen. ohh man, oh yuck.
617 // But for interwiki transclusion it sometimes does.
618 // Shit. Shit shit shit.
620 // Use the canonical namespaces if possible to try to
621 // resolve a foreign namespace.
622 if ( MWNamespace::exists( $this->mNamespace ) ) {
623 return MWNamespace::getCanonicalName( $this->mNamespace );
626 return $wgContLang->getNsText( $this->mNamespace );
630 * Get the DB key with the initial letter case as specified by the user
632 * @return String DB key
634 function getUserCaseDBKey() {
635 return $this->mUserCaseDBKey;
639 * Get the namespace text of the subject (rather than talk) page
641 * @return String Namespace text
643 public function getSubjectNsText() {
644 global $wgContLang;
645 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
649 * Get the namespace text of the talk page
651 * @return String Namespace text
653 public function getTalkNsText() {
654 global $wgContLang;
655 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
659 * Could this title have a corresponding talk page?
661 * @return Bool TRUE or FALSE
663 public function canTalk() {
664 return( MWNamespace::canTalk( $this->mNamespace ) );
668 * Get the interwiki prefix (or null string)
670 * @return String Interwiki prefix
672 public function getInterwiki() { return $this->mInterwiki; }
675 * Get the Title fragment (i.e.\ the bit after the #) in text form
677 * @return String Title fragment
679 public function getFragment() { return $this->mFragment; }
682 * Get the fragment in URL form, including the "#" character if there is one
683 * @return String Fragment in URL form
685 public function getFragmentForURL() {
686 if ( $this->mFragment == '' ) {
687 return '';
688 } else {
689 return '#' . Title::escapeFragmentForURL( $this->mFragment );
694 * Get the default namespace index, for when there is no namespace
696 * @return Int Default namespace index
698 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
701 * Get title for search index
703 * @return String a stripped-down title string ready for the
704 * search index
706 public function getIndexTitle() {
707 return Title::indexTitle( $this->mNamespace, $this->mTextform );
711 * Get the prefixed database key form
713 * @return String the prefixed title, with underscores and
714 * any interwiki and namespace prefixes
716 public function getPrefixedDBkey() {
717 $s = $this->prefix( $this->mDbkeyform );
718 $s = str_replace( ' ', '_', $s );
719 return $s;
723 * Get the prefixed title with spaces.
724 * This is the form usually used for display
726 * @return String the prefixed title, with spaces
728 public function getPrefixedText() {
729 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
730 $s = $this->prefix( $this->mTextform );
731 $s = str_replace( '_', ' ', $s );
732 $this->mPrefixedText = $s;
734 return $this->mPrefixedText;
738 * Get the prefixed title with spaces, plus any fragment
739 * (part beginning with '#')
741 * @return String the prefixed title, with spaces and
742 * the fragment, including '#'
744 public function getFullText() {
745 $text = $this->getPrefixedText();
746 if ( $this->mFragment != '' ) {
747 $text .= '#' . $this->mFragment;
749 return $text;
753 * Get the base name, i.e. the leftmost parts before the /
755 * @return String Base name
757 public function getBaseText() {
758 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
759 return $this->getText();
762 $parts = explode( '/', $this->getText() );
763 # Don't discard the real title if there's no subpage involved
764 if ( count( $parts ) > 1 ) {
765 unset( $parts[count( $parts ) - 1] );
767 return implode( '/', $parts );
771 * Get the lowest-level subpage name, i.e. the rightmost part after /
773 * @return String Subpage name
775 public function getSubpageText() {
776 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
777 return( $this->mTextform );
779 $parts = explode( '/', $this->mTextform );
780 return( $parts[count( $parts ) - 1] );
784 * Get a URL-encoded form of the subpage text
786 * @return String URL-encoded subpage name
788 public function getSubpageUrlForm() {
789 $text = $this->getSubpageText();
790 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
791 return( $text );
795 * Get a URL-encoded title (not an actual URL) including interwiki
797 * @return String the URL-encoded form
799 public function getPrefixedURL() {
800 $s = $this->prefix( $this->mDbkeyform );
801 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
802 return $s;
806 * Get a real URL referring to this title, with interwiki link and
807 * fragment
809 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
810 * links. Can be specified as an associative array as well, e.g.,
811 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
812 * @param $variant String language variant of url (for sr, zh..)
813 * @return String the URL
815 public function getFullURL( $query = '', $variant = false ) {
816 global $wgServer, $wgRequest;
818 if ( is_array( $query ) ) {
819 $query = wfArrayToCGI( $query );
822 $interwiki = Interwiki::fetch( $this->mInterwiki );
823 if ( !$interwiki ) {
824 $url = $this->getLocalURL( $query, $variant );
826 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
827 // Correct fix would be to move the prepending elsewhere.
828 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
829 $url = $wgServer . $url;
831 } else {
832 $baseUrl = $interwiki->getURL();
834 $namespace = wfUrlencode( $this->getNsText() );
835 if ( $namespace != '' ) {
836 # Can this actually happen? Interwikis shouldn't be parsed.
837 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
838 $namespace .= ':';
840 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
841 $url = wfAppendQuery( $url, $query );
844 # Finally, add the fragment.
845 $url .= $this->getFragmentForURL();
847 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
848 return $url;
852 * Get a URL with no fragment or server name. If this page is generated
853 * with action=render, $wgServer is prepended.
855 * @param $query Mixed: an optional query string; if not specified,
856 * $wgArticlePath will be used. Can be specified as an associative array
857 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
858 * URL-escaped).
859 * @param $variant String language variant of url (for sr, zh..)
860 * @return String the URL
862 public function getLocalURL( $query = '', $variant = false ) {
863 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
864 global $wgVariantArticlePath, $wgContLang;
866 if ( is_array( $query ) ) {
867 $query = wfArrayToCGI( $query );
870 if ( $this->isExternal() ) {
871 $url = $this->getFullURL();
872 if ( $query ) {
873 // This is currently only used for edit section links in the
874 // context of interwiki transclusion. In theory we should
875 // append the query to the end of any existing query string,
876 // but interwiki transclusion is already broken in that case.
877 $url .= "?$query";
879 } else {
880 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
881 if ( $query == '' ) {
882 if ( $variant != false && $wgContLang->hasVariants() ) {
883 if ( !$wgVariantArticlePath ) {
884 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
885 } else {
886 $variantArticlePath = $wgVariantArticlePath;
888 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
889 $url = str_replace( '$1', $dbkey, $url );
890 } else {
891 $url = str_replace( '$1', $dbkey, $wgArticlePath );
893 } else {
894 global $wgActionPaths;
895 $url = false;
896 $matches = array();
897 if ( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
900 $action = urldecode( $matches[2] );
901 if ( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if ( isset( $matches[4] ) ) {
904 $query .= $matches[4];
906 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
907 if ( $query != '' ) {
908 $url = wfAppendQuery( $url, $query );
912 if ( $url === false ) {
913 if ( $query == '-' ) {
914 $query = '';
916 $url = "{$wgScript}?title={$dbkey}&{$query}";
920 // FIXME: this causes breakage in various places when we
921 // actually expected a local URL and end up with dupe prefixes.
922 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
923 $url = $wgServer . $url;
926 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
927 return $url;
931 * Get a URL that's the simplest URL that will be valid to link, locally,
932 * to the current Title. It includes the fragment, but does not include
933 * the server unless action=render is used (or the link is external). If
934 * there's a fragment but the prefixed text is empty, we just return a link
935 * to the fragment.
937 * The result obviously should not be URL-escaped, but does need to be
938 * HTML-escaped if it's being output in HTML.
940 * @param $query Array of Strings An associative array of key => value pairs for the
941 * query string. Keys and values will be escaped.
942 * @param $variant String Language variant of URL (for sr, zh..). Ignored
943 * for external links. Default is "false" (same variant as current page,
944 * for anonymous users).
945 * @return String the URL
947 public function getLinkUrl( $query = array(), $variant = false ) {
948 wfProfileIn( __METHOD__ );
949 if ( $this->isExternal() ) {
950 $ret = $this->getFullURL( $query );
951 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
952 $ret = $this->getFragmentForURL();
953 } else {
954 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
956 wfProfileOut( __METHOD__ );
957 return $ret;
961 * Get an HTML-escaped version of the URL form, suitable for
962 * using in a link, without a server name or fragment
964 * @param $query String an optional query string
965 * @return String the URL
967 public function escapeLocalURL( $query = '' ) {
968 return htmlspecialchars( $this->getLocalURL( $query ) );
972 * Get an HTML-escaped version of the URL form, suitable for
973 * using in a link, including the server name and fragment
975 * @param $query String an optional query string
976 * @return String the URL
978 public function escapeFullURL( $query = '' ) {
979 return htmlspecialchars( $this->getFullURL( $query ) );
983 * Get the URL form for an internal link.
984 * - Used in various Squid-related code, in case we have a different
985 * internal hostname for the server from the exposed one.
987 * @param $query String an optional query string
988 * @param $variant String language variant of url (for sr, zh..)
989 * @return String the URL
991 public function getInternalURL( $query = '', $variant = false ) {
992 global $wgInternalServer;
993 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
994 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
995 return $url;
999 * Get the edit URL for this Title
1001 * @return String the URL, or a null string if this is an
1002 * interwiki link
1004 public function getEditURL() {
1005 if ( $this->mInterwiki != '' ) {
1006 return '';
1008 $s = $this->getLocalURL( 'action=edit' );
1010 return $s;
1014 * Get the HTML-escaped displayable text form.
1015 * Used for the title field in <a> tags.
1017 * @return String the text, including any prefixes
1019 public function getEscapedText() {
1020 return htmlspecialchars( $this->getPrefixedText() );
1024 * Is this Title interwiki?
1026 * @return Bool
1028 public function isExternal() {
1029 return ( $this->mInterwiki != '' );
1033 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1035 * @param $action String Action to check (default: edit)
1036 * @return Bool
1038 public function isSemiProtected( $action = 'edit' ) {
1039 if ( $this->exists() ) {
1040 $restrictions = $this->getRestrictions( $action );
1041 if ( count( $restrictions ) > 0 ) {
1042 foreach ( $restrictions as $restriction ) {
1043 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1044 return false;
1047 } else {
1048 # Not protected
1049 return false;
1051 return true;
1052 } else {
1053 # If it doesn't exist, it can't be protected
1054 return false;
1059 * Does the title correspond to a protected article?
1061 * @param $action String the action the page is protected from,
1062 * by default checks all actions.
1063 * @return Bool
1065 public function isProtected( $action = '' ) {
1066 global $wgRestrictionLevels;
1068 $restrictionTypes = $this->getRestrictionTypes();
1070 # Special pages have inherent protection
1071 if( $this->getNamespace() == NS_SPECIAL ) {
1072 return true;
1075 # Check regular protection levels
1076 foreach ( $restrictionTypes as $type ) {
1077 if ( $action == $type || $action == '' ) {
1078 $r = $this->getRestrictions( $type );
1079 foreach ( $wgRestrictionLevels as $level ) {
1080 if ( in_array( $level, $r ) && $level != '' ) {
1081 return true;
1087 return false;
1091 * Is this a conversion table for the LanguageConverter?
1093 * @return Bool
1095 public function isConversionTable() {
1097 $this->getNamespace() == NS_MEDIAWIKI &&
1098 strpos( $this->getText(), 'Conversiontable' ) !== false
1101 return true;
1104 return false;
1108 * Is $wgUser watching this page?
1110 * @return Bool
1112 public function userIsWatching() {
1113 global $wgUser;
1115 if ( is_null( $this->mWatched ) ) {
1116 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1117 $this->mWatched = false;
1118 } else {
1119 $this->mWatched = $wgUser->isWatched( $this );
1122 return $this->mWatched;
1126 * Can $wgUser perform $action on this page?
1127 * This skips potentially expensive cascading permission checks
1128 * as well as avoids expensive error formatting
1130 * Suitable for use for nonessential UI controls in common cases, but
1131 * _not_ for functional access control.
1133 * May provide false positives, but should never provide a false negative.
1135 * @param $action String action that permission needs to be checked for
1136 * @return Bool
1138 public function quickUserCan( $action ) {
1139 return $this->userCan( $action, false );
1143 * Determines if $user is unable to edit this page because it has been protected
1144 * by $wgNamespaceProtection.
1146 * @param $user User object, $wgUser will be used if not passed
1147 * @return Bool
1149 public function isNamespaceProtected( User $user = null ) {
1150 global $wgNamespaceProtection;
1152 if ( $user === null ) {
1153 global $wgUser;
1154 $user = $wgUser;
1157 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1158 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1159 if ( $right != '' && !$user->isAllowed( $right ) ) {
1160 return true;
1164 return false;
1168 * Can $wgUser perform $action on this page?
1170 * @param $action String action that permission needs to be checked for
1171 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1172 * @return Bool
1174 public function userCan( $action, $doExpensiveQueries = true ) {
1175 global $wgUser;
1176 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1180 * Can $user perform $action on this page?
1182 * FIXME: This *does not* check throttles (User::pingLimiter()).
1184 * @param $action String action that permission needs to be checked for
1185 * @param $user User to check
1186 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1187 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1188 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1190 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1191 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1193 // Remove the errors being ignored.
1194 foreach ( $errors as $index => $error ) {
1195 $error_key = is_array( $error ) ? $error[0] : $error;
1197 if ( in_array( $error_key, $ignoreErrors ) ) {
1198 unset( $errors[$index] );
1202 return $errors;
1206 * Permissions checks that fail most often, and which are easiest to test.
1208 * @param $action String the action to check
1209 * @param $user User user to check
1210 * @param $errors Array list of current errors
1211 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1212 * @param $short Boolean short circuit on first error
1214 * @return Array list of errors
1216 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1217 if ( $action == 'create' ) {
1218 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1219 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1220 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1222 } elseif ( $action == 'move' ) {
1223 if ( !$user->isAllowed( 'move-rootuserpages' )
1224 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1225 // Show user page-specific message only if the user can move other pages
1226 $errors[] = array( 'cant-move-user-page' );
1229 // Check if user is allowed to move files if it's a file
1230 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1231 $errors[] = array( 'movenotallowedfile' );
1234 if ( !$user->isAllowed( 'move' ) ) {
1235 // User can't move anything
1236 global $wgGroupPermissions;
1237 $userCanMove = false;
1238 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1239 $userCanMove = $wgGroupPermissions['user']['move'];
1241 $autoconfirmedCanMove = false;
1242 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1243 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1245 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1246 // custom message if logged-in users without any special rights can move
1247 $errors[] = array( 'movenologintext' );
1248 } else {
1249 $errors[] = array( 'movenotallowed' );
1252 } elseif ( $action == 'move-target' ) {
1253 if ( !$user->isAllowed( 'move' ) ) {
1254 // User can't move anything
1255 $errors[] = array( 'movenotallowed' );
1256 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1257 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1258 // Show user page-specific message only if the user can move other pages
1259 $errors[] = array( 'cant-move-to-user-page' );
1261 } elseif ( !$user->isAllowed( $action ) ) {
1262 // We avoid expensive display logic for quickUserCan's and such
1263 $groups = false;
1264 if ( !$short ) {
1265 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1266 User::getGroupsWithPermission( $action ) );
1269 if ( $groups ) {
1270 global $wgLang;
1271 $return = array(
1272 'badaccess-groups',
1273 $wgLang->commaList( $groups ),
1274 count( $groups )
1276 } else {
1277 $return = array( 'badaccess-group0' );
1279 $errors[] = $return;
1282 return $errors;
1286 * Add the resulting error code to the errors array
1288 * @param $errors Array list of current errors
1289 * @param $result Mixed result of errors
1291 * @return Array list of errors
1293 private function resultToError( $errors, $result ) {
1294 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1295 // A single array representing an error
1296 $errors[] = $result;
1297 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1298 // A nested array representing multiple errors
1299 $errors = array_merge( $errors, $result );
1300 } else if ( $result !== '' && is_string( $result ) ) {
1301 // A string representing a message-id
1302 $errors[] = array( $result );
1303 } else if ( $result === false ) {
1304 // a generic "We don't want them to do that"
1305 $errors[] = array( 'badaccess-group0' );
1307 return $errors;
1311 * Check various permission hooks
1313 * @param $action String the action to check
1314 * @param $user User user to check
1315 * @param $errors Array list of current errors
1316 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1317 * @param $short Boolean short circuit on first error
1319 * @return Array list of errors
1321 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1322 // Use getUserPermissionsErrors instead
1323 $result = '';
1324 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1325 return $result ? array() : array( array( 'badaccess-group0' ) );
1327 // Check getUserPermissionsErrors hook
1328 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1329 $errors = $this->resultToError( $errors, $result );
1331 // Check getUserPermissionsErrorsExpensive hook
1332 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1333 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1334 $errors = $this->resultToError( $errors, $result );
1337 return $errors;
1341 * Check permissions on special pages & namespaces
1343 * @param $action String the action to check
1344 * @param $user User user to check
1345 * @param $errors Array list of current errors
1346 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1347 * @param $short Boolean short circuit on first error
1349 * @return Array list of errors
1351 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1352 # Only 'createaccount' and 'execute' can be performed on
1353 # special pages, which don't actually exist in the DB.
1354 $specialOKActions = array( 'createaccount', 'execute' );
1355 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1356 $errors[] = array( 'ns-specialprotected' );
1359 # Check $wgNamespaceProtection for restricted namespaces
1360 if ( $this->isNamespaceProtected( $user ) ) {
1361 $ns = $this->mNamespace == NS_MAIN ?
1362 wfMsg( 'nstab-main' ) : $this->getNsText();
1363 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1364 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1367 return $errors;
1371 * Check CSS/JS sub-page permissions
1373 * @param $action String the action to check
1374 * @param $user User user to check
1375 * @param $errors Array list of current errors
1376 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1377 * @param $short Boolean short circuit on first error
1379 * @return Array list of errors
1381 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1382 # Protect css/js subpages of user pages
1383 # XXX: this might be better using restrictions
1384 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1385 # and $this->userCanEditJsSubpage() from working
1386 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1387 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1388 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1389 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1390 $errors[] = array( 'customcssjsprotected' );
1391 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1392 $errors[] = array( 'customcssjsprotected' );
1396 return $errors;
1400 * Check against page_restrictions table requirements on this
1401 * page. The user must possess all required rights for this
1402 * action.
1404 * @param $action String the action to check
1405 * @param $user User user to check
1406 * @param $errors Array list of current errors
1407 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1408 * @param $short Boolean short circuit on first error
1410 * @return Array list of errors
1412 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1413 foreach ( $this->getRestrictions( $action ) as $right ) {
1414 // Backwards compatibility, rewrite sysop -> protect
1415 if ( $right == 'sysop' ) {
1416 $right = 'protect';
1418 if ( $right != '' && !$user->isAllowed( $right ) ) {
1419 // Users with 'editprotected' permission can edit protected pages
1420 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1421 // Users with 'editprotected' permission cannot edit protected pages
1422 // with cascading option turned on.
1423 if ( $this->mCascadeRestriction ) {
1424 $errors[] = array( 'protectedpagetext', $right );
1426 } else {
1427 $errors[] = array( 'protectedpagetext', $right );
1432 return $errors;
1436 * Check restrictions on cascading pages.
1438 * @param $action String the action to check
1439 * @param $user User user to check
1440 * @param $errors Array list of current errors
1441 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1442 * @param $short Boolean short circuit on first error
1444 * @return Array list of errors
1446 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1447 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1448 # We /could/ use the protection level on the source page, but it's
1449 # fairly ugly as we have to establish a precedence hierarchy for pages
1450 # included by multiple cascade-protected pages. So just restrict
1451 # it to people with 'protect' permission, as they could remove the
1452 # protection anyway.
1453 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1454 # Cascading protection depends on more than this page...
1455 # Several cascading protected pages may include this page...
1456 # Check each cascading level
1457 # This is only for protection restrictions, not for all actions
1458 if ( isset( $restrictions[$action] ) ) {
1459 foreach ( $restrictions[$action] as $right ) {
1460 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1461 if ( $right != '' && !$user->isAllowed( $right ) ) {
1462 $pages = '';
1463 foreach ( $cascadingSources as $page )
1464 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1465 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1471 return $errors;
1475 * Check action permissions not already checked in checkQuickPermissions
1477 * @param $action String the action to check
1478 * @param $user User user to check
1479 * @param $errors Array list of current errors
1480 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1481 * @param $short Boolean short circuit on first error
1483 * @return Array list of errors
1485 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1486 if ( $action == 'protect' ) {
1487 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1488 // If they can't edit, they shouldn't protect.
1489 $errors[] = array( 'protect-cantedit' );
1491 } elseif ( $action == 'create' ) {
1492 $title_protection = $this->getTitleProtection();
1493 if( $title_protection ) {
1494 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1495 $title_protection['pt_create_perm'] = 'protect'; // B/C
1497 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1498 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1501 } elseif ( $action == 'move' ) {
1502 // Check for immobile pages
1503 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1504 // Specific message for this case
1505 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1506 } elseif ( !$this->isMovable() ) {
1507 // Less specific message for rarer cases
1508 $errors[] = array( 'immobile-page' );
1510 } elseif ( $action == 'move-target' ) {
1511 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1512 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1513 } elseif ( !$this->isMovable() ) {
1514 $errors[] = array( 'immobile-target-page' );
1517 return $errors;
1521 * Check that the user isn't blocked from editting.
1523 * @param $action String the action to check
1524 * @param $user User user to check
1525 * @param $errors Array list of current errors
1526 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1527 * @param $short Boolean short circuit on first error
1529 * @return Array list of errors
1531 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1532 if( $short && count( $errors ) > 0 ) {
1533 return $errors;
1536 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1538 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1539 $errors[] = array( 'confirmedittext' );
1542 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1543 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1544 $block = $user->mBlock;
1546 // This is from OutputPage::blockedPage
1547 // Copied at r23888 by werdna
1549 $id = $user->blockedBy();
1550 $reason = $user->blockedFor();
1551 if ( $reason == '' ) {
1552 $reason = wfMsg( 'blockednoreason' );
1554 $ip = wfGetIP();
1556 if ( is_numeric( $id ) ) {
1557 $name = User::whoIs( $id );
1558 } else {
1559 $name = $id;
1562 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1563 $blockid = $block->mId;
1564 $blockExpiry = $user->mBlock->mExpiry;
1565 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1566 if ( $blockExpiry == 'infinity' ) {
1567 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1568 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1570 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1571 if ( !strpos( $option, ':' ) )
1572 continue;
1574 list( $show, $value ) = explode( ':', $option );
1576 if ( $value == 'infinite' || $value == 'indefinite' ) {
1577 $blockExpiry = $show;
1578 break;
1581 } else {
1582 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1585 $intended = $user->mBlock->mAddress;
1587 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1588 $blockid, $blockExpiry, $intended, $blockTimestamp );
1591 return $errors;
1595 * Can $user perform $action on this page? This is an internal function,
1596 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1597 * checks on wfReadOnly() and blocks)
1599 * @param $action String action that permission needs to be checked for
1600 * @param $user User to check
1601 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1602 * @param $short Bool Set this to true to stop after the first permission error.
1603 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1605 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1606 wfProfileIn( __METHOD__ );
1608 $errors = array();
1609 $checks = array(
1610 'checkQuickPermissions',
1611 'checkPermissionHooks',
1612 'checkSpecialsAndNSPermissions',
1613 'checkCSSandJSPermissions',
1614 'checkPageRestrictions',
1615 'checkCascadingSourcesRestrictions',
1616 'checkActionPermissions',
1617 'checkUserBlock'
1620 while( count( $checks ) > 0 &&
1621 !( $short && count( $errors ) > 0 ) ) {
1622 $method = array_shift( $checks );
1623 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1626 wfProfileOut( __METHOD__ );
1627 return $errors;
1631 * Is this title subject to title protection?
1632 * Title protection is the one applied against creation of such title.
1634 * @return Mixed An associative array representing any existent title
1635 * protection, or false if there's none.
1637 private function getTitleProtection() {
1638 // Can't protect pages in special namespaces
1639 if ( $this->getNamespace() < 0 ) {
1640 return false;
1643 // Can't protect pages that exist.
1644 if ( $this->exists() ) {
1645 return false;
1648 if ( !isset( $this->mTitleProtection ) ) {
1649 $dbr = wfGetDB( DB_SLAVE );
1650 $res = $dbr->select( 'protected_titles', '*',
1651 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1652 __METHOD__ );
1654 // fetchRow returns false if there are no rows.
1655 $this->mTitleProtection = $dbr->fetchRow( $res );
1657 return $this->mTitleProtection;
1661 * Update the title protection status
1663 * @param $create_perm String Permission required for creation
1664 * @param $reason String Reason for protection
1665 * @param $expiry String Expiry timestamp
1666 * @return boolean true
1668 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1669 global $wgUser, $wgContLang;
1671 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1672 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1673 // No change
1674 return true;
1677 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1679 $dbw = wfGetDB( DB_MASTER );
1681 $encodedExpiry = Block::encodeExpiry( $expiry, $dbw );
1683 $expiry_description = '';
1684 if ( $encodedExpiry != 'infinity' ) {
1685 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1686 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1687 } else {
1688 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1691 # Update protection table
1692 if ( $create_perm != '' ) {
1693 $this->mTitleProtection = array(
1694 'pt_namespace' => $namespace,
1695 'pt_title' => $title,
1696 'pt_create_perm' => $create_perm,
1697 'pt_timestamp' => Block::encodeExpiry( wfTimestampNow(), $dbw ),
1698 'pt_expiry' => $encodedExpiry,
1699 'pt_user' => $wgUser->getId(),
1700 'pt_reason' => $reason,
1702 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1703 $this->mTitleProtection, __METHOD__ );
1704 } else {
1705 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1706 'pt_title' => $title ), __METHOD__ );
1707 $this->mTitleProtection = false;
1710 # Update the protection log
1711 if ( $dbw->affectedRows() ) {
1712 $log = new LogPage( 'protect' );
1714 if ( $create_perm ) {
1715 $params = array( "[create=$create_perm] $expiry_description", '' );
1716 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1717 } else {
1718 $log->addEntry( 'unprotect', $this, $reason );
1722 return true;
1726 * Remove any title protection due to page existing
1728 public function deleteTitleProtection() {
1729 $dbw = wfGetDB( DB_MASTER );
1731 $dbw->delete(
1732 'protected_titles',
1733 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1734 __METHOD__
1736 $this->mTitleProtection = false;
1740 * Would anybody with sufficient privileges be able to move this page?
1741 * Some pages just aren't movable.
1743 * @return Bool TRUE or FALSE
1745 public function isMovable() {
1746 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1750 * Can $wgUser read this page?
1752 * @return Bool
1753 * @todo fold these checks into userCan()
1755 public function userCanRead() {
1756 global $wgUser, $wgGroupPermissions;
1758 static $useShortcut = null;
1760 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1761 if ( is_null( $useShortcut ) ) {
1762 global $wgRevokePermissions;
1763 $useShortcut = true;
1764 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1765 # Not a public wiki, so no shortcut
1766 $useShortcut = false;
1767 } elseif ( !empty( $wgRevokePermissions ) ) {
1769 * Iterate through each group with permissions being revoked (key not included since we don't care
1770 * what the group name is), then check if the read permission is being revoked. If it is, then
1771 * we don't use the shortcut below since the user might not be able to read, even though anon
1772 * reading is allowed.
1774 foreach ( $wgRevokePermissions as $perms ) {
1775 if ( !empty( $perms['read'] ) ) {
1776 # We might be removing the read right from the user, so no shortcut
1777 $useShortcut = false;
1778 break;
1784 $result = null;
1785 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1786 if ( $result !== null ) {
1787 return $result;
1790 # Shortcut for public wikis, allows skipping quite a bit of code
1791 if ( $useShortcut ) {
1792 return true;
1795 if ( $wgUser->isAllowed( 'read' ) ) {
1796 return true;
1797 } else {
1798 global $wgWhitelistRead;
1801 * Always grant access to the login page.
1802 * Even anons need to be able to log in.
1804 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1805 return true;
1809 * Bail out if there isn't whitelist
1811 if ( !is_array( $wgWhitelistRead ) ) {
1812 return false;
1816 * Check for explicit whitelisting
1818 $name = $this->getPrefixedText();
1819 $dbName = $this->getPrefixedDBKey();
1820 // Check with and without underscores
1821 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1822 return true;
1825 * Old settings might have the title prefixed with
1826 * a colon for main-namespace pages
1828 if ( $this->getNamespace() == NS_MAIN ) {
1829 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1830 return true;
1835 * If it's a special page, ditch the subpage bit
1836 * and check again
1838 if ( $this->getNamespace() == NS_SPECIAL ) {
1839 $name = $this->getDBkey();
1840 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1841 if ( $name === false ) {
1842 # Invalid special page, but we show standard login required message
1843 return false;
1846 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1847 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1848 return true;
1853 return false;
1857 * Is this the mainpage?
1858 * @note Title::newFromText seams to be sufficiently optimized by the title
1859 * cache that we don't need to over-optimize by doing direct comparisons and
1860 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1861 * ends up reporting something differently than $title->isMainPage();
1863 * @return Bool
1865 public function isMainPage() {
1866 return $this->equals( Title::newMainPage() );
1870 * Is this a talk page of some sort?
1872 * @return Bool
1874 public function isTalkPage() {
1875 return MWNamespace::isTalk( $this->getNamespace() );
1879 * Is this a subpage?
1881 * @return Bool
1883 public function isSubpage() {
1884 return MWNamespace::hasSubpages( $this->mNamespace )
1885 ? strpos( $this->getText(), '/' ) !== false
1886 : false;
1890 * Does this have subpages? (Warning, usually requires an extra DB query.)
1892 * @return Bool
1894 public function hasSubpages() {
1895 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1896 # Duh
1897 return false;
1900 # We dynamically add a member variable for the purpose of this method
1901 # alone to cache the result. There's no point in having it hanging
1902 # around uninitialized in every Title object; therefore we only add it
1903 # if needed and don't declare it statically.
1904 if ( isset( $this->mHasSubpages ) ) {
1905 return $this->mHasSubpages;
1908 $subpages = $this->getSubpages( 1 );
1909 if ( $subpages instanceof TitleArray ) {
1910 return $this->mHasSubpages = (bool)$subpages->count();
1912 return $this->mHasSubpages = false;
1916 * Get all subpages of this page.
1918 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1919 * @return mixed TitleArray, or empty array if this page's namespace
1920 * doesn't allow subpages
1922 public function getSubpages( $limit = -1 ) {
1923 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1924 return array();
1927 $dbr = wfGetDB( DB_SLAVE );
1928 $conds['page_namespace'] = $this->getNamespace();
1929 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1930 $options = array();
1931 if ( $limit > -1 ) {
1932 $options['LIMIT'] = $limit;
1934 return $this->mSubpages = TitleArray::newFromResult(
1935 $dbr->select( 'page',
1936 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1937 $conds,
1938 __METHOD__,
1939 $options
1945 * Could this page contain custom CSS or JavaScript, based
1946 * on the title?
1948 * @return Bool
1950 public function isCssOrJsPage() {
1951 return $this->mNamespace == NS_MEDIAWIKI
1952 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1956 * Is this a .css or .js subpage of a user page?
1957 * @return Bool
1959 public function isCssJsSubpage() {
1960 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1964 * Is this a *valid* .css or .js subpage of a user page?
1966 * @return Bool
1967 * @deprecated
1969 public function isValidCssJsSubpage() {
1970 return $this->isCssJsSubpage();
1974 * Trim down a .css or .js subpage title to get the corresponding skin name
1976 * @return string containing skin name from .css or .js subpage title
1978 public function getSkinFromCssJsSubpage() {
1979 $subpage = explode( '/', $this->mTextform );
1980 $subpage = $subpage[ count( $subpage ) - 1 ];
1981 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1985 * Is this a .css subpage of a user page?
1987 * @return Bool
1989 public function isCssSubpage() {
1990 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1994 * Is this a .js subpage of a user page?
1996 * @return Bool
1998 public function isJsSubpage() {
1999 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
2003 * Protect css subpages of user pages: can $wgUser edit
2004 * this page?
2006 * @return Bool
2007 * @todo XXX: this might be better using restrictions
2009 public function userCanEditCssSubpage() {
2010 global $wgUser;
2011 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
2012 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2016 * Protect js subpages of user pages: can $wgUser edit
2017 * this page?
2019 * @return Bool
2020 * @todo XXX: this might be better using restrictions
2022 public function userCanEditJsSubpage() {
2023 global $wgUser;
2024 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
2025 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2029 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2031 * @return Bool If the page is subject to cascading restrictions.
2033 public function isCascadeProtected() {
2034 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2035 return ( $sources > 0 );
2039 * Cascading protection: Get the source of any cascading restrictions on this page.
2041 * @param $getPages Bool Whether or not to retrieve the actual pages
2042 * that the restrictions have come from.
2043 * @return Mixed Array of the Title
2044 * objects of the pages from which cascading restrictions have come,
2045 * false for none, or true if such restrictions exist, but $getPages was not set.
2046 * The restriction array is an array of each type, each of which contains a
2047 * array of unique groups.
2049 public function getCascadeProtectionSources( $getPages = true ) {
2050 $pagerestrictions = array();
2052 if ( isset( $this->mCascadeSources ) && $getPages ) {
2053 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2054 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2055 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2058 wfProfileIn( __METHOD__ );
2060 $dbr = wfGetDB( DB_SLAVE );
2062 if ( $this->getNamespace() == NS_FILE ) {
2063 $tables = array( 'imagelinks', 'page_restrictions' );
2064 $where_clauses = array(
2065 'il_to' => $this->getDBkey(),
2066 'il_from=pr_page',
2067 'pr_cascade' => 1
2069 } else {
2070 $tables = array( 'templatelinks', 'page_restrictions' );
2071 $where_clauses = array(
2072 'tl_namespace' => $this->getNamespace(),
2073 'tl_title' => $this->getDBkey(),
2074 'tl_from=pr_page',
2075 'pr_cascade' => 1
2079 if ( $getPages ) {
2080 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2081 'pr_expiry', 'pr_type', 'pr_level' );
2082 $where_clauses[] = 'page_id=pr_page';
2083 $tables[] = 'page';
2084 } else {
2085 $cols = array( 'pr_expiry' );
2088 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2090 $sources = $getPages ? array() : false;
2091 $now = wfTimestampNow();
2092 $purgeExpired = false;
2094 foreach ( $res as $row ) {
2095 $expiry = Block::decodeExpiry( $row->pr_expiry );
2096 if ( $expiry > $now ) {
2097 if ( $getPages ) {
2098 $page_id = $row->pr_page;
2099 $page_ns = $row->page_namespace;
2100 $page_title = $row->page_title;
2101 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2102 # Add groups needed for each restriction type if its not already there
2103 # Make sure this restriction type still exists
2105 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2106 $pagerestrictions[$row->pr_type] = array();
2109 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2110 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2111 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2113 } else {
2114 $sources = true;
2116 } else {
2117 // Trigger lazy purge of expired restrictions from the db
2118 $purgeExpired = true;
2121 if ( $purgeExpired ) {
2122 Title::purgeExpiredRestrictions();
2125 wfProfileOut( __METHOD__ );
2127 if ( $getPages ) {
2128 $this->mCascadeSources = $sources;
2129 $this->mCascadingRestrictions = $pagerestrictions;
2130 } else {
2131 $this->mHasCascadingRestrictions = $sources;
2134 return array( $sources, $pagerestrictions );
2138 * Returns cascading restrictions for the current article
2140 * @return Boolean
2142 function areRestrictionsCascading() {
2143 if ( !$this->mRestrictionsLoaded ) {
2144 $this->loadRestrictions();
2147 return $this->mCascadeRestriction;
2151 * Loads a string into mRestrictions array
2153 * @param $res Resource restrictions as an SQL result.
2154 * @param $oldFashionedRestrictions string comma-separated list of page
2155 * restrictions from page table (pre 1.10)
2157 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2158 $rows = array();
2160 foreach ( $res as $row ) {
2161 $rows[] = $row;
2164 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2168 * Compiles list of active page restrictions from both page table (pre 1.10)
2169 * and page_restrictions table for this existing page.
2170 * Public for usage by LiquidThreads.
2172 * @param $rows array of db result objects
2173 * @param $oldFashionedRestrictions string comma-separated list of page
2174 * restrictions from page table (pre 1.10)
2176 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2177 $dbr = wfGetDB( DB_SLAVE );
2179 $restrictionTypes = $this->getRestrictionTypes();
2181 foreach ( $restrictionTypes as $type ) {
2182 $this->mRestrictions[$type] = array();
2183 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry( '' );
2186 $this->mCascadeRestriction = false;
2188 # Backwards-compatibility: also load the restrictions from the page record (old format).
2190 if ( $oldFashionedRestrictions === null ) {
2191 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2192 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2195 if ( $oldFashionedRestrictions != '' ) {
2197 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2198 $temp = explode( '=', trim( $restrict ) );
2199 if ( count( $temp ) == 1 ) {
2200 // old old format should be treated as edit/move restriction
2201 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2202 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2203 } else {
2204 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2208 $this->mOldRestrictions = true;
2212 if ( count( $rows ) ) {
2213 # Current system - load second to make them override.
2214 $now = wfTimestampNow();
2215 $purgeExpired = false;
2217 foreach ( $rows as $row ) {
2218 # Cycle through all the restrictions.
2220 // Don't take care of restrictions types that aren't allowed
2222 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2223 continue;
2225 // This code should be refactored, now that it's being used more generally,
2226 // But I don't really see any harm in leaving it in Block for now -werdna
2227 $expiry = Block::decodeExpiry( $row->pr_expiry );
2229 // Only apply the restrictions if they haven't expired!
2230 if ( !$expiry || $expiry > $now ) {
2231 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2232 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2234 $this->mCascadeRestriction |= $row->pr_cascade;
2235 } else {
2236 // Trigger a lazy purge of expired restrictions
2237 $purgeExpired = true;
2241 if ( $purgeExpired ) {
2242 Title::purgeExpiredRestrictions();
2246 $this->mRestrictionsLoaded = true;
2250 * Load restrictions from the page_restrictions table
2252 * @param $oldFashionedRestrictions string comma-separated list of page
2253 * restrictions from page table (pre 1.10)
2255 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2256 if ( !$this->mRestrictionsLoaded ) {
2257 if ( $this->exists() ) {
2258 $dbr = wfGetDB( DB_SLAVE );
2260 $res = $dbr->select( 'page_restrictions', '*',
2261 array( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2263 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2264 } else {
2265 $title_protection = $this->getTitleProtection();
2267 if ( $title_protection ) {
2268 $now = wfTimestampNow();
2269 $expiry = Block::decodeExpiry( $title_protection['pt_expiry'] );
2271 if ( !$expiry || $expiry > $now ) {
2272 // Apply the restrictions
2273 $this->mRestrictionsExpiry['create'] = $expiry;
2274 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2275 } else { // Get rid of the old restrictions
2276 Title::purgeExpiredRestrictions();
2277 $this->mTitleProtection = false;
2279 } else {
2280 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry( '' );
2282 $this->mRestrictionsLoaded = true;
2288 * Purge expired restrictions from the page_restrictions table
2290 static function purgeExpiredRestrictions() {
2291 $dbw = wfGetDB( DB_MASTER );
2292 $dbw->delete(
2293 'page_restrictions',
2294 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2295 __METHOD__
2298 $dbw->delete(
2299 'protected_titles',
2300 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2301 __METHOD__
2306 * Accessor/initialisation for mRestrictions
2308 * @param $action String action that permission needs to be checked for
2309 * @return Array of Strings the array of groups allowed to edit this article
2311 public function getRestrictions( $action ) {
2312 if ( !$this->mRestrictionsLoaded ) {
2313 $this->loadRestrictions();
2315 return isset( $this->mRestrictions[$action] )
2316 ? $this->mRestrictions[$action]
2317 : array();
2321 * Get the expiry time for the restriction against a given action
2323 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2324 * or not protected at all, or false if the action is not recognised.
2326 public function getRestrictionExpiry( $action ) {
2327 if ( !$this->mRestrictionsLoaded ) {
2328 $this->loadRestrictions();
2330 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2334 * Is there a version of this page in the deletion archive?
2336 * @return Int the number of archived revisions
2338 public function isDeleted() {
2339 if ( $this->getNamespace() < 0 ) {
2340 $n = 0;
2341 } else {
2342 $dbr = wfGetDB( DB_SLAVE );
2343 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2344 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2345 __METHOD__
2347 if ( $this->getNamespace() == NS_FILE ) {
2348 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2349 array( 'fa_name' => $this->getDBkey() ),
2350 __METHOD__
2354 return (int)$n;
2358 * Is there a version of this page in the deletion archive?
2360 * @return Boolean
2362 public function isDeletedQuick() {
2363 if ( $this->getNamespace() < 0 ) {
2364 return false;
2366 $dbr = wfGetDB( DB_SLAVE );
2367 $deleted = (bool)$dbr->selectField( 'archive', '1',
2368 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2369 __METHOD__
2371 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2372 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2373 array( 'fa_name' => $this->getDBkey() ),
2374 __METHOD__
2377 return $deleted;
2381 * Get the article ID for this Title from the link cache,
2382 * adding it if necessary
2384 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2385 * for update
2386 * @return Int the ID
2388 public function getArticleID( $flags = 0 ) {
2389 if ( $this->getNamespace() < 0 ) {
2390 return $this->mArticleID = 0;
2392 $linkCache = LinkCache::singleton();
2393 if ( $flags & self::GAID_FOR_UPDATE ) {
2394 $oldUpdate = $linkCache->forUpdate( true );
2395 $linkCache->clearLink( $this );
2396 $this->mArticleID = $linkCache->addLinkObj( $this );
2397 $linkCache->forUpdate( $oldUpdate );
2398 } else {
2399 if ( -1 == $this->mArticleID ) {
2400 $this->mArticleID = $linkCache->addLinkObj( $this );
2403 return $this->mArticleID;
2407 * Is this an article that is a redirect 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 Bool
2413 public function isRedirect( $flags = 0 ) {
2414 if ( !is_null( $this->mRedirect ) ) {
2415 return $this->mRedirect;
2417 # Calling getArticleID() loads the field from cache as needed
2418 if ( !$this->getArticleID( $flags ) ) {
2419 return $this->mRedirect = false;
2421 $linkCache = LinkCache::singleton();
2422 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2424 return $this->mRedirect;
2428 * What is the length of this page?
2429 * Uses link cache, adding it if necessary
2431 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2432 * @return Int
2434 public function getLength( $flags = 0 ) {
2435 if ( $this->mLength != -1 ) {
2436 return $this->mLength;
2438 # Calling getArticleID() loads the field from cache as needed
2439 if ( !$this->getArticleID( $flags ) ) {
2440 return $this->mLength = 0;
2442 $linkCache = LinkCache::singleton();
2443 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2445 return $this->mLength;
2449 * What is the page_latest field for this page?
2451 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2452 * @return Int or 0 if the page doesn't exist
2454 public function getLatestRevID( $flags = 0 ) {
2455 if ( $this->mLatestID !== false ) {
2456 return intval( $this->mLatestID );
2458 # Calling getArticleID() loads the field from cache as needed
2459 if ( !$this->getArticleID( $flags ) ) {
2460 return $this->mLatestID = 0;
2462 $linkCache = LinkCache::singleton();
2463 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2465 return $this->mLatestID;
2469 * This clears some fields in this object, and clears any associated
2470 * keys in the "bad links" section of the link cache.
2472 * - This is called from Article::doEdit() and Article::insertOn() to allow
2473 * loading of the new page_id. It's also called from
2474 * Article::doDeleteArticle()
2476 * @param $newid Int the new Article ID
2478 public function resetArticleID( $newid ) {
2479 $linkCache = LinkCache::singleton();
2480 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2482 if ( $newid === false ) {
2483 $this->mArticleID = -1;
2484 } else {
2485 $this->mArticleID = intval( $newid );
2487 $this->mRestrictionsLoaded = false;
2488 $this->mRestrictions = array();
2489 $this->mRedirect = null;
2490 $this->mLength = -1;
2491 $this->mLatestID = false;
2495 * Updates page_touched for this page; called from LinksUpdate.php
2497 * @return Bool true if the update succeded
2499 public function invalidateCache() {
2500 if ( wfReadOnly() ) {
2501 return;
2503 $dbw = wfGetDB( DB_MASTER );
2504 $success = $dbw->update(
2505 'page',
2506 array( 'page_touched' => $dbw->timestamp() ),
2507 $this->pageCond(),
2508 __METHOD__
2510 HTMLFileCache::clearFileCache( $this );
2511 return $success;
2515 * Prefix some arbitrary text with the namespace or interwiki prefix
2516 * of this object
2518 * @param $name String the text
2519 * @return String the prefixed text
2520 * @private
2522 /* private */ function prefix( $name ) {
2523 $p = '';
2524 if ( $this->mInterwiki != '' ) {
2525 $p = $this->mInterwiki . ':';
2527 if ( 0 != $this->mNamespace ) {
2528 $p .= $this->getNsText() . ':';
2530 return $p . $name;
2534 * Returns a simple regex that will match on characters and sequences invalid in titles.
2535 * Note that this doesn't pick up many things that could be wrong with titles, but that
2536 * replacing this regex with something valid will make many titles valid.
2538 * @return string regex string
2540 static function getTitleInvalidRegex() {
2541 static $rxTc = false;
2542 if ( !$rxTc ) {
2543 # Matching titles will be held as illegal.
2544 $rxTc = '/' .
2545 # Any character not allowed is forbidden...
2546 '[^' . Title::legalChars() . ']' .
2547 # URL percent encoding sequences interfere with the ability
2548 # to round-trip titles -- you can't link to them consistently.
2549 '|%[0-9A-Fa-f]{2}' .
2550 # XML/HTML character references produce similar issues.
2551 '|&[A-Za-z0-9\x80-\xff]+;' .
2552 '|&#[0-9]+;' .
2553 '|&#x[0-9A-Fa-f]+;' .
2554 '/S';
2557 return $rxTc;
2561 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2563 * @param $text string containing title to capitalize
2564 * @param $ns int namespace index, defaults to NS_MAIN
2565 * @return String containing capitalized title
2567 public static function capitalize( $text, $ns = NS_MAIN ) {
2568 global $wgContLang;
2570 if ( MWNamespace::isCapitalized( $ns ) ) {
2571 return $wgContLang->ucfirst( $text );
2572 } else {
2573 return $text;
2578 * Secure and split - main initialisation function for this object
2580 * Assumes that mDbkeyform has been set, and is urldecoded
2581 * and uses underscores, but not otherwise munged. This function
2582 * removes illegal characters, splits off the interwiki and
2583 * namespace prefixes, sets the other forms, and canonicalizes
2584 * everything.
2586 * @return Bool true on success
2588 private function secureAndSplit() {
2589 global $wgContLang, $wgLocalInterwiki;
2591 # Initialisation
2592 $rxTc = self::getTitleInvalidRegex();
2594 $this->mInterwiki = $this->mFragment = '';
2595 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2597 $dbkey = $this->mDbkeyform;
2599 # Strip Unicode bidi override characters.
2600 # Sometimes they slip into cut-n-pasted page titles, where the
2601 # override chars get included in list displays.
2602 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2604 # Clean up whitespace
2605 # Note: use of the /u option on preg_replace here will cause
2606 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2607 # conveniently disabling them.
2609 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2610 $dbkey = trim( $dbkey, '_' );
2612 if ( $dbkey == '' ) {
2613 return false;
2616 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2617 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2618 return false;
2621 $this->mDbkeyform = $dbkey;
2623 # Initial colon indicates main namespace rather than specified default
2624 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2625 if ( ':' == $dbkey { 0 } ) {
2626 $this->mNamespace = NS_MAIN;
2627 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2628 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2631 # Namespace or interwiki prefix
2632 $firstPass = true;
2633 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2634 do {
2635 $m = array();
2636 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2637 $p = $m[1];
2638 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2639 # Ordinary namespace
2640 $dbkey = $m[2];
2641 $this->mNamespace = $ns;
2642 # For Talk:X pages, check if X has a "namespace" prefix
2643 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2644 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2645 return false; # Disallow Talk:File:x type titles...
2646 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2647 return false; # Disallow Talk:Interwiki:x type titles...
2650 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2651 if ( !$firstPass ) {
2652 # Can't make a local interwiki link to an interwiki link.
2653 # That's just crazy!
2654 return false;
2657 # Interwiki link
2658 $dbkey = $m[2];
2659 $this->mInterwiki = $wgContLang->lc( $p );
2661 # Redundant interwiki prefix to the local wiki
2662 if ( $wgLocalInterwiki !== false
2663 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2665 if ( $dbkey == '' ) {
2666 # Can't have an empty self-link
2667 return false;
2669 $this->mInterwiki = '';
2670 $firstPass = false;
2671 # Do another namespace split...
2672 continue;
2675 # If there's an initial colon after the interwiki, that also
2676 # resets the default namespace
2677 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2678 $this->mNamespace = NS_MAIN;
2679 $dbkey = substr( $dbkey, 1 );
2682 # If there's no recognized interwiki or namespace,
2683 # then let the colon expression be part of the title.
2685 break;
2686 } while ( true );
2688 # We already know that some pages won't be in the database!
2690 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2691 $this->mArticleID = 0;
2693 $fragment = strstr( $dbkey, '#' );
2694 if ( false !== $fragment ) {
2695 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2696 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2697 # remove whitespace again: prevents "Foo_bar_#"
2698 # becoming "Foo_bar_"
2699 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2702 # Reject illegal characters.
2704 if ( preg_match( $rxTc, $dbkey ) ) {
2705 return false;
2709 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2710 * reachable due to the way web browsers deal with 'relative' URLs.
2711 * Also, they conflict with subpage syntax. Forbid them explicitly.
2713 if ( strpos( $dbkey, '.' ) !== false &&
2714 ( $dbkey === '.' || $dbkey === '..' ||
2715 strpos( $dbkey, './' ) === 0 ||
2716 strpos( $dbkey, '../' ) === 0 ||
2717 strpos( $dbkey, '/./' ) !== false ||
2718 strpos( $dbkey, '/../' ) !== false ||
2719 substr( $dbkey, -2 ) == '/.' ||
2720 substr( $dbkey, -3 ) == '/..' ) )
2722 return false;
2726 * Magic tilde sequences? Nu-uh!
2728 if ( strpos( $dbkey, '~~~' ) !== false ) {
2729 return false;
2733 * Limit the size of titles to 255 bytes.
2734 * This is typically the size of the underlying database field.
2735 * We make an exception for special pages, which don't need to be stored
2736 * in the database, and may edge over 255 bytes due to subpage syntax
2737 * for long titles, e.g. [[Special:Block/Long name]]
2739 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2740 strlen( $dbkey ) > 512 )
2742 return false;
2746 * Normally, all wiki links are forced to have
2747 * an initial capital letter so [[foo]] and [[Foo]]
2748 * point to the same place.
2750 * Don't force it for interwikis, since the other
2751 * site might be case-sensitive.
2753 $this->mUserCaseDBKey = $dbkey;
2754 if ( $this->mInterwiki == '' ) {
2755 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2759 * Can't make a link to a namespace alone...
2760 * "empty" local links can only be self-links
2761 * with a fragment identifier.
2763 if ( $dbkey == '' &&
2764 $this->mInterwiki == '' &&
2765 $this->mNamespace != NS_MAIN ) {
2766 return false;
2768 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2769 // IP names are not allowed for accounts, and can only be referring to
2770 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2771 // there are numerous ways to present the same IP. Having sp:contribs scan
2772 // them all is silly and having some show the edits and others not is
2773 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2774 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK ) ?
2775 IP::sanitizeIP( $dbkey ) : $dbkey;
2776 // Any remaining initial :s are illegal.
2777 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2778 return false;
2781 # Fill fields
2782 $this->mDbkeyform = $dbkey;
2783 $this->mUrlform = wfUrlencode( $dbkey );
2785 $this->mTextform = str_replace( '_', ' ', $dbkey );
2787 return true;
2791 * Set the fragment for this title. Removes the first character from the
2792 * specified fragment before setting, so it assumes you're passing it with
2793 * an initial "#".
2795 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2796 * Still in active use privately.
2798 * @param $fragment String text
2800 public function setFragment( $fragment ) {
2801 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2805 * Get a Title object associated with the talk page of this article
2807 * @return Title the object for the talk page
2809 public function getTalkPage() {
2810 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2814 * Get a title object associated with the subject page of this
2815 * talk page
2817 * @return Title the object for the subject page
2819 public function getSubjectPage() {
2820 // Is this the same title?
2821 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2822 if ( $this->getNamespace() == $subjectNS ) {
2823 return $this;
2825 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2829 * Get an array of Title objects linking to this Title
2830 * Also stores the IDs in the link cache.
2832 * WARNING: do not use this function on arbitrary user-supplied titles!
2833 * On heavily-used templates it will max out the memory.
2835 * @param $options Array: may be FOR UPDATE
2836 * @param $table String: table name
2837 * @param $prefix String: fields prefix
2838 * @return Array of Title objects linking here
2840 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2841 $linkCache = LinkCache::singleton();
2843 if ( count( $options ) > 0 ) {
2844 $db = wfGetDB( DB_MASTER );
2845 } else {
2846 $db = wfGetDB( DB_SLAVE );
2849 $res = $db->select(
2850 array( 'page', $table ),
2851 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2852 array(
2853 "{$prefix}_from=page_id",
2854 "{$prefix}_namespace" => $this->getNamespace(),
2855 "{$prefix}_title" => $this->getDBkey() ),
2856 __METHOD__,
2857 $options
2860 $retVal = array();
2861 if ( $db->numRows( $res ) ) {
2862 foreach ( $res as $row ) {
2863 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2864 if ( $titleObj ) {
2865 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2866 $retVal[] = $titleObj;
2870 return $retVal;
2874 * Get an array of Title objects using this Title as a template
2875 * Also stores the IDs in the link cache.
2877 * WARNING: do not use this function on arbitrary user-supplied titles!
2878 * On heavily-used templates it will max out the memory.
2880 * @param $options Array: may be FOR UPDATE
2881 * @return Array of Title the Title objects linking here
2883 public function getTemplateLinksTo( $options = array() ) {
2884 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2888 * Get an array of Title objects referring to non-existent articles linked from this page
2890 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2891 * @return Array of Title the Title objects
2893 public function getBrokenLinksFrom() {
2894 if ( $this->getArticleId() == 0 ) {
2895 # All links from article ID 0 are false positives
2896 return array();
2899 $dbr = wfGetDB( DB_SLAVE );
2900 $res = $dbr->select(
2901 array( 'page', 'pagelinks' ),
2902 array( 'pl_namespace', 'pl_title' ),
2903 array(
2904 'pl_from' => $this->getArticleId(),
2905 'page_namespace IS NULL'
2907 __METHOD__, array(),
2908 array(
2909 'page' => array(
2910 'LEFT JOIN',
2911 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2916 $retVal = array();
2917 foreach ( $res as $row ) {
2918 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2920 return $retVal;
2925 * Get a list of URLs to purge from the Squid cache when this
2926 * page changes
2928 * @return Array of String the URLs
2930 public function getSquidURLs() {
2931 global $wgContLang;
2933 $urls = array(
2934 $this->getInternalURL(),
2935 $this->getInternalURL( 'action=history' )
2938 // purge variant urls as well
2939 if ( $wgContLang->hasVariants() ) {
2940 $variants = $wgContLang->getVariants();
2941 foreach ( $variants as $vCode ) {
2942 $urls[] = $this->getInternalURL( '', $vCode );
2946 return $urls;
2950 * Purge all applicable Squid URLs
2952 public function purgeSquid() {
2953 global $wgUseSquid;
2954 if ( $wgUseSquid ) {
2955 $urls = $this->getSquidURLs();
2956 $u = new SquidUpdate( $urls );
2957 $u->doUpdate();
2962 * Move this page without authentication
2964 * @param $nt Title the new page Title
2965 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2967 public function moveNoAuth( &$nt ) {
2968 return $this->moveTo( $nt, false );
2972 * Check whether a given move operation would be valid.
2973 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2975 * @param $nt Title the new title
2976 * @param $auth Bool indicates whether $wgUser's permissions
2977 * should be checked
2978 * @param $reason String is the log summary of the move, used for spam checking
2979 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2981 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2982 global $wgUser;
2984 $errors = array();
2985 if ( !$nt ) {
2986 // Normally we'd add this to $errors, but we'll get
2987 // lots of syntax errors if $nt is not an object
2988 return array( array( 'badtitletext' ) );
2990 if ( $this->equals( $nt ) ) {
2991 $errors[] = array( 'selfmove' );
2993 if ( !$this->isMovable() ) {
2994 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2996 if ( $nt->getInterwiki() != '' ) {
2997 $errors[] = array( 'immobile-target-namespace-iw' );
2999 if ( !$nt->isMovable() ) {
3000 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3003 $oldid = $this->getArticleID();
3004 $newid = $nt->getArticleID();
3006 if ( strlen( $nt->getDBkey() ) < 1 ) {
3007 $errors[] = array( 'articleexists' );
3009 if ( ( $this->getDBkey() == '' ) ||
3010 ( !$oldid ) ||
3011 ( $nt->getDBkey() == '' ) ) {
3012 $errors[] = array( 'badarticleerror' );
3015 // Image-specific checks
3016 if ( $this->getNamespace() == NS_FILE ) {
3017 if ( $nt->getNamespace() != NS_FILE ) {
3018 $errors[] = array( 'imagenocrossnamespace' );
3020 $file = wfLocalFile( $this );
3021 if ( $file->exists() ) {
3022 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3023 $errors[] = array( 'imageinvalidfilename' );
3025 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3026 $errors[] = array( 'imagetypemismatch' );
3029 $destfile = wfLocalFile( $nt );
3030 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
3031 $errors[] = array( 'file-exists-sharedrepo' );
3035 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3036 $errors[] = array( 'nonfile-cannot-move-to-file' );
3039 if ( $auth ) {
3040 $errors = wfMergeErrorArrays( $errors,
3041 $this->getUserPermissionsErrors( 'move', $wgUser ),
3042 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3043 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3044 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3047 $match = EditPage::matchSummarySpamRegex( $reason );
3048 if ( $match !== false ) {
3049 // This is kind of lame, won't display nice
3050 $errors[] = array( 'spamprotectiontext' );
3053 $err = null;
3054 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3055 $errors[] = array( 'hookaborted', $err );
3058 # The move is allowed only if (1) the target doesn't exist, or
3059 # (2) the target is a redirect to the source, and has no history
3060 # (so we can undo bad moves right after they're done).
3062 if ( 0 != $newid ) { # Target exists; check for validity
3063 if ( !$this->isValidMoveTarget( $nt ) ) {
3064 $errors[] = array( 'articleexists' );
3066 } else {
3067 $tp = $nt->getTitleProtection();
3068 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3069 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3070 $errors[] = array( 'cantmove-titleprotected' );
3073 if ( empty( $errors ) ) {
3074 return true;
3076 return $errors;
3080 * Move a title to a new location
3082 * @param $nt Title the new title
3083 * @param $auth Bool indicates whether $wgUser's permissions
3084 * should be checked
3085 * @param $reason String The reason for the move
3086 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3087 * Ignored if the user doesn't have the suppressredirect right.
3088 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3090 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3091 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3092 if ( is_array( $err ) ) {
3093 return $err;
3096 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
3097 $dbw = wfGetDB( DB_MASTER );
3098 if ( $this->getNamespace() == NS_FILE ) {
3099 $file = wfLocalFile( $this );
3100 if ( $file->exists() ) {
3101 $status = $file->move( $nt );
3102 if ( !$status->isOk() ) {
3103 return $status->getErrorsArray();
3108 $pageid = $this->getArticleID();
3109 $protected = $this->isProtected();
3110 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3112 // Do the actual move
3113 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3114 if ( is_array( $err ) ) {
3115 return $err;
3118 $redirid = $this->getArticleID();
3120 // Refresh the sortkey for this row. Be careful to avoid resetting
3121 // cl_timestamp, which may disturb time-based lists on some sites.
3122 $prefix = $dbw->selectField(
3123 'categorylinks',
3124 'cl_sortkey_prefix',
3125 array( 'cl_from' => $pageid ),
3126 __METHOD__
3128 $dbw->update( 'categorylinks',
3129 array(
3130 'cl_sortkey' => Collation::singleton()->getSortKey(
3131 $nt->getCategorySortkey( $prefix ) ),
3132 'cl_timestamp=cl_timestamp' ),
3133 array( 'cl_from' => $pageid ),
3134 __METHOD__ );
3136 if ( $protected ) {
3137 # Protect the redirect title as the title used to be...
3138 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3139 array(
3140 'pr_page' => $redirid,
3141 'pr_type' => 'pr_type',
3142 'pr_level' => 'pr_level',
3143 'pr_cascade' => 'pr_cascade',
3144 'pr_user' => 'pr_user',
3145 'pr_expiry' => 'pr_expiry'
3147 array( 'pr_page' => $pageid ),
3148 __METHOD__,
3149 array( 'IGNORE' )
3151 # Update the protection log
3152 $log = new LogPage( 'protect' );
3153 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3154 if ( $reason ) {
3155 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3157 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3160 # Update watchlists
3161 $oldnamespace = $this->getNamespace() & ~1;
3162 $newnamespace = $nt->getNamespace() & ~1;
3163 $oldtitle = $this->getDBkey();
3164 $newtitle = $nt->getDBkey();
3166 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3167 WatchedItem::duplicateEntries( $this, $nt );
3170 # Update search engine
3171 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3172 $u->doUpdate();
3173 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3174 $u->doUpdate();
3176 # Update site_stats
3177 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3178 # No longer a content page
3179 # Not viewed, edited, removing
3180 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3181 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3182 # Now a content page
3183 # Not viewed, edited, adding
3184 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3185 } elseif ( $pageCountChange ) {
3186 # Redirect added
3187 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3188 } else {
3189 # Nothing special
3190 $u = false;
3192 if ( $u ) {
3193 $u->doUpdate();
3195 # Update message cache for interface messages
3196 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3197 # @bug 17860: old article can be deleted, if this the case,
3198 # delete it from message cache
3199 if ( $this->getArticleID() === 0 ) {
3200 MessageCache::singleton()->replace( $this->getDBkey(), false );
3201 } else {
3202 $oldarticle = new Article( $this );
3203 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3206 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3207 $newarticle = new Article( $nt );
3208 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3211 global $wgUser;
3212 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3213 return true;
3217 * Move page to a title which is either a redirect to the
3218 * source page or nonexistent
3220 * @param $nt Title the page to move to, which should
3221 * be a redirect or nonexistent
3222 * @param $reason String The reason for the move
3223 * @param $createRedirect Bool Whether to leave a
3224 * redirect at the old title. Ignored if the user doesn't
3225 * have the suppressredirect right
3227 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3228 global $wgUser, $wgContLang;
3230 $moveOverRedirect = $nt->exists();
3232 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3233 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3235 if ( $reason ) {
3236 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3238 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3239 $comment = $wgContLang->truncate( $comment, 250 );
3241 $oldid = $this->getArticleID();
3242 $latest = $this->getLatestRevID();
3244 $dbw = wfGetDB( DB_MASTER );
3246 if ( $moveOverRedirect ) {
3247 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3249 $newid = $nt->getArticleID();
3250 $newns = $nt->getNamespace();
3251 $newdbk = $nt->getDBkey();
3253 # Delete the old redirect. We don't save it to history since
3254 # by definition if we've got here it's rather uninteresting.
3255 # We have to remove it so that the next step doesn't trigger
3256 # a conflict on the unique namespace+title index...
3257 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3258 if ( !$dbw->cascadingDeletes() ) {
3259 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3260 global $wgUseTrackbacks;
3261 if ( $wgUseTrackbacks ) {
3262 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3264 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3265 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3266 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3267 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3268 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3269 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3270 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3272 // If the target page was recently created, it may have an entry in recentchanges still
3273 $dbw->delete( 'recentchanges',
3274 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3275 __METHOD__
3279 # Save a null revision in the page's history notifying of the move
3280 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3281 if ( !is_object( $nullRevision ) ) {
3282 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3284 $nullRevId = $nullRevision->insertOn( $dbw );
3286 $article = new Article( $this );
3287 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3289 # Change the name of the target page:
3290 $dbw->update( 'page',
3291 /* SET */ array(
3292 'page_touched' => $dbw->timestamp(),
3293 'page_namespace' => $nt->getNamespace(),
3294 'page_title' => $nt->getDBkey(),
3295 'page_latest' => $nullRevId,
3297 /* WHERE */ array( 'page_id' => $oldid ),
3298 __METHOD__
3300 $nt->resetArticleID( $oldid );
3302 # Recreate the redirect, this time in the other direction.
3303 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3304 $mwRedir = MagicWord::get( 'redirect' );
3305 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3306 $redirectArticle = new Article( $this );
3307 $newid = $redirectArticle->insertOn( $dbw );
3308 $redirectRevision = new Revision( array(
3309 'page' => $newid,
3310 'comment' => $comment,
3311 'text' => $redirectText ) );
3312 $redirectRevision->insertOn( $dbw );
3313 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3315 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3317 # Now, we record the link from the redirect to the new title.
3318 # It should have no other outgoing links...
3319 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3320 $dbw->insert( 'pagelinks',
3321 array(
3322 'pl_from' => $newid,
3323 'pl_namespace' => $nt->getNamespace(),
3324 'pl_title' => $nt->getDBkey() ),
3325 __METHOD__ );
3326 $redirectSuppressed = false;
3327 } else {
3328 $this->resetArticleID( 0 );
3329 $redirectSuppressed = true;
3332 # Log the move
3333 $log = new LogPage( 'move' );
3334 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3335 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3337 # Purge caches for old and new titles
3338 if ( $moveOverRedirect ) {
3339 # A simple purge is enough when moving over a redirect
3340 $nt->purgeSquid();
3341 } else {
3342 # Purge caches as per article creation, including any pages that link to this title
3343 Article::onArticleCreate( $nt );
3345 $this->purgeSquid();
3349 * Move this page's subpages to be subpages of $nt
3351 * @param $nt Title Move target
3352 * @param $auth bool Whether $wgUser's permissions should be checked
3353 * @param $reason string The reason for the move
3354 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3355 * Ignored if the user doesn't have the 'suppressredirect' right
3356 * @return mixed array with old page titles as keys, and strings (new page titles) or
3357 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3359 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3360 global $wgMaximumMovedPages;
3361 // Check permissions
3362 if ( !$this->userCan( 'move-subpages' ) ) {
3363 return array( 'cant-move-subpages' );
3365 // Do the source and target namespaces support subpages?
3366 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3367 return array( 'namespace-nosubpages',
3368 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3370 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3371 return array( 'namespace-nosubpages',
3372 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3375 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3376 $retval = array();
3377 $count = 0;
3378 foreach ( $subpages as $oldSubpage ) {
3379 $count++;
3380 if ( $count > $wgMaximumMovedPages ) {
3381 $retval[$oldSubpage->getPrefixedTitle()] =
3382 array( 'movepage-max-pages',
3383 $wgMaximumMovedPages );
3384 break;
3387 // We don't know whether this function was called before
3388 // or after moving the root page, so check both
3389 // $this and $nt
3390 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3391 $oldSubpage->getArticleID() == $nt->getArticleId() )
3393 // When moving a page to a subpage of itself,
3394 // don't move it twice
3395 continue;
3397 $newPageName = preg_replace(
3398 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3399 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3400 $oldSubpage->getDBkey() );
3401 if ( $oldSubpage->isTalkPage() ) {
3402 $newNs = $nt->getTalkPage()->getNamespace();
3403 } else {
3404 $newNs = $nt->getSubjectPage()->getNamespace();
3406 # Bug 14385: we need makeTitleSafe because the new page names may
3407 # be longer than 255 characters.
3408 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3410 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3411 if ( $success === true ) {
3412 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3413 } else {
3414 $retval[$oldSubpage->getPrefixedText()] = $success;
3417 return $retval;
3421 * Checks if this page is just a one-rev redirect.
3422 * Adds lock, so don't use just for light purposes.
3424 * @return Bool
3426 public function isSingleRevRedirect() {
3427 $dbw = wfGetDB( DB_MASTER );
3428 # Is it a redirect?
3429 $row = $dbw->selectRow( 'page',
3430 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3431 $this->pageCond(),
3432 __METHOD__,
3433 array( 'FOR UPDATE' )
3435 # Cache some fields we may want
3436 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3437 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3438 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3439 if ( !$this->mRedirect ) {
3440 return false;
3442 # Does the article have a history?
3443 $row = $dbw->selectField( array( 'page', 'revision' ),
3444 'rev_id',
3445 array( 'page_namespace' => $this->getNamespace(),
3446 'page_title' => $this->getDBkey(),
3447 'page_id=rev_page',
3448 'page_latest != rev_id'
3450 __METHOD__,
3451 array( 'FOR UPDATE' )
3453 # Return true if there was no history
3454 return ( $row === false );
3458 * Checks if $this can be moved to a given Title
3459 * - Selects for update, so don't call it unless you mean business
3461 * @param $nt Title the new title to check
3462 * @return Bool TRUE or FALSE
3464 public function isValidMoveTarget( $nt ) {
3465 # Is it an existing file?
3466 if ( $nt->getNamespace() == NS_FILE ) {
3467 $file = wfLocalFile( $nt );
3468 if ( $file->exists() ) {
3469 wfDebug( __METHOD__ . ": file exists\n" );
3470 return false;
3473 # Is it a redirect with no history?
3474 if ( !$nt->isSingleRevRedirect() ) {
3475 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3476 return false;
3478 # Get the article text
3479 $rev = Revision::newFromTitle( $nt );
3480 $text = $rev->getText();
3481 # Does the redirect point to the source?
3482 # Or is it a broken self-redirect, usually caused by namespace collisions?
3483 $m = array();
3484 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3485 $redirTitle = Title::newFromText( $m[1] );
3486 if ( !is_object( $redirTitle ) ||
3487 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3488 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3489 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3490 return false;
3492 } else {
3493 # Fail safe
3494 wfDebug( __METHOD__ . ": failsafe\n" );
3495 return false;
3497 return true;
3501 * Can this title be added to a user's watchlist?
3503 * @return Bool TRUE or FALSE
3505 public function isWatchable() {
3506 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3510 * Get categories to which this Title belongs and return an array of
3511 * categories' names.
3513 * @return Array of parents in the form:
3514 * $parent => $currentarticle
3516 public function getParentCategories() {
3517 global $wgContLang;
3519 $titlekey = $this->getArticleId();
3520 $dbr = wfGetDB( DB_SLAVE );
3522 $res = $dbr->select( 'categorylinks', '*',
3523 array(
3524 'cl_from' => $titleKey,
3525 "cl_from <> '0'",
3527 __METHOD__,
3528 array( 'ORDER BY' => 'cl_sortkey' )
3530 $data = array();
3532 if ( $dbr->numRows( $res ) > 0 ) {
3533 foreach ( $res as $row ) {
3534 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3535 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3538 return $data;
3542 * Get a tree of parent categories
3544 * @param $children Array with the children in the keys, to check for circular refs
3545 * @return Array Tree of parent categories
3547 public function getParentCategoryTree( $children = array() ) {
3548 $stack = array();
3549 $parents = $this->getParentCategories();
3551 if ( $parents ) {
3552 foreach ( $parents as $parent => $current ) {
3553 if ( array_key_exists( $parent, $children ) ) {
3554 # Circular reference
3555 $stack[$parent] = array();
3556 } else {
3557 $nt = Title::newFromText( $parent );
3558 if ( $nt ) {
3559 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3565 return $stack;
3570 * Get an associative array for selecting this title from
3571 * the "page" table
3573 * @return Array Selection array
3575 public function pageCond() {
3576 if ( $this->mArticleID > 0 ) {
3577 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3578 return array( 'page_id' => $this->mArticleID );
3579 } else {
3580 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3585 * Get the revision ID of the previous revision
3587 * @param $revId Int Revision ID. Get the revision that was before this one.
3588 * @param $flags Int Title::GAID_FOR_UPDATE
3589 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3591 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3592 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3593 return $db->selectField( 'revision', 'rev_id',
3594 array(
3595 'rev_page' => $this->getArticleId( $flags ),
3596 'rev_id < ' . intval( $revId )
3598 __METHOD__,
3599 array( 'ORDER BY' => 'rev_id DESC' )
3604 * Get the revision ID of the next revision
3606 * @param $revId Int Revision ID. Get the revision that was after this one.
3607 * @param $flags Int Title::GAID_FOR_UPDATE
3608 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3610 public function getNextRevisionID( $revId, $flags = 0 ) {
3611 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3612 return $db->selectField( 'revision', 'rev_id',
3613 array(
3614 'rev_page' => $this->getArticleId( $flags ),
3615 'rev_id > ' . intval( $revId )
3617 __METHOD__,
3618 array( 'ORDER BY' => 'rev_id' )
3623 * Get the first revision of the page
3625 * @param $flags Int Title::GAID_FOR_UPDATE
3626 * @return Revision (or NULL if page doesn't exist)
3628 public function getFirstRevision( $flags = 0 ) {
3629 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3630 $pageId = $this->getArticleId( $flags );
3631 if ( !$pageId ) {
3632 return null;
3634 $row = $db->selectRow( 'revision', '*',
3635 array( 'rev_page' => $pageId ),
3636 __METHOD__,
3637 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3639 if ( !$row ) {
3640 return null;
3641 } else {
3642 return new Revision( $row );
3647 * Check if this is a new page
3649 * @return bool
3651 public function isNewPage() {
3652 $dbr = wfGetDB( DB_SLAVE );
3653 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3657 * Get the oldest revision timestamp of this page
3659 * @return String: MW timestamp
3661 public function getEarliestRevTime() {
3662 $dbr = wfGetDB( DB_SLAVE );
3663 if ( $this->exists() ) {
3664 $min = $dbr->selectField( 'revision',
3665 'MIN(rev_timestamp)',
3666 array( 'rev_page' => $this->getArticleId() ),
3667 __METHOD__ );
3668 return wfTimestampOrNull( TS_MW, $min );
3670 return null;
3674 * Get the number of revisions between the given revision IDs.
3675 * Used for diffs and other things that really need it.
3677 * @param $old Int Revision ID.
3678 * @param $new Int Revision ID.
3679 * @return Int Number of revisions between these IDs.
3681 public function countRevisionsBetween( $old, $new ) {
3682 $dbr = wfGetDB( DB_SLAVE );
3683 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3684 'rev_page' => intval( $this->getArticleId() ),
3685 'rev_id > ' . intval( $old ),
3686 'rev_id < ' . intval( $new )
3687 ), __METHOD__
3692 * Get the number of authors between the given revision IDs.
3693 * Used for diffs and other things that really need it.
3695 * @param $fromRevId Int Revision ID (first before range)
3696 * @param $toRevId Int Revision ID (first after range)
3697 * @param $limit Int Maximum number of authors
3698 * @param $flags Int Title::GAID_FOR_UPDATE
3699 * @return Int
3701 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3702 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3703 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3704 array(
3705 'rev_page' => $this->getArticleID(),
3706 'rev_id > ' . (int)$fromRevId,
3707 'rev_id < ' . (int)$toRevId
3708 ), __METHOD__,
3709 array( 'LIMIT' => $limit )
3711 return (int)$db->numRows( $res );
3715 * Compare with another title.
3717 * @param $title Title
3718 * @return Bool TRUE or FALSE
3720 public function equals( Title $title ) {
3721 // Note: === is necessary for proper matching of number-like titles.
3722 return $this->getInterwiki() === $title->getInterwiki()
3723 && $this->getNamespace() == $title->getNamespace()
3724 && $this->getDBkey() === $title->getDBkey();
3728 * Callback for usort() to do title sorts by (namespace, title)
3730 * @return Integer: result of string comparison, or namespace comparison
3732 public static function compare( $a, $b ) {
3733 if ( $a->getNamespace() == $b->getNamespace() ) {
3734 return strcmp( $a->getText(), $b->getText() );
3735 } else {
3736 return $a->getNamespace() - $b->getNamespace();
3741 * Return a string representation of this title
3743 * @return String String representation of this title
3745 public function __toString() {
3746 return $this->getPrefixedText();
3750 * Check if page exists. For historical reasons, this function simply
3751 * checks for the existence of the title in the page table, and will
3752 * thus return false for interwiki links, special pages and the like.
3753 * If you want to know if a title can be meaningfully viewed, you should
3754 * probably call the isKnown() method instead.
3756 * @return Bool
3758 public function exists() {
3759 return $this->getArticleId() != 0;
3763 * Should links to this title be shown as potentially viewable (i.e. as
3764 * "bluelinks"), even if there's no record by this title in the page
3765 * table?
3767 * This function is semi-deprecated for public use, as well as somewhat
3768 * misleadingly named. You probably just want to call isKnown(), which
3769 * calls this function internally.
3771 * (ISSUE: Most of these checks are cheap, but the file existence check
3772 * can potentially be quite expensive. Including it here fixes a lot of
3773 * existing code, but we might want to add an optional parameter to skip
3774 * it and any other expensive checks.)
3776 * @return Bool
3778 public function isAlwaysKnown() {
3779 if ( $this->mInterwiki != '' ) {
3780 return true; // any interwiki link might be viewable, for all we know
3782 switch( $this->mNamespace ) {
3783 case NS_MEDIA:
3784 case NS_FILE:
3785 return (bool)wfFindFile( $this ); // file exists, possibly in a foreign repo
3786 case NS_SPECIAL:
3787 return SpecialPage::exists( $this->getDBkey() ); // valid special page
3788 case NS_MAIN:
3789 return $this->mDbkeyform == ''; // selflink, possibly with fragment
3790 case NS_MEDIAWIKI:
3791 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3792 // the full l10n of that language to be loaded. That takes much memory and
3793 // isn't needed. So we strip the language part away.
3794 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3795 return (bool)wfMsgWeirdKey( $basename ); // known system message
3796 default:
3797 return false;
3802 * Does this title refer to a page that can (or might) be meaningfully
3803 * viewed? In particular, this function may be used to determine if
3804 * links to the title should be rendered as "bluelinks" (as opposed to
3805 * "redlinks" to non-existent pages).
3807 * @return Bool
3809 public function isKnown() {
3810 return $this->isAlwaysKnown() || $this->exists();
3814 * Does this page have source text?
3816 * @return Boolean
3818 public function hasSourceText() {
3819 if ( $this->exists() ) {
3820 return true;
3823 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3824 // If the page doesn't exist but is a known system message, default
3825 // message content will be displayed, same for language subpages
3826 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3827 // causes the full l10n of that language to be loaded. That takes much
3828 // memory and isn't needed. So we strip the language part away.
3829 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3830 return (bool)wfMsgWeirdKey( $basename );
3833 return false;
3837 * Is this in a namespace that allows actual pages?
3839 * @return Bool
3840 * @internal note -- uses hardcoded namespace index instead of constants
3842 public function canExist() {
3843 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3847 * Update page_touched timestamps and send squid purge messages for
3848 * pages linking to this title. May be sent to the job queue depending
3849 * on the number of links. Typically called on create and delete.
3851 public function touchLinks() {
3852 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3853 $u->doUpdate();
3855 if ( $this->getNamespace() == NS_CATEGORY ) {
3856 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3857 $u->doUpdate();
3862 * Get the last touched timestamp
3864 * @param $db DatabaseBase: optional db
3865 * @return String Last touched timestamp
3867 public function getTouched( $db = null ) {
3868 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3869 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3870 return $touched;
3874 * Get the timestamp when this page was updated since the user last saw it.
3876 * @param $user User
3877 * @return Mixed: string/null
3879 public function getNotificationTimestamp( $user = null ) {
3880 global $wgUser, $wgShowUpdatedMarker;
3881 // Assume current user if none given
3882 if ( !$user ) {
3883 $user = $wgUser;
3885 // Check cache first
3886 $uid = $user->getId();
3887 if ( isset( $this->mNotificationTimestamp[$uid] ) ) {
3888 return $this->mNotificationTimestamp[$uid];
3890 if ( !$uid || !$wgShowUpdatedMarker ) {
3891 return $this->mNotificationTimestamp[$uid] = false;
3893 // Don't cache too much!
3894 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3895 $this->mNotificationTimestamp = array();
3897 $dbr = wfGetDB( DB_SLAVE );
3898 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3899 'wl_notificationtimestamp',
3900 array( 'wl_namespace' => $this->getNamespace(),
3901 'wl_title' => $this->getDBkey(),
3902 'wl_user' => $user->getId()
3904 __METHOD__
3906 return $this->mNotificationTimestamp[$uid];
3910 * Get the trackback URL for this page
3912 * @return String Trackback URL
3914 public function trackbackURL() {
3915 global $wgScriptPath, $wgServer, $wgScriptExtension;
3917 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3918 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3922 * Get the trackback RDF for this page
3924 * @return String Trackback RDF
3926 public function trackbackRDF() {
3927 $url = htmlspecialchars( $this->getFullURL() );
3928 $title = htmlspecialchars( $this->getText() );
3929 $tburl = $this->trackbackURL();
3931 // Autodiscovery RDF is placed in comments so HTML validator
3932 // won't barf. This is a rather icky workaround, but seems
3933 // frequently used by this kind of RDF thingy.
3935 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3936 return "<!--
3937 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3938 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3939 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3940 <rdf:Description
3941 rdf:about=\"$url\"
3942 dc:identifier=\"$url\"
3943 dc:title=\"$title\"
3944 trackback:ping=\"$tburl\" />
3945 </rdf:RDF>
3946 -->";
3950 * Generate strings used for xml 'id' names in monobook tabs
3952 * @param $prepend string defaults to 'nstab-'
3953 * @return String XML 'id' name
3955 public function getNamespaceKey( $prepend = 'nstab-' ) {
3956 global $wgContLang;
3957 // Gets the subject namespace if this title
3958 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3959 // Checks if cononical namespace name exists for namespace
3960 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3961 // Uses canonical namespace name
3962 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3963 } else {
3964 // Uses text of namespace
3965 $namespaceKey = $this->getSubjectNsText();
3967 // Makes namespace key lowercase
3968 $namespaceKey = $wgContLang->lc( $namespaceKey );
3969 // Uses main
3970 if ( $namespaceKey == '' ) {
3971 $namespaceKey = 'main';
3973 // Changes file to image for backwards compatibility
3974 if ( $namespaceKey == 'file' ) {
3975 $namespaceKey = 'image';
3977 return $prepend . $namespaceKey;
3981 * Returns true if this is a special page.
3983 * @return boolean
3985 public function isSpecialPage() {
3986 return $this->getNamespace() == NS_SPECIAL;
3990 * Returns true if this title resolves to the named special page
3992 * @param $name String The special page name
3993 * @return boolean
3995 public function isSpecial( $name ) {
3996 if ( $this->getNamespace() == NS_SPECIAL ) {
3997 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3998 if ( $name == $thisName ) {
3999 return true;
4002 return false;
4006 * If the Title refers to a special page alias which is not the local default,
4008 * @return Title A new Title which points to the local default.
4009 * Otherwise, returns $this.
4011 public function fixSpecialName() {
4012 if ( $this->getNamespace() == NS_SPECIAL ) {
4013 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4014 if ( $canonicalName ) {
4015 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4016 if ( $localName != $this->mDbkeyform ) {
4017 return Title::makeTitle( NS_SPECIAL, $localName );
4021 return $this;
4025 * Is this Title in a namespace which contains content?
4026 * In other words, is this a content page, for the purposes of calculating
4027 * statistics, etc?
4029 * @return Boolean
4031 public function isContentPage() {
4032 return MWNamespace::isContent( $this->getNamespace() );
4036 * Get all extant redirects to this Title
4038 * @param $ns Int|Null Single namespace to consider;
4039 * NULL to consider all namespaces
4040 * @return Array of Title redirects to this title
4042 public function getRedirectsHere( $ns = null ) {
4043 $redirs = array();
4045 $dbr = wfGetDB( DB_SLAVE );
4046 $where = array(
4047 'rd_namespace' => $this->getNamespace(),
4048 'rd_title' => $this->getDBkey(),
4049 'rd_from = page_id'
4051 if ( !is_null( $ns ) ) {
4052 $where['page_namespace'] = $ns;
4055 $res = $dbr->select(
4056 array( 'redirect', 'page' ),
4057 array( 'page_namespace', 'page_title' ),
4058 $where,
4059 __METHOD__
4062 foreach ( $res as $row ) {
4063 $redirs[] = self::newFromRow( $row );
4065 return $redirs;
4069 * Check if this Title is a valid redirect target
4071 * @return Bool
4073 public function isValidRedirectTarget() {
4074 global $wgInvalidRedirectTargets;
4076 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4077 if ( $this->isSpecial( 'Userlogout' ) ) {
4078 return false;
4081 foreach ( $wgInvalidRedirectTargets as $target ) {
4082 if ( $this->isSpecial( $target ) ) {
4083 return false;
4087 return true;
4091 * Get a backlink cache object
4093 * @return object BacklinkCache
4095 function getBacklinkCache() {
4096 if ( is_null( $this->mBacklinkCache ) ) {
4097 $this->mBacklinkCache = new BacklinkCache( $this );
4099 return $this->mBacklinkCache;
4103 * Whether the magic words __INDEX__ and __NOINDEX__ function for
4104 * this page.
4106 * @return Boolean
4108 public function canUseNoindex() {
4109 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4111 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4112 ? $wgContentNamespaces
4113 : $wgExemptFromUserRobotsControl;
4115 return !in_array( $this->mNamespace, $bannedNamespaces );
4120 * Returns restriction types for the current Title
4122 * @return array applicable restriction types
4124 public function getRestrictionTypes() {
4125 global $wgRestrictionTypes;
4127 $types = $this->exists() ? $wgRestrictionTypes : array( 'create' );
4129 if ( $this->getNamespace() != NS_FILE ) {
4130 $types = array_diff( $types, array( 'upload' ) );
4133 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4135 return $types;
4139 * Returns the raw sort key to be used for categories, with the specified
4140 * prefix. This will be fed to Collation::getSortKey() to get a
4141 * binary sortkey that can be used for actual sorting.
4143 * @param $prefix string The prefix to be used, specified using
4144 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4145 * prefix.
4146 * @return string
4148 public function getCategorySortkey( $prefix = '' ) {
4149 $unprefixed = $this->getText();
4150 if ( $prefix !== '' ) {
4151 # Separate with a null byte, so the unprefixed part is only used as
4152 # a tiebreaker when two pages have the exact same prefix -- null
4153 # sorts before everything else (hopefully).
4154 $prefix = strtr( $prefix, "\n\t", ' ' );
4155 return "$prefix\n$unprefixed";
4157 return $unprefixed;