Fix misspelling of my name, that I seem to have put in myself. Kinda embarrassing
[mediawiki.git] / includes / Title.php
blob089d2a8c946ed167d1b9839525ac41cb6f2d6cad
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 of getTitleProtection
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 \type{\string} The database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return \type{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 \type{\string} the title, as might be taken from a URL
181 * @return \type{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 \type{\int} the page_id corresponding to the Title to create
206 * @param $flags \type{\int} use Title::GAID_FOR_UPDATE to use master
207 * @return \type{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 \type{\arrayof{\int}} Array of IDs
224 * @return \type{\arrayof{Title}} 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 \type{Row} (needs at least page_title,page_namespace)
253 * @return \type{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 \type{\int} the namespace of the article
274 * @param $title \type{\string} the unprefixed database key form
275 * @param $fragment \type{\string} The link fragment (after the "#")
276 * @param $interwiki \type{\string} The interwiki prefix
277 * @return \type{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 \type{\int} the namespace of the article
297 * @param $title \type{\string} the database key form
298 * @param $fragment \type{\string} The link fragment (after the "#")
299 * @param $interwiki \type{\string} The interwiki prefix
300 * @return \type{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 \type{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 \type{\string} Text with possible redirect
346 * @return \type{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 \type{\string} Text with possible redirect
360 * @return \type{\array} 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 \type{\string} Text with possible redirect
399 * @return \type{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 // don't interpret + as " " most of the time!
415 // It might be safe to just use rawurldecode instead, though.
416 $m[1] = urldecode( ltrim( $m[1], ':' ) );
418 $title = Title::newFromText( $m[1] );
419 // If the title is a redirect to bad special pages or is invalid, return null
420 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
421 return null;
423 return $title;
426 return null;
429 # ----------------------------------------------------------------------------
430 # Static functions
431 # ----------------------------------------------------------------------------
434 * Get the prefixed DB key associated with an ID
436 * @param $id \type{\int} the page_id of the article
437 * @return \type{Title} an object representing the article, or NULL
438 * if no such article was found
440 public static function nameOf( $id ) {
441 $dbr = wfGetDB( DB_SLAVE );
443 $s = $dbr->selectRow(
444 'page',
445 array( 'page_namespace', 'page_title' ),
446 array( 'page_id' => $id ),
447 __METHOD__
449 if ( $s === false ) {
450 return null;
453 $n = self::makeName( $s->page_namespace, $s->page_title );
454 return $n;
458 * Get a regex character class describing the legal characters in a link
460 * @return \type{\string} the list of characters, not delimited
462 public static function legalChars() {
463 global $wgLegalTitleChars;
464 return $wgLegalTitleChars;
468 * Get a string representation of a title suitable for
469 * including in a search index
471 * @param $ns \type{\int} a namespace index
472 * @param $title \type{\string} text-form main part
473 * @return \type{\string} a stripped-down title string ready for the
474 * search index
476 public static function indexTitle( $ns, $title ) {
477 global $wgContLang;
479 $lc = SearchEngine::legalSearchChars() . '&#;';
480 $t = $wgContLang->normalizeForSearch( $title );
481 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
482 $t = $wgContLang->lc( $t );
484 # Handle 's, s'
485 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
486 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
488 $t = preg_replace( "/\\s+/", ' ', $t );
490 if ( $ns == NS_FILE ) {
491 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
493 return trim( $t );
497 * Make a prefixed DB key from a DB key and a namespace index
499 * @param $ns \type{\int} numerical representation of the namespace
500 * @param $title \type{\string} the DB key form the title
501 * @param $fragment \type{\string} The link fragment (after the "#")
502 * @param $interwiki \type{\string} The interwiki prefix
503 * @return \type{\string} the prefixed form of the title
505 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
506 global $wgContLang;
508 $namespace = $wgContLang->getNsText( $ns );
509 $name = $namespace == '' ? $title : "$namespace:$title";
510 if ( strval( $interwiki ) != '' ) {
511 $name = "$interwiki:$name";
513 if ( strval( $fragment ) != '' ) {
514 $name .= '#' . $fragment;
516 return $name;
520 * Determine whether the object refers to a page within
521 * this project.
523 * @return \type{\bool} TRUE if this is an in-project interwiki link
524 * or a wikilink, FALSE otherwise
526 public function isLocal() {
527 if ( $this->mInterwiki != '' ) {
528 return Interwiki::fetch( $this->mInterwiki )->isLocal();
529 } else {
530 return true;
535 * Determine whether the object refers to a page within
536 * this project and is transcludable.
538 * @return \type{\bool} TRUE if this is transcludable
540 public function isTrans() {
541 if ( $this->mInterwiki == '' ) {
542 return false;
545 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
549 * Returns the DB name of the distant wiki
550 * which owns the object.
552 * @return \type{\string} the DB name
554 public function getTransWikiID() {
555 if ( $this->mInterwiki == '' ) {
556 return false;
559 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
563 * Escape a text fragment, say from a link, for a URL
565 * @param $fragment string containing a URL or link fragment (after the "#")
566 * @return String: escaped string
568 static function escapeFragmentForURL( $fragment ) {
569 # Note that we don't urlencode the fragment. urlencoded Unicode
570 # fragments appear not to work in IE (at least up to 7) or in at least
571 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
572 # to care if they aren't encoded.
573 return Sanitizer::escapeId( $fragment, 'noninitial' );
576 # ----------------------------------------------------------------------------
577 # Other stuff
578 # ----------------------------------------------------------------------------
580 /** Simple accessors */
582 * Get the text form (spaces not underscores) of the main part
584 * @return \type{\string} Main part of the title
586 public function getText() { return $this->mTextform; }
589 * Get the URL-encoded form of the main part
591 * @return \type{\string} Main part of the title, URL-encoded
593 public function getPartialURL() { return $this->mUrlform; }
596 * Get the main part with underscores
598 * @return String: Main part of the title, with underscores
600 public function getDBkey() { return $this->mDbkeyform; }
603 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
605 * @return Integer: Namespace index
607 public function getNamespace() { return $this->mNamespace; }
610 * Get the namespace text
612 * @return String: Namespace text
614 public function getNsText() {
615 global $wgContLang;
617 if ( $this->mInterwiki != '' ) {
618 // This probably shouldn't even happen. ohh man, oh yuck.
619 // But for interwiki transclusion it sometimes does.
620 // Shit. Shit shit shit.
622 // Use the canonical namespaces if possible to try to
623 // resolve a foreign namespace.
624 if ( MWNamespace::exists( $this->mNamespace ) ) {
625 return MWNamespace::getCanonicalName( $this->mNamespace );
628 return $wgContLang->getNsText( $this->mNamespace );
632 * Get the DB key with the initial letter case as specified by the user
634 * @return \type{\string} DB key
636 function getUserCaseDBKey() {
637 return $this->mUserCaseDBKey;
641 * Get the namespace text of the subject (rather than talk) page
643 * @return \type{\string} Namespace text
645 public function getSubjectNsText() {
646 global $wgContLang;
647 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
651 * Get the namespace text of the talk page
653 * @return \type{\string} Namespace text
655 public function getTalkNsText() {
656 global $wgContLang;
657 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
661 * Could this title have a corresponding talk page?
663 * @return \type{\bool} TRUE or FALSE
665 public function canTalk() {
666 return( MWNamespace::canTalk( $this->mNamespace ) );
670 * Get the interwiki prefix (or null string)
672 * @return \type{\string} Interwiki prefix
674 public function getInterwiki() { return $this->mInterwiki; }
677 * Get the Title fragment (i.e.\ the bit after the #) in text form
679 * @return \type{\string} Title fragment
681 public function getFragment() { return $this->mFragment; }
684 * Get the fragment in URL form, including the "#" character if there is one
685 * @return \type{\string} Fragment in URL form
687 public function getFragmentForURL() {
688 if ( $this->mFragment == '' ) {
689 return '';
690 } else {
691 return '#' . Title::escapeFragmentForURL( $this->mFragment );
696 * Get the default namespace index, for when there is no namespace
698 * @return \type{\int} Default namespace index
700 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
703 * Get title for search index
705 * @return \type{\string} a stripped-down title string ready for the
706 * search index
708 public function getIndexTitle() {
709 return Title::indexTitle( $this->mNamespace, $this->mTextform );
713 * Get the prefixed database key form
715 * @return \type{\string} the prefixed title, with underscores and
716 * any interwiki and namespace prefixes
718 public function getPrefixedDBkey() {
719 $s = $this->prefix( $this->mDbkeyform );
720 $s = str_replace( ' ', '_', $s );
721 return $s;
725 * Get the prefixed title with spaces.
726 * This is the form usually used for display
728 * @return \type{\string} the prefixed title, with spaces
730 public function getPrefixedText() {
731 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
732 $s = $this->prefix( $this->mTextform );
733 $s = str_replace( '_', ' ', $s );
734 $this->mPrefixedText = $s;
736 return $this->mPrefixedText;
740 * Get the prefixed title with spaces, plus any fragment
741 * (part beginning with '#')
743 * @return \type{\string} the prefixed title, with spaces and
744 * the fragment, including '#'
746 public function getFullText() {
747 $text = $this->getPrefixedText();
748 if ( $this->mFragment != '' ) {
749 $text .= '#' . $this->mFragment;
751 return $text;
755 * Get the base name, i.e. the leftmost parts before the /
757 * @return \type{\string} Base name
759 public function getBaseText() {
760 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
761 return $this->getText();
764 $parts = explode( '/', $this->getText() );
765 # Don't discard the real title if there's no subpage involved
766 if ( count( $parts ) > 1 ) {
767 unset( $parts[count( $parts ) - 1] );
769 return implode( '/', $parts );
773 * Get the lowest-level subpage name, i.e. the rightmost part after /
775 * @return \type{\string} Subpage name
777 public function getSubpageText() {
778 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
779 return( $this->mTextform );
781 $parts = explode( '/', $this->mTextform );
782 return( $parts[count( $parts ) - 1] );
786 * Get a URL-encoded form of the subpage text
788 * @return \type{\string} URL-encoded subpage name
790 public function getSubpageUrlForm() {
791 $text = $this->getSubpageText();
792 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
793 return( $text );
797 * Get a URL-encoded title (not an actual URL) including interwiki
799 * @return \type{\string} the URL-encoded form
801 public function getPrefixedURL() {
802 $s = $this->prefix( $this->mDbkeyform );
803 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
804 return $s;
808 * Get a real URL referring to this title, with interwiki link and
809 * fragment
811 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
812 * links. Can be specified as an associative array as well, e.g.,
813 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
814 * @param $variant \type{\string} language variant of url (for sr, zh..)
815 * @return \type{\string} the URL
817 public function getFullURL( $query = '', $variant = false ) {
818 global $wgServer, $wgRequest;
820 if ( is_array( $query ) ) {
821 $query = wfArrayToCGI( $query );
824 $interwiki = Interwiki::fetch( $this->mInterwiki );
825 if ( !$interwiki ) {
826 $url = $this->getLocalURL( $query, $variant );
828 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
829 // Correct fix would be to move the prepending elsewhere.
830 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
831 $url = $wgServer . $url;
833 } else {
834 $baseUrl = $interwiki->getURL();
836 $namespace = wfUrlencode( $this->getNsText() );
837 if ( $namespace != '' ) {
838 # Can this actually happen? Interwikis shouldn't be parsed.
839 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
840 $namespace .= ':';
842 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
843 $url = wfAppendQuery( $url, $query );
846 # Finally, add the fragment.
847 $url .= $this->getFragmentForURL();
849 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
850 return $url;
854 * Get a URL with no fragment or server name. If this page is generated
855 * with action=render, $wgServer is prepended.
857 * @param $query Mixed: an optional query string; if not specified,
858 * $wgArticlePath will be used. Can be specified as an associative array
859 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
860 * URL-escaped).
861 * @param $variant \type{\string} language variant of url (for sr, zh..)
862 * @return \type{\string} the URL
864 public function getLocalURL( $query = '', $variant = false ) {
865 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
866 global $wgVariantArticlePath, $wgContLang;
868 if ( is_array( $query ) ) {
869 $query = wfArrayToCGI( $query );
872 if ( $this->isExternal() ) {
873 $url = $this->getFullURL();
874 if ( $query ) {
875 // This is currently only used for edit section links in the
876 // context of interwiki transclusion. In theory we should
877 // append the query to the end of any existing query string,
878 // but interwiki transclusion is already broken in that case.
879 $url .= "?$query";
881 } else {
882 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
883 if ( $query == '' ) {
884 if ( $variant != false && $wgContLang->hasVariants() ) {
885 if ( !$wgVariantArticlePath ) {
886 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
887 } else {
888 $variantArticlePath = $wgVariantArticlePath;
890 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
891 $url = str_replace( '$1', $dbkey, $url );
892 } else {
893 $url = str_replace( '$1', $dbkey, $wgArticlePath );
895 } else {
896 global $wgActionPaths;
897 $url = false;
898 $matches = array();
899 if ( !empty( $wgActionPaths ) &&
900 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
902 $action = urldecode( $matches[2] );
903 if ( isset( $wgActionPaths[$action] ) ) {
904 $query = $matches[1];
905 if ( isset( $matches[4] ) ) {
906 $query .= $matches[4];
908 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
909 if ( $query != '' ) {
910 $url = wfAppendQuery( $url, $query );
914 if ( $url === false ) {
915 if ( $query == '-' ) {
916 $query = '';
918 $url = "{$wgScript}?title={$dbkey}&{$query}";
922 // FIXME: this causes breakage in various places when we
923 // actually expected a local URL and end up with dupe prefixes.
924 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
925 $url = $wgServer . $url;
928 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
929 return $url;
933 * Get a URL that's the simplest URL that will be valid to link, locally,
934 * to the current Title. It includes the fragment, but does not include
935 * the server unless action=render is used (or the link is external). If
936 * there's a fragment but the prefixed text is empty, we just return a link
937 * to the fragment.
939 * The result obviously should not be URL-escaped, but does need to be
940 * HTML-escaped if it's being output in HTML.
942 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
943 * query string. Keys and values will be escaped.
944 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
945 * for external links. Default is "false" (same variant as current page,
946 * for anonymous users).
947 * @return \type{\string} the URL
949 public function getLinkUrl( $query = array(), $variant = false ) {
950 wfProfileIn( __METHOD__ );
951 if ( $this->isExternal() ) {
952 $ret = $this->getFullURL( $query );
953 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
954 $ret = $this->getFragmentForURL();
955 } else {
956 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
958 wfProfileOut( __METHOD__ );
959 return $ret;
963 * Get an HTML-escaped version of the URL form, suitable for
964 * using in a link, without a server name or fragment
966 * @param $query \type{\string} an optional query string
967 * @return \type{\string} the URL
969 public function escapeLocalURL( $query = '' ) {
970 return htmlspecialchars( $this->getLocalURL( $query ) );
974 * Get an HTML-escaped version of the URL form, suitable for
975 * using in a link, including the server name and fragment
977 * @param $query \type{\string} an optional query string
978 * @return \type{\string} the URL
980 public function escapeFullURL( $query = '' ) {
981 return htmlspecialchars( $this->getFullURL( $query ) );
985 * Get the URL form for an internal link.
986 * - Used in various Squid-related code, in case we have a different
987 * internal hostname for the server from the exposed one.
989 * @param $query \type{\string} an optional query string
990 * @param $variant \type{\string} language variant of url (for sr, zh..)
991 * @return \type{\string} the URL
993 public function getInternalURL( $query = '', $variant = false ) {
994 global $wgInternalServer;
995 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
996 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
997 return $url;
1001 * Get the edit URL for this Title
1003 * @return \type{\string} the URL, or a null string if this is an
1004 * interwiki link
1006 public function getEditURL() {
1007 if ( $this->mInterwiki != '' ) {
1008 return '';
1010 $s = $this->getLocalURL( 'action=edit' );
1012 return $s;
1016 * Get the HTML-escaped displayable text form.
1017 * Used for the title field in <a> tags.
1019 * @return \type{\string} the text, including any prefixes
1021 public function getEscapedText() {
1022 return htmlspecialchars( $this->getPrefixedText() );
1026 * Is this Title interwiki?
1028 * @return \type{\bool}
1030 public function isExternal() {
1031 return ( $this->mInterwiki != '' );
1035 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1037 * @param $action \type{\string} Action to check (default: edit)
1038 * @return \type{\bool}
1040 public function isSemiProtected( $action = 'edit' ) {
1041 if ( $this->exists() ) {
1042 $restrictions = $this->getRestrictions( $action );
1043 if ( count( $restrictions ) > 0 ) {
1044 foreach ( $restrictions as $restriction ) {
1045 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1046 return false;
1049 } else {
1050 # Not protected
1051 return false;
1053 return true;
1054 } else {
1055 # If it doesn't exist, it can't be protected
1056 return false;
1061 * Does the title correspond to a protected article?
1063 * @param $action \type{\string} the action the page is protected from,
1064 * by default checks all actions.
1065 * @return \type{\bool}
1067 public function isProtected( $action = '' ) {
1068 global $wgRestrictionLevels;
1070 $restrictionTypes = $this->getRestrictionTypes();
1072 # Special pages have inherent protection
1073 if( $this->getNamespace() == NS_SPECIAL ) {
1074 return true;
1077 # Check regular protection levels
1078 foreach ( $restrictionTypes as $type ) {
1079 if ( $action == $type || $action == '' ) {
1080 $r = $this->getRestrictions( $type );
1081 foreach ( $wgRestrictionLevels as $level ) {
1082 if ( in_array( $level, $r ) && $level != '' ) {
1083 return true;
1089 return false;
1093 * Is this a conversion table for the LanguageConverter?
1095 * @return \type{\bool}
1097 public function isConversionTable() {
1099 $this->getNamespace() == NS_MEDIAWIKI &&
1100 strpos( $this->getText(), 'Conversiontable' ) !== false
1103 return true;
1106 return false;
1110 * Is $wgUser watching this page?
1112 * @return \type{\bool}
1114 public function userIsWatching() {
1115 global $wgUser;
1117 if ( is_null( $this->mWatched ) ) {
1118 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1119 $this->mWatched = false;
1120 } else {
1121 $this->mWatched = $wgUser->isWatched( $this );
1124 return $this->mWatched;
1128 * Can $wgUser perform $action on this page?
1129 * This skips potentially expensive cascading permission checks
1130 * as well as avoids expensive error formatting
1132 * Suitable for use for nonessential UI controls in common cases, but
1133 * _not_ for functional access control.
1135 * May provide false positives, but should never provide a false negative.
1137 * @param $action \type{\string} action that permission needs to be checked for
1138 * @return \type{\bool}
1140 public function quickUserCan( $action ) {
1141 return $this->userCan( $action, false );
1145 * Determines if $user is unable to edit this page because it has been protected
1146 * by $wgNamespaceProtection.
1148 * @param $user User object, $wgUser will be used if not passed
1149 * @return \type{\bool}
1151 public function isNamespaceProtected( User $user = null ) {
1152 global $wgNamespaceProtection;
1154 if ( $user === null ) {
1155 global $wgUser;
1156 $user = $wgUser;
1159 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1160 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1161 if ( $right != '' && !$user->isAllowed( $right ) ) {
1162 return true;
1166 return false;
1170 * Can $wgUser perform $action on this page?
1172 * @param $action \type{\string} action that permission needs to be checked for
1173 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1174 * @return \type{\bool}
1176 public function userCan( $action, $doExpensiveQueries = true ) {
1177 global $wgUser;
1178 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1182 * Can $user perform $action on this page?
1184 * FIXME: This *does not* check throttles (User::pingLimiter()).
1186 * @param $action \type{\string}action that permission needs to be checked for
1187 * @param $user \type{User} user to check
1188 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1189 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1190 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1192 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1193 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1195 // Remove the errors being ignored.
1196 foreach ( $errors as $index => $error ) {
1197 $error_key = is_array( $error ) ? $error[0] : $error;
1199 if ( in_array( $error_key, $ignoreErrors ) ) {
1200 unset( $errors[$index] );
1204 return $errors;
1208 * Permissions checks that fail most often, and which are easiest to test.
1210 * @param $action String the action to check
1211 * @param $user User user to check
1212 * @param $errors Array list of current errors
1213 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1214 * @param $short Boolean short circuit on first error
1216 * @return Array list of errors
1218 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1219 if ( $action == 'create' ) {
1220 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1221 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1222 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1224 } elseif ( $action == 'move' ) {
1225 if ( !$user->isAllowed( 'move-rootuserpages' )
1226 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1227 // Show user page-specific message only if the user can move other pages
1228 $errors[] = array( 'cant-move-user-page' );
1231 // Check if user is allowed to move files if it's a file
1232 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1233 $errors[] = array( 'movenotallowedfile' );
1236 if ( !$user->isAllowed( 'move' ) ) {
1237 // User can't move anything
1238 global $wgGroupPermissions;
1239 $userCanMove = false;
1240 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1241 $userCanMove = $wgGroupPermissions['user']['move'];
1243 $autoconfirmedCanMove = false;
1244 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1245 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1247 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1248 // custom message if logged-in users without any special rights can move
1249 $errors[] = array( 'movenologintext' );
1250 } else {
1251 $errors[] = array( 'movenotallowed' );
1254 } elseif ( $action == 'move-target' ) {
1255 if ( !$user->isAllowed( 'move' ) ) {
1256 // User can't move anything
1257 $errors[] = array( 'movenotallowed' );
1258 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1259 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1260 // Show user page-specific message only if the user can move other pages
1261 $errors[] = array( 'cant-move-to-user-page' );
1263 } elseif ( !$user->isAllowed( $action ) ) {
1264 // We avoid expensive display logic for quickUserCan's and such
1265 $groups = false;
1266 if ( !$short ) {
1267 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1268 User::getGroupsWithPermission( $action ) );
1271 if ( $groups ) {
1272 global $wgLang;
1273 $return = array(
1274 'badaccess-groups',
1275 $wgLang->commaList( $groups ),
1276 count( $groups )
1278 } else {
1279 $return = array( 'badaccess-group0' );
1281 $errors[] = $return;
1284 return $errors;
1288 * Add the resulting error code to the errors array
1290 * @param $errors Array list of current errors
1291 * @param $result Mixed result of errors
1293 * @return Array list of errors
1295 private function resultToError( $errors, $result ) {
1296 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1297 // A single array representing an error
1298 $errors[] = $result;
1299 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1300 // A nested array representing multiple errors
1301 $errors = array_merge( $errors, $result );
1302 } else if ( $result !== '' && is_string( $result ) ) {
1303 // A string representing a message-id
1304 $errors[] = array( $result );
1305 } else if ( $result === false ) {
1306 // a generic "We don't want them to do that"
1307 $errors[] = array( 'badaccess-group0' );
1309 return $errors;
1313 * Check various permission hooks
1315 * @param $action String the action to check
1316 * @param $user User user to check
1317 * @param $errors Array list of current errors
1318 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1319 * @param $short Boolean short circuit on first error
1321 * @return Array list of errors
1323 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1324 // Use getUserPermissionsErrors instead
1325 $result = '';
1326 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1327 return $result ? array() : array( array( 'badaccess-group0' ) );
1329 // Check getUserPermissionsErrors hook
1330 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1331 $errors = $this->resultToError( $errors, $result );
1333 // Check getUserPermissionsErrorsExpensive hook
1334 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1335 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1336 $errors = $this->resultToError( $errors, $result );
1339 return $errors;
1343 * Check permissions on special pages & namespaces
1345 * @param $action String the action to check
1346 * @param $user User user to check
1347 * @param $errors Array list of current errors
1348 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1349 * @param $short Boolean short circuit on first error
1351 * @return Array list of errors
1353 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1354 # Only 'createaccount' and 'execute' can be performed on
1355 # special pages, which don't actually exist in the DB.
1356 $specialOKActions = array( 'createaccount', 'execute' );
1357 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1358 $errors[] = array( 'ns-specialprotected' );
1361 # Check $wgNamespaceProtection for restricted namespaces
1362 if ( $this->isNamespaceProtected( $user ) ) {
1363 $ns = $this->mNamespace == NS_MAIN ?
1364 wfMsg( 'nstab-main' ) : $this->getNsText();
1365 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1366 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1369 return $errors;
1373 * Check CSS/JS sub-page permissions
1375 * @param $action String the action to check
1376 * @param $user User user to check
1377 * @param $errors Array list of current errors
1378 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1379 * @param $short Boolean short circuit on first error
1381 * @return Array list of errors
1383 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1384 # Protect css/js subpages of user pages
1385 # XXX: this might be better using restrictions
1386 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1387 # and $this->userCanEditJsSubpage() from working
1388 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1389 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1390 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1391 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1392 $errors[] = array( 'customcssjsprotected' );
1393 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1394 $errors[] = array( 'customcssjsprotected' );
1398 return $errors;
1402 * Check against page_restrictions table requirements on this
1403 * page. The user must possess all required rights for this
1404 * action.
1406 * @param $action String the action to check
1407 * @param $user User user to check
1408 * @param $errors Array list of current errors
1409 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1410 * @param $short Boolean short circuit on first error
1412 * @return Array list of errors
1414 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1415 foreach ( $this->getRestrictions( $action ) as $right ) {
1416 // Backwards compatibility, rewrite sysop -> protect
1417 if ( $right == 'sysop' ) {
1418 $right = 'protect';
1420 if ( $right != '' && !$user->isAllowed( $right ) ) {
1421 // Users with 'editprotected' permission can edit protected pages
1422 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1423 // Users with 'editprotected' permission cannot edit protected pages
1424 // with cascading option turned on.
1425 if ( $this->mCascadeRestriction ) {
1426 $errors[] = array( 'protectedpagetext', $right );
1428 } else {
1429 $errors[] = array( 'protectedpagetext', $right );
1434 return $errors;
1438 * Check restrictions on cascading pages.
1440 * @param $action String the action to check
1441 * @param $user User user to check
1442 * @param $errors Array list of current errors
1443 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1444 * @param $short Boolean short circuit on first error
1446 * @return Array list of errors
1448 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1449 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1450 # We /could/ use the protection level on the source page, but it's
1451 # fairly ugly as we have to establish a precedence hierarchy for pages
1452 # included by multiple cascade-protected pages. So just restrict
1453 # it to people with 'protect' permission, as they could remove the
1454 # protection anyway.
1455 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1456 # Cascading protection depends on more than this page...
1457 # Several cascading protected pages may include this page...
1458 # Check each cascading level
1459 # This is only for protection restrictions, not for all actions
1460 if ( isset( $restrictions[$action] ) ) {
1461 foreach ( $restrictions[$action] as $right ) {
1462 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1463 if ( $right != '' && !$user->isAllowed( $right ) ) {
1464 $pages = '';
1465 foreach ( $cascadingSources as $page )
1466 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1467 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1473 return $errors;
1477 * Check action permissions not already checked in checkQuickPermissions
1479 * @param $action String the action to check
1480 * @param $user User user to check
1481 * @param $errors Array list of current errors
1482 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1483 * @param $short Boolean short circuit on first error
1485 * @return Array list of errors
1487 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1488 if ( $action == 'protect' ) {
1489 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1490 // If they can't edit, they shouldn't protect.
1491 $errors[] = array( 'protect-cantedit' );
1493 } elseif ( $action == 'create' ) {
1494 $title_protection = $this->getTitleProtection();
1495 if( $title_protection ) {
1496 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1497 $title_protection['pt_create_perm'] = 'protect'; // B/C
1499 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1500 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1503 } elseif ( $action == 'move' ) {
1504 // Check for immobile pages
1505 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1506 // Specific message for this case
1507 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1508 } elseif ( !$this->isMovable() ) {
1509 // Less specific message for rarer cases
1510 $errors[] = array( 'immobile-page' );
1512 } elseif ( $action == 'move-target' ) {
1513 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1514 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1515 } elseif ( !$this->isMovable() ) {
1516 $errors[] = array( 'immobile-target-page' );
1519 return $errors;
1523 * Check that the user isn't blocked from editting.
1525 * @param $action String the action to check
1526 * @param $user User user to check
1527 * @param $errors Array list of current errors
1528 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1529 * @param $short Boolean short circuit on first error
1531 * @return Array list of errors
1533 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1534 if( $short && count( $errors ) > 0 ) {
1535 return $errors;
1538 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1540 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1541 $errors[] = array( 'confirmedittext' );
1544 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1545 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1546 $block = $user->mBlock;
1548 // This is from OutputPage::blockedPage
1549 // Copied at r23888 by werdna
1551 $id = $user->blockedBy();
1552 $reason = $user->blockedFor();
1553 if ( $reason == '' ) {
1554 $reason = wfMsg( 'blockednoreason' );
1556 $ip = wfGetIP();
1558 if ( is_numeric( $id ) ) {
1559 $name = User::whoIs( $id );
1560 } else {
1561 $name = $id;
1564 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1565 $blockid = $block->mId;
1566 $blockExpiry = $user->mBlock->mExpiry;
1567 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1568 if ( $blockExpiry == 'infinity' ) {
1569 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1570 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1572 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1573 if ( !strpos( $option, ':' ) )
1574 continue;
1576 list( $show, $value ) = explode( ':', $option );
1578 if ( $value == 'infinite' || $value == 'indefinite' ) {
1579 $blockExpiry = $show;
1580 break;
1583 } else {
1584 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1587 $intended = $user->mBlock->mAddress;
1589 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1590 $blockid, $blockExpiry, $intended, $blockTimestamp );
1593 return $errors;
1597 * Can $user perform $action on this page? This is an internal function,
1598 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1599 * checks on wfReadOnly() and blocks)
1601 * @param $action \type{\string} action that permission needs to be checked for
1602 * @param $user \type{User} user to check
1603 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1604 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1605 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1607 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1608 wfProfileIn( __METHOD__ );
1610 $errors = array();
1611 $checks = array(
1612 'checkQuickPermissions',
1613 'checkPermissionHooks',
1614 'checkSpecialsAndNSPermissions',
1615 'checkCSSandJSPermissions',
1616 'checkPageRestrictions',
1617 'checkCascadingSourcesRestrictions',
1618 'checkActionPermissions',
1619 'checkUserBlock'
1622 while( count( $checks ) > 0 &&
1623 !( $short && count( $errors ) > 0 ) ) {
1624 $method = array_shift( $checks );
1625 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1628 wfProfileOut( __METHOD__ );
1629 return $errors;
1633 * Is this title subject to title protection?
1635 * @return \type{\mixed} An associative array representing any existent title
1636 * protection, or false if there's none.
1638 private function getTitleProtection() {
1639 // Can't protect pages in special namespaces
1640 if ( $this->getNamespace() < 0 ) {
1641 return false;
1644 // Can't protect pages that exist.
1645 if ( $this->exists() ) {
1646 return false;
1649 if ( !isset( $this->mTitleProtection ) ) {
1650 $dbr = wfGetDB( DB_SLAVE );
1651 $res = $dbr->select( 'protected_titles', '*',
1652 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1653 __METHOD__ );
1655 // fetchRow returns false if there are no rows.
1656 $this->mTitleProtection = $dbr->fetchRow( $res );
1658 return $this->mTitleProtection;
1661 private function invalidateTitleProtectionCache() {
1662 unset( $this->mTitleProtection );
1666 * Update the title protection status
1668 * @param $create_perm \type{\string} Permission required for creation
1669 * @param $reason \type{\string} Reason for protection
1670 * @param $expiry \type{\string} Expiry timestamp
1671 * @return boolean true
1673 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1674 global $wgUser, $wgContLang;
1676 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1677 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1678 // No change
1679 return true;
1682 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1684 $dbw = wfGetDB( DB_MASTER );
1686 $encodedExpiry = Block::encodeExpiry( $expiry, $dbw );
1688 $expiry_description = '';
1689 if ( $encodedExpiry != 'infinity' ) {
1690 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1691 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1692 } else {
1693 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1696 # Update protection table
1697 if ( $create_perm != '' ) {
1698 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1699 array(
1700 'pt_namespace' => $namespace,
1701 'pt_title' => $title,
1702 'pt_create_perm' => $create_perm,
1703 'pt_timestamp' => Block::encodeExpiry( wfTimestampNow(), $dbw ),
1704 'pt_expiry' => $encodedExpiry,
1705 'pt_user' => $wgUser->getId(),
1706 'pt_reason' => $reason,
1707 ), __METHOD__
1709 } else {
1710 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1711 'pt_title' => $title ), __METHOD__ );
1713 $this->invalidateTitleProtectionCache();
1715 # Update the protection log
1716 if ( $dbw->affectedRows() ) {
1717 $log = new LogPage( 'protect' );
1719 if ( $create_perm ) {
1720 $params = array( "[create=$create_perm] $expiry_description", '' );
1721 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1722 } else {
1723 $log->addEntry( 'unprotect', $this, $reason );
1727 return true;
1731 * Remove any title protection due to page existing
1733 public function deleteTitleProtection() {
1734 $dbw = wfGetDB( DB_MASTER );
1736 $dbw->delete(
1737 'protected_titles',
1738 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1739 __METHOD__
1741 $this->invalidateTitleProtectionCache();
1745 * Would anybody with sufficient privileges be able to move this page?
1746 * Some pages just aren't movable.
1748 * @return \type{\bool} TRUE or FALSE
1750 public function isMovable() {
1751 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1755 * Can $wgUser read this page?
1757 * @return \type{\bool}
1758 * @todo fold these checks into userCan()
1760 public function userCanRead() {
1761 global $wgUser, $wgGroupPermissions;
1763 static $useShortcut = null;
1765 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1766 if ( is_null( $useShortcut ) ) {
1767 global $wgRevokePermissions;
1768 $useShortcut = true;
1769 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1770 # Not a public wiki, so no shortcut
1771 $useShortcut = false;
1772 } elseif ( !empty( $wgRevokePermissions ) ) {
1774 * Iterate through each group with permissions being revoked (key not included since we don't care
1775 * what the group name is), then check if the read permission is being revoked. If it is, then
1776 * we don't use the shortcut below since the user might not be able to read, even though anon
1777 * reading is allowed.
1779 foreach ( $wgRevokePermissions as $perms ) {
1780 if ( !empty( $perms['read'] ) ) {
1781 # We might be removing the read right from the user, so no shortcut
1782 $useShortcut = false;
1783 break;
1789 $result = null;
1790 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1791 if ( $result !== null ) {
1792 return $result;
1795 # Shortcut for public wikis, allows skipping quite a bit of code
1796 if ( $useShortcut ) {
1797 return true;
1800 if ( $wgUser->isAllowed( 'read' ) ) {
1801 return true;
1802 } else {
1803 global $wgWhitelistRead;
1806 * Always grant access to the login page.
1807 * Even anons need to be able to log in.
1809 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1810 return true;
1814 * Bail out if there isn't whitelist
1816 if ( !is_array( $wgWhitelistRead ) ) {
1817 return false;
1821 * Check for explicit whitelisting
1823 $name = $this->getPrefixedText();
1824 $dbName = $this->getPrefixedDBKey();
1825 // Check with and without underscores
1826 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1827 return true;
1830 * Old settings might have the title prefixed with
1831 * a colon for main-namespace pages
1833 if ( $this->getNamespace() == NS_MAIN ) {
1834 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1835 return true;
1840 * If it's a special page, ditch the subpage bit
1841 * and check again
1843 if ( $this->getNamespace() == NS_SPECIAL ) {
1844 $name = $this->getDBkey();
1845 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1846 if ( $name === false ) {
1847 # Invalid special page, but we show standard login required message
1848 return false;
1851 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1852 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1853 return true;
1858 return false;
1862 * Is this a talk page of some sort?
1864 * @return \type{\bool}
1866 public function isTalkPage() {
1867 return MWNamespace::isTalk( $this->getNamespace() );
1871 * Is this a subpage?
1873 * @return \type{\bool}
1875 public function isSubpage() {
1876 return MWNamespace::hasSubpages( $this->mNamespace )
1877 ? strpos( $this->getText(), '/' ) !== false
1878 : false;
1882 * Does this have subpages? (Warning, usually requires an extra DB query.)
1884 * @return \type{\bool}
1886 public function hasSubpages() {
1887 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1888 # Duh
1889 return false;
1892 # We dynamically add a member variable for the purpose of this method
1893 # alone to cache the result. There's no point in having it hanging
1894 # around uninitialized in every Title object; therefore we only add it
1895 # if needed and don't declare it statically.
1896 if ( isset( $this->mHasSubpages ) ) {
1897 return $this->mHasSubpages;
1900 $subpages = $this->getSubpages( 1 );
1901 if ( $subpages instanceof TitleArray ) {
1902 return $this->mHasSubpages = (bool)$subpages->count();
1904 return $this->mHasSubpages = false;
1908 * Get all subpages of this page.
1910 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1911 * @return mixed TitleArray, or empty array if this page's namespace
1912 * doesn't allow subpages
1914 public function getSubpages( $limit = -1 ) {
1915 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1916 return array();
1919 $dbr = wfGetDB( DB_SLAVE );
1920 $conds['page_namespace'] = $this->getNamespace();
1921 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1922 $options = array();
1923 if ( $limit > -1 ) {
1924 $options['LIMIT'] = $limit;
1926 return $this->mSubpages = TitleArray::newFromResult(
1927 $dbr->select( 'page',
1928 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1929 $conds,
1930 __METHOD__,
1931 $options
1937 * Could this page contain custom CSS or JavaScript, based
1938 * on the title?
1940 * @return \type{\bool}
1942 public function isCssOrJsPage() {
1943 return $this->mNamespace == NS_MEDIAWIKI
1944 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1948 * Is this a .css or .js subpage of a user page?
1949 * @return \type{\bool}
1951 public function isCssJsSubpage() {
1952 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1956 * Is this a *valid* .css or .js subpage of a user page?
1958 * @return \type{\bool}
1959 * @deprecated
1961 public function isValidCssJsSubpage() {
1962 return $this->isCssJsSubpage();
1966 * Trim down a .css or .js subpage title to get the corresponding skin name
1968 * @return string containing skin name from .css or .js subpage title
1970 public function getSkinFromCssJsSubpage() {
1971 $subpage = explode( '/', $this->mTextform );
1972 $subpage = $subpage[ count( $subpage ) - 1 ];
1973 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1977 * Is this a .css subpage of a user page?
1979 * @return \type{\bool}
1981 public function isCssSubpage() {
1982 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1986 * Is this a .js subpage of a user page?
1988 * @return \type{\bool}
1990 public function isJsSubpage() {
1991 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1995 * Protect css subpages of user pages: can $wgUser edit
1996 * this page?
1998 * @return \type{\bool}
1999 * @todo XXX: this might be better using restrictions
2001 public function userCanEditCssSubpage() {
2002 global $wgUser;
2003 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
2004 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2008 * Protect js subpages of user pages: can $wgUser edit
2009 * this page?
2011 * @return \type{\bool}
2012 * @todo XXX: this might be better using restrictions
2014 public function userCanEditJsSubpage() {
2015 global $wgUser;
2016 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
2017 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2021 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2023 * @return \type{\bool} If the page is subject to cascading restrictions.
2025 public function isCascadeProtected() {
2026 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2027 return ( $sources > 0 );
2031 * Cascading protection: Get the source of any cascading restrictions on this page.
2033 * @param $getPages \type{\bool} Whether or not to retrieve the actual pages
2034 * that the restrictions have come from.
2035 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
2036 * objects of the pages from which cascading restrictions have come,
2037 * false for none, or true if such restrictions exist, but $getPages was not set.
2038 * The restriction array is an array of each type, each of which contains a
2039 * array of unique groups.
2041 public function getCascadeProtectionSources( $getPages = true ) {
2042 $pagerestrictions = array();
2044 if ( isset( $this->mCascadeSources ) && $getPages ) {
2045 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2046 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2047 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2050 wfProfileIn( __METHOD__ );
2052 $dbr = wfGetDB( DB_SLAVE );
2054 if ( $this->getNamespace() == NS_FILE ) {
2055 $tables = array( 'imagelinks', 'page_restrictions' );
2056 $where_clauses = array(
2057 'il_to' => $this->getDBkey(),
2058 'il_from=pr_page',
2059 'pr_cascade' => 1
2061 } else {
2062 $tables = array( 'templatelinks', 'page_restrictions' );
2063 $where_clauses = array(
2064 'tl_namespace' => $this->getNamespace(),
2065 'tl_title' => $this->getDBkey(),
2066 'tl_from=pr_page',
2067 'pr_cascade' => 1
2071 if ( $getPages ) {
2072 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2073 'pr_expiry', 'pr_type', 'pr_level' );
2074 $where_clauses[] = 'page_id=pr_page';
2075 $tables[] = 'page';
2076 } else {
2077 $cols = array( 'pr_expiry' );
2080 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2082 $sources = $getPages ? array() : false;
2083 $now = wfTimestampNow();
2084 $purgeExpired = false;
2086 foreach ( $res as $row ) {
2087 $expiry = Block::decodeExpiry( $row->pr_expiry );
2088 if ( $expiry > $now ) {
2089 if ( $getPages ) {
2090 $page_id = $row->pr_page;
2091 $page_ns = $row->page_namespace;
2092 $page_title = $row->page_title;
2093 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2094 # Add groups needed for each restriction type if its not already there
2095 # Make sure this restriction type still exists
2097 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2098 $pagerestrictions[$row->pr_type] = array();
2101 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2102 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2103 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2105 } else {
2106 $sources = true;
2108 } else {
2109 // Trigger lazy purge of expired restrictions from the db
2110 $purgeExpired = true;
2113 if ( $purgeExpired ) {
2114 Title::purgeExpiredRestrictions();
2115 $this->invalidateTitleProtectionCache();
2118 wfProfileOut( __METHOD__ );
2120 if ( $getPages ) {
2121 $this->mCascadeSources = $sources;
2122 $this->mCascadingRestrictions = $pagerestrictions;
2123 } else {
2124 $this->mHasCascadingRestrictions = $sources;
2127 return array( $sources, $pagerestrictions );
2131 * Returns cascading restrictions for the current article
2133 * @return Boolean
2135 function areRestrictionsCascading() {
2136 if ( !$this->mRestrictionsLoaded ) {
2137 $this->loadRestrictions();
2140 return $this->mCascadeRestriction;
2144 * Loads a string into mRestrictions array
2146 * @param $res \type{Resource} restrictions as an SQL result.
2147 * @param $oldFashionedRestrictions string comma-separated list of page
2148 * restrictions from page table (pre 1.10)
2150 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2151 $rows = array();
2153 foreach ( $res as $row ) {
2154 $rows[] = $row;
2157 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2161 * Compiles list of active page restrictions from both page table (pre 1.10)
2162 * and page_restrictions table
2164 * @param $rows array of db result objects
2165 * @param $oldFashionedRestrictions string comma-separated list of page
2166 * restrictions from page table (pre 1.10)
2168 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2169 $dbr = wfGetDB( DB_SLAVE );
2171 $restrictionTypes = $this->getRestrictionTypes();
2173 foreach ( $restrictionTypes as $type ) {
2174 $this->mRestrictions[$type] = array();
2175 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry( '' );
2178 $this->mCascadeRestriction = false;
2180 # Backwards-compatibility: also load the restrictions from the page record (old format).
2182 if ( $oldFashionedRestrictions === null ) {
2183 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2184 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2187 if ( $oldFashionedRestrictions != '' ) {
2189 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2190 $temp = explode( '=', trim( $restrict ) );
2191 if ( count( $temp ) == 1 ) {
2192 // old old format should be treated as edit/move restriction
2193 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2194 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2195 } else {
2196 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2200 $this->mOldRestrictions = true;
2204 if ( count( $rows ) ) {
2205 # Current system - load second to make them override.
2206 $now = wfTimestampNow();
2207 $purgeExpired = false;
2209 foreach ( $rows as $row ) {
2210 # Cycle through all the restrictions.
2212 // Don't take care of restrictions types that aren't allowed
2214 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2215 continue;
2217 // This code should be refactored, now that it's being used more generally,
2218 // But I don't really see any harm in leaving it in Block for now -werdna
2219 $expiry = Block::decodeExpiry( $row->pr_expiry );
2221 // Only apply the restrictions if they haven't expired!
2222 if ( !$expiry || $expiry > $now ) {
2223 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2224 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2226 $this->mCascadeRestriction |= $row->pr_cascade;
2227 } else {
2228 // Trigger a lazy purge of expired restrictions
2229 $purgeExpired = true;
2233 if ( $purgeExpired ) {
2234 Title::purgeExpiredRestrictions();
2235 $this->invalidateTitleProtectionCache();
2239 $this->mRestrictionsLoaded = true;
2243 * Load restrictions from the page_restrictions table
2245 * @param $oldFashionedRestrictions string comma-separated list of page
2246 * restrictions from page table (pre 1.10)
2248 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2249 if ( !$this->mRestrictionsLoaded ) {
2250 if ( $this->exists() ) {
2251 $dbr = wfGetDB( DB_SLAVE );
2253 $res = $dbr->select( 'page_restrictions', '*',
2254 array( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2256 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2257 } else {
2258 $title_protection = $this->getTitleProtection();
2260 if ( $title_protection ) {
2261 $now = wfTimestampNow();
2262 $expiry = Block::decodeExpiry( $title_protection['pt_expiry'] );
2264 if ( !$expiry || $expiry > $now ) {
2265 // Apply the restrictions
2266 $this->mRestrictionsExpiry['create'] = $expiry;
2267 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2268 } else { // Get rid of the old restrictions
2269 Title::purgeExpiredRestrictions();
2270 $this->invalidateTitleProtectionCache();
2272 } else {
2273 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry( '' );
2275 $this->mRestrictionsLoaded = true;
2281 * Purge expired restrictions from the page_restrictions table
2283 static function purgeExpiredRestrictions() {
2284 $dbw = wfGetDB( DB_MASTER );
2285 $dbw->delete(
2286 'page_restrictions',
2287 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2288 __METHOD__
2291 $dbw->delete(
2292 'protected_titles',
2293 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2294 __METHOD__
2299 * Accessor/initialisation for mRestrictions
2301 * @param $action \type{\string} action that permission needs to be checked for
2302 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2304 public function getRestrictions( $action ) {
2305 if ( !$this->mRestrictionsLoaded ) {
2306 $this->loadRestrictions();
2308 return isset( $this->mRestrictions[$action] )
2309 ? $this->mRestrictions[$action]
2310 : array();
2314 * Get the expiry time for the restriction against a given action
2316 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2317 * or not protected at all, or false if the action is not recognised.
2319 public function getRestrictionExpiry( $action ) {
2320 if ( !$this->mRestrictionsLoaded ) {
2321 $this->loadRestrictions();
2323 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2327 * Is there a version of this page in the deletion archive?
2329 * @return \type{\int} the number of archived revisions
2331 public function isDeleted() {
2332 if ( $this->getNamespace() < 0 ) {
2333 $n = 0;
2334 } else {
2335 $dbr = wfGetDB( DB_SLAVE );
2336 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2337 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2338 __METHOD__
2340 if ( $this->getNamespace() == NS_FILE ) {
2341 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2342 array( 'fa_name' => $this->getDBkey() ),
2343 __METHOD__
2347 return (int)$n;
2351 * Is there a version of this page in the deletion archive?
2353 * @return Boolean
2355 public function isDeletedQuick() {
2356 if ( $this->getNamespace() < 0 ) {
2357 return false;
2359 $dbr = wfGetDB( DB_SLAVE );
2360 $deleted = (bool)$dbr->selectField( 'archive', '1',
2361 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2362 __METHOD__
2364 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2365 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2366 array( 'fa_name' => $this->getDBkey() ),
2367 __METHOD__
2370 return $deleted;
2374 * Get the article ID for this Title from the link cache,
2375 * adding it if necessary
2377 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select
2378 * for update
2379 * @return \type{\int} the ID
2381 public function getArticleID( $flags = 0 ) {
2382 if ( $this->getNamespace() < 0 ) {
2383 return $this->mArticleID = 0;
2385 $linkCache = LinkCache::singleton();
2386 if ( $flags & self::GAID_FOR_UPDATE ) {
2387 $oldUpdate = $linkCache->forUpdate( true );
2388 $linkCache->clearLink( $this );
2389 $this->mArticleID = $linkCache->addLinkObj( $this );
2390 $linkCache->forUpdate( $oldUpdate );
2391 } else {
2392 if ( -1 == $this->mArticleID ) {
2393 $this->mArticleID = $linkCache->addLinkObj( $this );
2396 return $this->mArticleID;
2400 * Is this an article that is a redirect page?
2401 * Uses link cache, adding it if necessary
2403 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2404 * @return \type{\bool}
2406 public function isRedirect( $flags = 0 ) {
2407 if ( !is_null( $this->mRedirect ) ) {
2408 return $this->mRedirect;
2410 # Calling getArticleID() loads the field from cache as needed
2411 if ( !$this->getArticleID( $flags ) ) {
2412 return $this->mRedirect = false;
2414 $linkCache = LinkCache::singleton();
2415 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2417 return $this->mRedirect;
2421 * What is the length of this page?
2422 * Uses link cache, adding it if necessary
2424 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2425 * @return \type{\int}
2427 public function getLength( $flags = 0 ) {
2428 if ( $this->mLength != -1 ) {
2429 return $this->mLength;
2431 # Calling getArticleID() loads the field from cache as needed
2432 if ( !$this->getArticleID( $flags ) ) {
2433 return $this->mLength = 0;
2435 $linkCache = LinkCache::singleton();
2436 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2438 return $this->mLength;
2442 * What is the page_latest field for this page?
2444 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2445 * @return \type{\int} or 0 if the page doesn't exist
2447 public function getLatestRevID( $flags = 0 ) {
2448 if ( $this->mLatestID !== false ) {
2449 return intval( $this->mLatestID );
2451 # Calling getArticleID() loads the field from cache as needed
2452 if ( !$this->getArticleID( $flags ) ) {
2453 return $this->mLatestID = 0;
2455 $linkCache = LinkCache::singleton();
2456 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2458 return $this->mLatestID;
2462 * This clears some fields in this object, and clears any associated
2463 * keys in the "bad links" section of the link cache.
2465 * - This is called from Article::doEdit() and Article::insertOn() to allow
2466 * loading of the new page_id. It's also called from
2467 * Article::doDeleteArticle()
2469 * @param $newid \type{\int} the new Article ID
2471 public function resetArticleID( $newid ) {
2472 $linkCache = LinkCache::singleton();
2473 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2475 if ( $newid === false ) {
2476 $this->mArticleID = -1;
2477 } else {
2478 $this->mArticleID = intval( $newid );
2480 $this->mRestrictionsLoaded = false;
2481 $this->mRestrictions = array();
2482 $this->mRedirect = null;
2483 $this->mLength = -1;
2484 $this->mLatestID = false;
2488 * Updates page_touched for this page; called from LinksUpdate.php
2490 * @return \type{\bool} true if the update succeded
2492 public function invalidateCache() {
2493 if ( wfReadOnly() ) {
2494 return;
2496 $dbw = wfGetDB( DB_MASTER );
2497 $success = $dbw->update(
2498 'page',
2499 array( 'page_touched' => $dbw->timestamp() ),
2500 $this->pageCond(),
2501 __METHOD__
2503 HTMLFileCache::clearFileCache( $this );
2504 return $success;
2508 * Prefix some arbitrary text with the namespace or interwiki prefix
2509 * of this object
2511 * @param $name \type{\string} the text
2512 * @return \type{\string} the prefixed text
2513 * @private
2515 /* private */ function prefix( $name ) {
2516 $p = '';
2517 if ( $this->mInterwiki != '' ) {
2518 $p = $this->mInterwiki . ':';
2520 if ( 0 != $this->mNamespace ) {
2521 $p .= $this->getNsText() . ':';
2523 return $p . $name;
2527 * Returns a simple regex that will match on characters and sequences invalid in titles.
2528 * Note that this doesn't pick up many things that could be wrong with titles, but that
2529 * replacing this regex with something valid will make many titles valid.
2531 * @return string regex string
2533 static function getTitleInvalidRegex() {
2534 static $rxTc = false;
2535 if ( !$rxTc ) {
2536 # Matching titles will be held as illegal.
2537 $rxTc = '/' .
2538 # Any character not allowed is forbidden...
2539 '[^' . Title::legalChars() . ']' .
2540 # URL percent encoding sequences interfere with the ability
2541 # to round-trip titles -- you can't link to them consistently.
2542 '|%[0-9A-Fa-f]{2}' .
2543 # XML/HTML character references produce similar issues.
2544 '|&[A-Za-z0-9\x80-\xff]+;' .
2545 '|&#[0-9]+;' .
2546 '|&#x[0-9A-Fa-f]+;' .
2547 '/S';
2550 return $rxTc;
2554 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2556 * @param $text string containing title to capitalize
2557 * @param $ns int namespace index, defaults to NS_MAIN
2558 * @return String containing capitalized title
2560 public static function capitalize( $text, $ns = NS_MAIN ) {
2561 global $wgContLang;
2563 if ( MWNamespace::isCapitalized( $ns ) ) {
2564 return $wgContLang->ucfirst( $text );
2565 } else {
2566 return $text;
2571 * Secure and split - main initialisation function for this object
2573 * Assumes that mDbkeyform has been set, and is urldecoded
2574 * and uses underscores, but not otherwise munged. This function
2575 * removes illegal characters, splits off the interwiki and
2576 * namespace prefixes, sets the other forms, and canonicalizes
2577 * everything.
2579 * @return \type{\bool} true on success
2581 private function secureAndSplit() {
2582 global $wgContLang, $wgLocalInterwiki;
2584 # Initialisation
2585 $rxTc = self::getTitleInvalidRegex();
2587 $this->mInterwiki = $this->mFragment = '';
2588 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2590 $dbkey = $this->mDbkeyform;
2592 # Strip Unicode bidi override characters.
2593 # Sometimes they slip into cut-n-pasted page titles, where the
2594 # override chars get included in list displays.
2595 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2597 # Clean up whitespace
2598 # Note: use of the /u option on preg_replace here will cause
2599 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2600 # conveniently disabling them.
2602 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2603 $dbkey = trim( $dbkey, '_' );
2605 if ( $dbkey == '' ) {
2606 return false;
2609 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2610 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2611 return false;
2614 $this->mDbkeyform = $dbkey;
2616 # Initial colon indicates main namespace rather than specified default
2617 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2618 if ( ':' == $dbkey { 0 } ) {
2619 $this->mNamespace = NS_MAIN;
2620 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2621 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2624 # Namespace or interwiki prefix
2625 $firstPass = true;
2626 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2627 do {
2628 $m = array();
2629 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2630 $p = $m[1];
2631 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2632 # Ordinary namespace
2633 $dbkey = $m[2];
2634 $this->mNamespace = $ns;
2635 # For Talk:X pages, check if X has a "namespace" prefix
2636 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2637 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2638 return false; # Disallow Talk:File:x type titles...
2639 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2640 return false; # Disallow Talk:Interwiki:x type titles...
2643 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2644 if ( !$firstPass ) {
2645 # Can't make a local interwiki link to an interwiki link.
2646 # That's just crazy!
2647 return false;
2650 # Interwiki link
2651 $dbkey = $m[2];
2652 $this->mInterwiki = $wgContLang->lc( $p );
2654 # Redundant interwiki prefix to the local wiki
2655 if ( $wgLocalInterwiki !== false
2656 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2658 if ( $dbkey == '' ) {
2659 # Can't have an empty self-link
2660 return false;
2662 $this->mInterwiki = '';
2663 $firstPass = false;
2664 # Do another namespace split...
2665 continue;
2668 # If there's an initial colon after the interwiki, that also
2669 # resets the default namespace
2670 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2671 $this->mNamespace = NS_MAIN;
2672 $dbkey = substr( $dbkey, 1 );
2675 # If there's no recognized interwiki or namespace,
2676 # then let the colon expression be part of the title.
2678 break;
2679 } while ( true );
2681 # We already know that some pages won't be in the database!
2683 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2684 $this->mArticleID = 0;
2686 $fragment = strstr( $dbkey, '#' );
2687 if ( false !== $fragment ) {
2688 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2689 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2690 # remove whitespace again: prevents "Foo_bar_#"
2691 # becoming "Foo_bar_"
2692 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2695 # Reject illegal characters.
2697 if ( preg_match( $rxTc, $dbkey ) ) {
2698 return false;
2702 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2703 * reachable due to the way web browsers deal with 'relative' URLs.
2704 * Also, they conflict with subpage syntax. Forbid them explicitly.
2706 if ( strpos( $dbkey, '.' ) !== false &&
2707 ( $dbkey === '.' || $dbkey === '..' ||
2708 strpos( $dbkey, './' ) === 0 ||
2709 strpos( $dbkey, '../' ) === 0 ||
2710 strpos( $dbkey, '/./' ) !== false ||
2711 strpos( $dbkey, '/../' ) !== false ||
2712 substr( $dbkey, -2 ) == '/.' ||
2713 substr( $dbkey, -3 ) == '/..' ) )
2715 return false;
2719 * Magic tilde sequences? Nu-uh!
2721 if ( strpos( $dbkey, '~~~' ) !== false ) {
2722 return false;
2726 * Limit the size of titles to 255 bytes.
2727 * This is typically the size of the underlying database field.
2728 * We make an exception for special pages, which don't need to be stored
2729 * in the database, and may edge over 255 bytes due to subpage syntax
2730 * for long titles, e.g. [[Special:Block/Long name]]
2732 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2733 strlen( $dbkey ) > 512 )
2735 return false;
2739 * Normally, all wiki links are forced to have
2740 * an initial capital letter so [[foo]] and [[Foo]]
2741 * point to the same place.
2743 * Don't force it for interwikis, since the other
2744 * site might be case-sensitive.
2746 $this->mUserCaseDBKey = $dbkey;
2747 if ( $this->mInterwiki == '' ) {
2748 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2752 * Can't make a link to a namespace alone...
2753 * "empty" local links can only be self-links
2754 * with a fragment identifier.
2756 if ( $dbkey == '' &&
2757 $this->mInterwiki == '' &&
2758 $this->mNamespace != NS_MAIN ) {
2759 return false;
2761 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2762 // IP names are not allowed for accounts, and can only be referring to
2763 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2764 // there are numerous ways to present the same IP. Having sp:contribs scan
2765 // them all is silly and having some show the edits and others not is
2766 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2767 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK ) ?
2768 IP::sanitizeIP( $dbkey ) : $dbkey;
2769 // Any remaining initial :s are illegal.
2770 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2771 return false;
2774 # Fill fields
2775 $this->mDbkeyform = $dbkey;
2776 $this->mUrlform = wfUrlencode( $dbkey );
2778 $this->mTextform = str_replace( '_', ' ', $dbkey );
2780 return true;
2784 * Set the fragment for this title. Removes the first character from the
2785 * specified fragment before setting, so it assumes you're passing it with
2786 * an initial "#".
2788 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2789 * Still in active use privately.
2791 * @param $fragment \type{\string} text
2793 public function setFragment( $fragment ) {
2794 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2798 * Get a Title object associated with the talk page of this article
2800 * @return Title the object for the talk page
2802 public function getTalkPage() {
2803 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2807 * Get a title object associated with the subject page of this
2808 * talk page
2810 * @return Title the object for the subject page
2812 public function getSubjectPage() {
2813 // Is this the same title?
2814 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2815 if ( $this->getNamespace() == $subjectNS ) {
2816 return $this;
2818 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2822 * Get an array of Title objects linking to this Title
2823 * Also stores the IDs in the link cache.
2825 * WARNING: do not use this function on arbitrary user-supplied titles!
2826 * On heavily-used templates it will max out the memory.
2828 * @param $options Array: may be FOR UPDATE
2829 * @param $table String: table name
2830 * @param $prefix String: fields prefix
2831 * @return \type{\arrayof{Title}} the Title objects linking here
2833 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2834 $linkCache = LinkCache::singleton();
2836 if ( count( $options ) > 0 ) {
2837 $db = wfGetDB( DB_MASTER );
2838 } else {
2839 $db = wfGetDB( DB_SLAVE );
2842 $res = $db->select(
2843 array( 'page', $table ),
2844 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2845 array(
2846 "{$prefix}_from=page_id",
2847 "{$prefix}_namespace" => $this->getNamespace(),
2848 "{$prefix}_title" => $this->getDBkey() ),
2849 __METHOD__,
2850 $options
2853 $retVal = array();
2854 if ( $db->numRows( $res ) ) {
2855 foreach ( $res as $row ) {
2856 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2857 if ( $titleObj ) {
2858 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2859 $retVal[] = $titleObj;
2863 return $retVal;
2867 * Get an array of Title objects using this Title as a template
2868 * Also stores the IDs in the link cache.
2870 * WARNING: do not use this function on arbitrary user-supplied titles!
2871 * On heavily-used templates it will max out the memory.
2873 * @param $options Array: may be FOR UPDATE
2874 * @return \type{\arrayof{Title}} the Title objects linking here
2876 public function getTemplateLinksTo( $options = array() ) {
2877 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2881 * Get an array of Title objects referring to non-existent articles linked from this page
2883 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2884 * @return \type{\arrayof{Title}} the Title objects
2886 public function getBrokenLinksFrom() {
2887 if ( $this->getArticleId() == 0 ) {
2888 # All links from article ID 0 are false positives
2889 return array();
2892 $dbr = wfGetDB( DB_SLAVE );
2893 $res = $dbr->select(
2894 array( 'page', 'pagelinks' ),
2895 array( 'pl_namespace', 'pl_title' ),
2896 array(
2897 'pl_from' => $this->getArticleId(),
2898 'page_namespace IS NULL'
2900 __METHOD__, array(),
2901 array(
2902 'page' => array(
2903 'LEFT JOIN',
2904 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2909 $retVal = array();
2910 foreach ( $res as $row ) {
2911 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2913 return $retVal;
2918 * Get a list of URLs to purge from the Squid cache when this
2919 * page changes
2921 * @return \type{\arrayof{\string}} the URLs
2923 public function getSquidURLs() {
2924 global $wgContLang;
2926 $urls = array(
2927 $this->getInternalURL(),
2928 $this->getInternalURL( 'action=history' )
2931 // purge variant urls as well
2932 if ( $wgContLang->hasVariants() ) {
2933 $variants = $wgContLang->getVariants();
2934 foreach ( $variants as $vCode ) {
2935 $urls[] = $this->getInternalURL( '', $vCode );
2939 return $urls;
2943 * Purge all applicable Squid URLs
2945 public function purgeSquid() {
2946 global $wgUseSquid;
2947 if ( $wgUseSquid ) {
2948 $urls = $this->getSquidURLs();
2949 $u = new SquidUpdate( $urls );
2950 $u->doUpdate();
2955 * Move this page without authentication
2957 * @param $nt \type{Title} the new page Title
2958 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2960 public function moveNoAuth( &$nt ) {
2961 return $this->moveTo( $nt, false );
2965 * Check whether a given move operation would be valid.
2966 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2968 * @param $nt \type{Title} the new title
2969 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2970 * should be checked
2971 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2972 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2974 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2975 global $wgUser;
2977 $errors = array();
2978 if ( !$nt ) {
2979 // Normally we'd add this to $errors, but we'll get
2980 // lots of syntax errors if $nt is not an object
2981 return array( array( 'badtitletext' ) );
2983 if ( $this->equals( $nt ) ) {
2984 $errors[] = array( 'selfmove' );
2986 if ( !$this->isMovable() ) {
2987 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2989 if ( $nt->getInterwiki() != '' ) {
2990 $errors[] = array( 'immobile-target-namespace-iw' );
2992 if ( !$nt->isMovable() ) {
2993 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2996 $oldid = $this->getArticleID();
2997 $newid = $nt->getArticleID();
2999 if ( strlen( $nt->getDBkey() ) < 1 ) {
3000 $errors[] = array( 'articleexists' );
3002 if ( ( $this->getDBkey() == '' ) ||
3003 ( !$oldid ) ||
3004 ( $nt->getDBkey() == '' ) ) {
3005 $errors[] = array( 'badarticleerror' );
3008 // Image-specific checks
3009 if ( $this->getNamespace() == NS_FILE ) {
3010 if ( $nt->getNamespace() != NS_FILE ) {
3011 $errors[] = array( 'imagenocrossnamespace' );
3013 $file = wfLocalFile( $this );
3014 if ( $file->exists() ) {
3015 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3016 $errors[] = array( 'imageinvalidfilename' );
3018 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3019 $errors[] = array( 'imagetypemismatch' );
3022 $destfile = wfLocalFile( $nt );
3023 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
3024 $errors[] = array( 'file-exists-sharedrepo' );
3028 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3029 $errors[] = array( 'nonfile-cannot-move-to-file' );
3032 if ( $auth ) {
3033 $errors = wfMergeErrorArrays( $errors,
3034 $this->getUserPermissionsErrors( 'move', $wgUser ),
3035 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3036 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3037 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3040 $match = EditPage::matchSummarySpamRegex( $reason );
3041 if ( $match !== false ) {
3042 // This is kind of lame, won't display nice
3043 $errors[] = array( 'spamprotectiontext' );
3046 $err = null;
3047 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3048 $errors[] = array( 'hookaborted', $err );
3051 # The move is allowed only if (1) the target doesn't exist, or
3052 # (2) the target is a redirect to the source, and has no history
3053 # (so we can undo bad moves right after they're done).
3055 if ( 0 != $newid ) { # Target exists; check for validity
3056 if ( !$this->isValidMoveTarget( $nt ) ) {
3057 $errors[] = array( 'articleexists' );
3059 } else {
3060 $tp = $nt->getTitleProtection();
3061 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3062 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3063 $errors[] = array( 'cantmove-titleprotected' );
3066 if ( empty( $errors ) ) {
3067 return true;
3069 return $errors;
3073 * Move a title to a new location
3075 * @param $nt \type{Title} the new title
3076 * @param $auth \type{\bool} indicates whether $wgUser's permissions
3077 * should be checked
3078 * @param $reason \type{\string} The reason for the move
3079 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
3080 * Ignored if the user doesn't have the suppressredirect right.
3081 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
3083 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3084 global $wgContLang;
3086 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3087 if ( is_array( $err ) ) {
3088 return $err;
3091 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
3092 $dbw = wfGetDB( DB_MASTER );
3093 if ( $this->getNamespace() == NS_FILE ) {
3094 $file = wfLocalFile( $this );
3095 if ( $file->exists() ) {
3096 $status = $file->move( $nt );
3097 if ( !$status->isOk() ) {
3098 return $status->getErrorsArray();
3103 $pageid = $this->getArticleID();
3104 $protected = $this->isProtected();
3105 if ( $nt->exists() ) {
3106 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
3107 $pageCountChange = ( $createRedirect ? 0 : -1 );
3108 } else { # Target didn't exist, do normal move.
3109 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
3110 $pageCountChange = ( $createRedirect ? 1 : 0 );
3113 if ( is_array( $err ) ) {
3114 return $err;
3116 $redirid = $this->getArticleID();
3118 // Refresh the sortkey for this row. Be careful to avoid resetting
3119 // cl_timestamp, which may disturb time-based lists on some sites.
3120 $prefix = $dbw->selectField(
3121 'categorylinks',
3122 'cl_sortkey_prefix',
3123 array( 'cl_from' => $pageid ),
3124 __METHOD__
3126 $dbw->update( 'categorylinks',
3127 array(
3128 'cl_sortkey' => $wgContLang->convertToSortkey( $nt->getCategorySortkey( $prefix ) ),
3129 'cl_timestamp=cl_timestamp' ),
3130 array( 'cl_from' => $pageid ),
3131 __METHOD__ );
3133 if ( $protected ) {
3134 # Protect the redirect title as the title used to be...
3135 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3136 array(
3137 'pr_page' => $redirid,
3138 'pr_type' => 'pr_type',
3139 'pr_level' => 'pr_level',
3140 'pr_cascade' => 'pr_cascade',
3141 'pr_user' => 'pr_user',
3142 'pr_expiry' => 'pr_expiry'
3144 array( 'pr_page' => $pageid ),
3145 __METHOD__,
3146 array( 'IGNORE' )
3148 # Update the protection log
3149 $log = new LogPage( 'protect' );
3150 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3151 if ( $reason ) {
3152 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3154 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3157 # Update watchlists
3158 $oldnamespace = $this->getNamespace() & ~1;
3159 $newnamespace = $nt->getNamespace() & ~1;
3160 $oldtitle = $this->getDBkey();
3161 $newtitle = $nt->getDBkey();
3163 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3164 WatchedItem::duplicateEntries( $this, $nt );
3167 # Update search engine
3168 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3169 $u->doUpdate();
3170 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3171 $u->doUpdate();
3173 # Update site_stats
3174 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3175 # No longer a content page
3176 # Not viewed, edited, removing
3177 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3178 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3179 # Now a content page
3180 # Not viewed, edited, adding
3181 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3182 } elseif ( $pageCountChange ) {
3183 # Redirect added
3184 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3185 } else {
3186 # Nothing special
3187 $u = false;
3189 if ( $u ) {
3190 $u->doUpdate();
3192 # Update message cache for interface messages
3193 global $wgMessageCache;
3194 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3195 # @bug 17860: old article can be deleted, if this the case,
3196 # delete it from message cache
3197 if ( $this->getArticleID() === 0 ) {
3198 $wgMessageCache->replace( $this->getDBkey(), false );
3199 } else {
3200 $oldarticle = new Article( $this );
3201 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3204 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3205 $newarticle = new Article( $nt );
3206 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3209 global $wgUser;
3210 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3211 return true;
3215 * Move page to a title which is at present a redirect to the
3216 * source page
3218 * @param $nt \type{Title} the page to move to, which should currently
3219 * be a redirect
3220 * @param $reason \type{\string} The reason for the move
3221 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3222 * Ignored if the user doesn't have the suppressredirect right
3224 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3225 global $wgUseSquid, $wgUser, $wgContLang;
3227 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3229 if ( $reason ) {
3230 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3232 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3233 $comment = $wgContLang->truncate( $comment, 250 );
3235 $now = wfTimestampNow();
3236 $newid = $nt->getArticleID();
3237 $oldid = $this->getArticleID();
3238 $latest = $this->getLatestRevID();
3240 $dbw = wfGetDB( DB_MASTER );
3242 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3243 $newns = $nt->getNamespace();
3244 $newdbk = $nt->getDBkey();
3246 # Delete the old redirect. We don't save it to history since
3247 # by definition if we've got here it's rather uninteresting.
3248 # We have to remove it so that the next step doesn't trigger
3249 # a conflict on the unique namespace+title index...
3250 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3251 if ( !$dbw->cascadingDeletes() ) {
3252 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3253 global $wgUseTrackbacks;
3254 if ( $wgUseTrackbacks ) {
3255 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3257 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3258 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3259 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3260 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3261 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3262 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3263 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3265 // If the redirect was recently created, it may have an entry in recentchanges still
3266 $dbw->delete( 'recentchanges',
3267 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3268 __METHOD__
3271 # Save a null revision in the page's history notifying of the move
3272 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3273 $nullRevId = $nullRevision->insertOn( $dbw );
3275 $article = new Article( $this );
3276 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3278 # Change the name of the target page:
3279 $dbw->update( 'page',
3280 /* SET */ array(
3281 'page_touched' => $dbw->timestamp( $now ),
3282 'page_namespace' => $nt->getNamespace(),
3283 'page_title' => $nt->getDBkey(),
3284 'page_latest' => $nullRevId,
3286 /* WHERE */ array( 'page_id' => $oldid ),
3287 __METHOD__
3289 $nt->resetArticleID( $oldid );
3291 # Recreate the redirect, this time in the other direction.
3292 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3293 $mwRedir = MagicWord::get( 'redirect' );
3294 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3295 $redirectArticle = new Article( $this );
3296 $newid = $redirectArticle->insertOn( $dbw );
3297 $redirectRevision = new Revision( array(
3298 'page' => $newid,
3299 'comment' => $comment,
3300 'text' => $redirectText ) );
3301 $redirectRevision->insertOn( $dbw );
3302 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3304 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3306 # Now, we record the link from the redirect to the new title.
3307 # It should have no other outgoing links...
3308 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3309 $dbw->insert( 'pagelinks',
3310 array(
3311 'pl_from' => $newid,
3312 'pl_namespace' => $nt->getNamespace(),
3313 'pl_title' => $nt->getDBkey() ),
3314 __METHOD__ );
3315 $redirectSuppressed = false;
3316 } else {
3317 $this->resetArticleID( 0 );
3318 $redirectSuppressed = true;
3321 # Log the move
3322 $log = new LogPage( 'move' );
3323 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3325 # Purge squid
3326 if ( $wgUseSquid ) {
3327 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3328 $u = new SquidUpdate( $urls );
3329 $u->doUpdate();
3335 * Move page to non-existing title.
3337 * @param $nt \type{Title} the new Title
3338 * @param $reason \type{\string} The reason for the move
3339 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3340 * Ignored if the user doesn't have the suppressredirect right
3342 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3343 global $wgUser, $wgContLang;
3345 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3346 if ( $reason ) {
3347 $comment .= wfMsgExt( 'colon-separator',
3348 array( 'escapenoentities', 'content' ) );
3349 $comment .= $reason;
3351 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3352 $comment = $wgContLang->truncate( $comment, 250 );
3354 $oldid = $this->getArticleID();
3355 $latest = $this->getLatestRevId();
3357 $dbw = wfGetDB( DB_MASTER );
3358 $now = $dbw->timestamp();
3360 # Save a null revision in the page's history notifying of the move
3361 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3362 if ( !is_object( $nullRevision ) ) {
3363 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3365 $nullRevId = $nullRevision->insertOn( $dbw );
3367 $article = new Article( $this );
3368 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3370 # Rename page entry
3371 $dbw->update( 'page',
3372 /* SET */ array(
3373 'page_touched' => $now,
3374 'page_namespace' => $nt->getNamespace(),
3375 'page_title' => $nt->getDBkey(),
3376 'page_latest' => $nullRevId,
3378 /* WHERE */ array( 'page_id' => $oldid ),
3379 __METHOD__
3381 $nt->resetArticleID( $oldid );
3383 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3384 # Insert redirect
3385 $mwRedir = MagicWord::get( 'redirect' );
3386 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3387 $redirectArticle = new Article( $this );
3388 $newid = $redirectArticle->insertOn( $dbw );
3389 $redirectRevision = new Revision( array(
3390 'page' => $newid,
3391 'comment' => $comment,
3392 'text' => $redirectText ) );
3393 $redirectRevision->insertOn( $dbw );
3394 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3396 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3398 # Record the just-created redirect's linking to the page
3399 $dbw->insert( 'pagelinks',
3400 array(
3401 'pl_from' => $newid,
3402 'pl_namespace' => $nt->getNamespace(),
3403 'pl_title' => $nt->getDBkey() ),
3404 __METHOD__ );
3405 $redirectSuppressed = false;
3406 } else {
3407 $this->resetArticleID( 0 );
3408 $redirectSuppressed = true;
3411 # Log the move
3412 $log = new LogPage( 'move' );
3413 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3415 # Purge caches as per article creation
3416 Article::onArticleCreate( $nt );
3418 # Purge old title from squid
3419 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3420 $this->purgeSquid();
3424 * Move this page's subpages to be subpages of $nt
3426 * @param $nt Title Move target
3427 * @param $auth bool Whether $wgUser's permissions should be checked
3428 * @param $reason string The reason for the move
3429 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3430 * Ignored if the user doesn't have the 'suppressredirect' right
3431 * @return mixed array with old page titles as keys, and strings (new page titles) or
3432 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3434 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3435 global $wgMaximumMovedPages;
3436 // Check permissions
3437 if ( !$this->userCan( 'move-subpages' ) ) {
3438 return array( 'cant-move-subpages' );
3440 // Do the source and target namespaces support subpages?
3441 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3442 return array( 'namespace-nosubpages',
3443 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3445 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3446 return array( 'namespace-nosubpages',
3447 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3450 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3451 $retval = array();
3452 $count = 0;
3453 foreach ( $subpages as $oldSubpage ) {
3454 $count++;
3455 if ( $count > $wgMaximumMovedPages ) {
3456 $retval[$oldSubpage->getPrefixedTitle()] =
3457 array( 'movepage-max-pages',
3458 $wgMaximumMovedPages );
3459 break;
3462 // We don't know whether this function was called before
3463 // or after moving the root page, so check both
3464 // $this and $nt
3465 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3466 $oldSubpage->getArticleID() == $nt->getArticleId() )
3468 // When moving a page to a subpage of itself,
3469 // don't move it twice
3470 continue;
3472 $newPageName = preg_replace(
3473 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3474 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3475 $oldSubpage->getDBkey() );
3476 if ( $oldSubpage->isTalkPage() ) {
3477 $newNs = $nt->getTalkPage()->getNamespace();
3478 } else {
3479 $newNs = $nt->getSubjectPage()->getNamespace();
3481 # Bug 14385: we need makeTitleSafe because the new page names may
3482 # be longer than 255 characters.
3483 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3485 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3486 if ( $success === true ) {
3487 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3488 } else {
3489 $retval[$oldSubpage->getPrefixedText()] = $success;
3492 return $retval;
3496 * Checks if this page is just a one-rev redirect.
3497 * Adds lock, so don't use just for light purposes.
3499 * @return \type{\bool}
3501 public function isSingleRevRedirect() {
3502 $dbw = wfGetDB( DB_MASTER );
3503 # Is it a redirect?
3504 $row = $dbw->selectRow( 'page',
3505 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3506 $this->pageCond(),
3507 __METHOD__,
3508 array( 'FOR UPDATE' )
3510 # Cache some fields we may want
3511 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3512 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3513 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3514 if ( !$this->mRedirect ) {
3515 return false;
3517 # Does the article have a history?
3518 $row = $dbw->selectField( array( 'page', 'revision' ),
3519 'rev_id',
3520 array( 'page_namespace' => $this->getNamespace(),
3521 'page_title' => $this->getDBkey(),
3522 'page_id=rev_page',
3523 'page_latest != rev_id'
3525 __METHOD__,
3526 array( 'FOR UPDATE' )
3528 # Return true if there was no history
3529 return ( $row === false );
3533 * Checks if $this can be moved to a given Title
3534 * - Selects for update, so don't call it unless you mean business
3536 * @param $nt \type{Title} the new title to check
3537 * @return \type{\bool} TRUE or FALSE
3539 public function isValidMoveTarget( $nt ) {
3540 # Is it an existing file?
3541 if ( $nt->getNamespace() == NS_FILE ) {
3542 $file = wfLocalFile( $nt );
3543 if ( $file->exists() ) {
3544 wfDebug( __METHOD__ . ": file exists\n" );
3545 return false;
3548 # Is it a redirect with no history?
3549 if ( !$nt->isSingleRevRedirect() ) {
3550 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3551 return false;
3553 # Get the article text
3554 $rev = Revision::newFromTitle( $nt );
3555 $text = $rev->getText();
3556 # Does the redirect point to the source?
3557 # Or is it a broken self-redirect, usually caused by namespace collisions?
3558 $m = array();
3559 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3560 $redirTitle = Title::newFromText( $m[1] );
3561 if ( !is_object( $redirTitle ) ||
3562 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3563 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3564 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3565 return false;
3567 } else {
3568 # Fail safe
3569 wfDebug( __METHOD__ . ": failsafe\n" );
3570 return false;
3572 return true;
3576 * Can this title be added to a user's watchlist?
3578 * @return \type{\bool} TRUE or FALSE
3580 public function isWatchable() {
3581 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3585 * Get categories to which this Title belongs and return an array of
3586 * categories' names.
3588 * @return \type{\array} array an array of parents in the form:
3589 * $parent => $currentarticle
3591 public function getParentCategories() {
3592 global $wgContLang;
3594 $titlekey = $this->getArticleId();
3595 $dbr = wfGetDB( DB_SLAVE );
3596 $categorylinks = $dbr->tableName( 'categorylinks' );
3598 # NEW SQL
3599 $sql = "SELECT * FROM $categorylinks"
3600 . " WHERE cl_from='$titlekey'"
3601 . " AND cl_from <> '0'"
3602 . " ORDER BY cl_sortkey";
3604 $res = $dbr->query( $sql );
3605 $data = array();
3607 if ( $dbr->numRows( $res ) > 0 ) {
3608 foreach ( $res as $row ) {
3609 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3610 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3613 return $data;
3617 * Get a tree of parent categories
3619 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3620 * @return \type{\array} Tree of parent categories
3622 public function getParentCategoryTree( $children = array() ) {
3623 $stack = array();
3624 $parents = $this->getParentCategories();
3626 if ( $parents ) {
3627 foreach ( $parents as $parent => $current ) {
3628 if ( array_key_exists( $parent, $children ) ) {
3629 # Circular reference
3630 $stack[$parent] = array();
3631 } else {
3632 $nt = Title::newFromText( $parent );
3633 if ( $nt ) {
3634 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3640 return $stack;
3645 * Get an associative array for selecting this title from
3646 * the "page" table
3648 * @return \type{\array} Selection array
3650 public function pageCond() {
3651 if ( $this->mArticleID > 0 ) {
3652 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3653 return array( 'page_id' => $this->mArticleID );
3654 } else {
3655 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3660 * Get the revision ID of the previous revision
3662 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3663 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3664 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3666 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3667 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3668 return $db->selectField( 'revision', 'rev_id',
3669 array(
3670 'rev_page' => $this->getArticleId( $flags ),
3671 'rev_id < ' . intval( $revId )
3673 __METHOD__,
3674 array( 'ORDER BY' => 'rev_id DESC' )
3679 * Get the revision ID of the next revision
3681 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3682 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3683 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3685 public function getNextRevisionID( $revId, $flags = 0 ) {
3686 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3687 return $db->selectField( 'revision', 'rev_id',
3688 array(
3689 'rev_page' => $this->getArticleId( $flags ),
3690 'rev_id > ' . intval( $revId )
3692 __METHOD__,
3693 array( 'ORDER BY' => 'rev_id' )
3698 * Get the first revision of the page
3700 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3701 * @return Revision (or NULL if page doesn't exist)
3703 public function getFirstRevision( $flags = 0 ) {
3704 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3705 $pageId = $this->getArticleId( $flags );
3706 if ( !$pageId ) {
3707 return null;
3709 $row = $db->selectRow( 'revision', '*',
3710 array( 'rev_page' => $pageId ),
3711 __METHOD__,
3712 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3714 if ( !$row ) {
3715 return null;
3716 } else {
3717 return new Revision( $row );
3722 * Check if this is a new page
3724 * @return bool
3726 public function isNewPage() {
3727 $dbr = wfGetDB( DB_SLAVE );
3728 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3732 * Get the oldest revision timestamp of this page
3734 * @return String: MW timestamp
3736 public function getEarliestRevTime() {
3737 $dbr = wfGetDB( DB_SLAVE );
3738 if ( $this->exists() ) {
3739 $min = $dbr->selectField( 'revision',
3740 'MIN(rev_timestamp)',
3741 array( 'rev_page' => $this->getArticleId() ),
3742 __METHOD__ );
3743 return wfTimestampOrNull( TS_MW, $min );
3745 return null;
3749 * Get the number of revisions between the given revision IDs.
3750 * Used for diffs and other things that really need it.
3752 * @param $old \type{\int} Revision ID.
3753 * @param $new \type{\int} Revision ID.
3754 * @return \type{\int} Number of revisions between these IDs.
3756 public function countRevisionsBetween( $old, $new ) {
3757 $dbr = wfGetDB( DB_SLAVE );
3758 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3759 'rev_page' => intval( $this->getArticleId() ),
3760 'rev_id > ' . intval( $old ),
3761 'rev_id < ' . intval( $new )
3762 ), __METHOD__
3767 * Get the number of authors between the given revision IDs.
3768 * Used for diffs and other things that really need it.
3770 * @param $fromRevId \type{\int} Revision ID (first before range)
3771 * @param $toRevId \type{\int} Revision ID (first after range)
3772 * @param $limit \type{\int} Maximum number of authors
3773 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3774 * @return \type{\int}
3776 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3777 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3778 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3779 array(
3780 'rev_page' => $this->getArticleID(),
3781 'rev_id > ' . (int)$fromRevId,
3782 'rev_id < ' . (int)$toRevId
3783 ), __METHOD__,
3784 array( 'LIMIT' => $limit )
3786 return (int)$db->numRows( $res );
3790 * Compare with another title.
3792 * @param $title \type{Title}
3793 * @return \type{\bool} TRUE or FALSE
3795 public function equals( Title $title ) {
3796 // Note: === is necessary for proper matching of number-like titles.
3797 return $this->getInterwiki() === $title->getInterwiki()
3798 && $this->getNamespace() == $title->getNamespace()
3799 && $this->getDBkey() === $title->getDBkey();
3803 * Callback for usort() to do title sorts by (namespace, title)
3805 * @return Integer: result of string comparison, or namespace comparison
3807 public static function compare( $a, $b ) {
3808 if ( $a->getNamespace() == $b->getNamespace() ) {
3809 return strcmp( $a->getText(), $b->getText() );
3810 } else {
3811 return $a->getNamespace() - $b->getNamespace();
3816 * Return a string representation of this title
3818 * @return \type{\string} String representation of this title
3820 public function __toString() {
3821 return $this->getPrefixedText();
3825 * Check if page exists. For historical reasons, this function simply
3826 * checks for the existence of the title in the page table, and will
3827 * thus return false for interwiki links, special pages and the like.
3828 * If you want to know if a title can be meaningfully viewed, you should
3829 * probably call the isKnown() method instead.
3831 * @return \type{\bool}
3833 public function exists() {
3834 return $this->getArticleId() != 0;
3838 * Should links to this title be shown as potentially viewable (i.e. as
3839 * "bluelinks"), even if there's no record by this title in the page
3840 * table?
3842 * This function is semi-deprecated for public use, as well as somewhat
3843 * misleadingly named. You probably just want to call isKnown(), which
3844 * calls this function internally.
3846 * (ISSUE: Most of these checks are cheap, but the file existence check
3847 * can potentially be quite expensive. Including it here fixes a lot of
3848 * existing code, but we might want to add an optional parameter to skip
3849 * it and any other expensive checks.)
3851 * @return \type{\bool}
3853 public function isAlwaysKnown() {
3854 if ( $this->mInterwiki != '' ) {
3855 return true; // any interwiki link might be viewable, for all we know
3857 switch( $this->mNamespace ) {
3858 case NS_MEDIA:
3859 case NS_FILE:
3860 return (bool)wfFindFile( $this ); // file exists, possibly in a foreign repo
3861 case NS_SPECIAL:
3862 return SpecialPage::exists( $this->getDBkey() ); // valid special page
3863 case NS_MAIN:
3864 return $this->mDbkeyform == ''; // selflink, possibly with fragment
3865 case NS_MEDIAWIKI:
3866 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3867 // the full l10n of that language to be loaded. That takes much memory and
3868 // isn't needed. So we strip the language part away.
3869 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3870 return (bool)wfMsgWeirdKey( $basename ); // known system message
3871 default:
3872 return false;
3877 * Does this title refer to a page that can (or might) be meaningfully
3878 * viewed? In particular, this function may be used to determine if
3879 * links to the title should be rendered as "bluelinks" (as opposed to
3880 * "redlinks" to non-existent pages).
3882 * @return \type{\bool}
3884 public function isKnown() {
3885 return $this->isAlwaysKnown() || $this->exists();
3889 * Does this page have source text?
3891 * @return Boolean
3893 public function hasSourceText() {
3894 if ( $this->exists() ) {
3895 return true;
3898 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3899 // If the page doesn't exist but is a known system message, default
3900 // message content will be displayed, same for language subpages
3901 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3902 // causes the full l10n of that language to be loaded. That takes much
3903 // memory and isn't needed. So we strip the language part away.
3904 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3905 return (bool)wfMsgWeirdKey( $basename );
3908 return false;
3912 * Is this in a namespace that allows actual pages?
3914 * @return \type{\bool}
3915 * @internal note -- uses hardcoded namespace index instead of constants
3917 public function canExist() {
3918 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3922 * Update page_touched timestamps and send squid purge messages for
3923 * pages linking to this title. May be sent to the job queue depending
3924 * on the number of links. Typically called on create and delete.
3926 public function touchLinks() {
3927 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3928 $u->doUpdate();
3930 if ( $this->getNamespace() == NS_CATEGORY ) {
3931 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3932 $u->doUpdate();
3937 * Get the last touched timestamp
3939 * @param $db DatabaseBase: optional db
3940 * @return \type{\string} Last touched timestamp
3942 public function getTouched( $db = null ) {
3943 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3944 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3945 return $touched;
3949 * Get the timestamp when this page was updated since the user last saw it.
3951 * @param $user User
3952 * @return Mixed: string/null
3954 public function getNotificationTimestamp( $user = null ) {
3955 global $wgUser, $wgShowUpdatedMarker;
3956 // Assume current user if none given
3957 if ( !$user ) {
3958 $user = $wgUser;
3960 // Check cache first
3961 $uid = $user->getId();
3962 if ( isset( $this->mNotificationTimestamp[$uid] ) ) {
3963 return $this->mNotificationTimestamp[$uid];
3965 if ( !$uid || !$wgShowUpdatedMarker ) {
3966 return $this->mNotificationTimestamp[$uid] = false;
3968 // Don't cache too much!
3969 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3970 $this->mNotificationTimestamp = array();
3972 $dbr = wfGetDB( DB_SLAVE );
3973 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3974 'wl_notificationtimestamp',
3975 array( 'wl_namespace' => $this->getNamespace(),
3976 'wl_title' => $this->getDBkey(),
3977 'wl_user' => $user->getId()
3979 __METHOD__
3981 return $this->mNotificationTimestamp[$uid];
3985 * Get the trackback URL for this page
3987 * @return \type{\string} Trackback URL
3989 public function trackbackURL() {
3990 global $wgScriptPath, $wgServer, $wgScriptExtension;
3992 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3993 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3997 * Get the trackback RDF for this page
3999 * @return \type{\string} Trackback RDF
4001 public function trackbackRDF() {
4002 $url = htmlspecialchars( $this->getFullURL() );
4003 $title = htmlspecialchars( $this->getText() );
4004 $tburl = $this->trackbackURL();
4006 // Autodiscovery RDF is placed in comments so HTML validator
4007 // won't barf. This is a rather icky workaround, but seems
4008 // frequently used by this kind of RDF thingy.
4010 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
4011 return "<!--
4012 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
4013 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
4014 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
4015 <rdf:Description
4016 rdf:about=\"$url\"
4017 dc:identifier=\"$url\"
4018 dc:title=\"$title\"
4019 trackback:ping=\"$tburl\" />
4020 </rdf:RDF>
4021 -->";
4025 * Generate strings used for xml 'id' names in monobook tabs
4027 * @param $prepend string defaults to 'nstab-'
4028 * @return \type{\string} XML 'id' name
4030 public function getNamespaceKey( $prepend = 'nstab-' ) {
4031 global $wgContLang;
4032 // Gets the subject namespace if this title
4033 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4034 // Checks if cononical namespace name exists for namespace
4035 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4036 // Uses canonical namespace name
4037 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4038 } else {
4039 // Uses text of namespace
4040 $namespaceKey = $this->getSubjectNsText();
4042 // Makes namespace key lowercase
4043 $namespaceKey = $wgContLang->lc( $namespaceKey );
4044 // Uses main
4045 if ( $namespaceKey == '' ) {
4046 $namespaceKey = 'main';
4048 // Changes file to image for backwards compatibility
4049 if ( $namespaceKey == 'file' ) {
4050 $namespaceKey = 'image';
4052 return $prepend . $namespaceKey;
4056 * Returns true if this is a special page.
4058 * @return boolean
4060 public function isSpecialPage() {
4061 return $this->getNamespace() == NS_SPECIAL;
4065 * Returns true if this title resolves to the named special page
4067 * @param $name \type{\string} The special page name
4068 * @return boolean
4070 public function isSpecial( $name ) {
4071 if ( $this->getNamespace() == NS_SPECIAL ) {
4072 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
4073 if ( $name == $thisName ) {
4074 return true;
4077 return false;
4081 * If the Title refers to a special page alias which is not the local default,
4083 * @return \type{Title} A new Title which points to the local default.
4084 * Otherwise, returns $this.
4086 public function fixSpecialName() {
4087 if ( $this->getNamespace() == NS_SPECIAL ) {
4088 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4089 if ( $canonicalName ) {
4090 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4091 if ( $localName != $this->mDbkeyform ) {
4092 return Title::makeTitle( NS_SPECIAL, $localName );
4096 return $this;
4100 * Is this Title in a namespace which contains content?
4101 * In other words, is this a content page, for the purposes of calculating
4102 * statistics, etc?
4104 * @return Boolean
4106 public function isContentPage() {
4107 return MWNamespace::isContent( $this->getNamespace() );
4111 * Get all extant redirects to this Title
4113 * @param $ns \twotypes{\int,\null} Single namespace to consider;
4114 * NULL to consider all namespaces
4115 * @return \type{\arrayof{Title}} Redirects to this title
4117 public function getRedirectsHere( $ns = null ) {
4118 $redirs = array();
4120 $dbr = wfGetDB( DB_SLAVE );
4121 $where = array(
4122 'rd_namespace' => $this->getNamespace(),
4123 'rd_title' => $this->getDBkey(),
4124 'rd_from = page_id'
4126 if ( !is_null( $ns ) ) {
4127 $where['page_namespace'] = $ns;
4130 $res = $dbr->select(
4131 array( 'redirect', 'page' ),
4132 array( 'page_namespace', 'page_title' ),
4133 $where,
4134 __METHOD__
4137 foreach ( $res as $row ) {
4138 $redirs[] = self::newFromRow( $row );
4140 return $redirs;
4144 * Check if this Title is a valid redirect target
4146 * @return \type{\bool}
4148 public function isValidRedirectTarget() {
4149 global $wgInvalidRedirectTargets;
4151 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4152 if ( $this->isSpecial( 'Userlogout' ) ) {
4153 return false;
4156 foreach ( $wgInvalidRedirectTargets as $target ) {
4157 if ( $this->isSpecial( $target ) ) {
4158 return false;
4162 return true;
4166 * Get a backlink cache object
4168 * @return object BacklinkCache
4170 function getBacklinkCache() {
4171 if ( is_null( $this->mBacklinkCache ) ) {
4172 $this->mBacklinkCache = new BacklinkCache( $this );
4174 return $this->mBacklinkCache;
4178 * Whether the magic words __INDEX__ and __NOINDEX__ function for
4179 * this page.
4181 * @return Boolean
4183 public function canUseNoindex() {
4184 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4186 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4187 ? $wgContentNamespaces
4188 : $wgExemptFromUserRobotsControl;
4190 return !in_array( $this->mNamespace, $bannedNamespaces );
4195 * Returns restriction types for the current Title
4197 * @return array applicable restriction types
4199 public function getRestrictionTypes() {
4200 global $wgRestrictionTypes;
4201 $types = $this->exists() ? $wgRestrictionTypes : array( 'create' );
4203 if ( $this->getNamespace() == NS_FILE ) {
4204 $types[] = 'upload';
4207 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4209 return $types;
4213 * Returns the raw sort key to be used for categories, with the specified
4214 * prefix. This will be fed to Language::convertToSortkey() to get a
4215 * binary sortkey that can be used for actual sorting.
4217 * @param $prefix string The prefix to be used, specified using
4218 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4219 * prefix.
4220 * @return string
4222 public function getCategorySortkey( $prefix = '' ) {
4223 $unprefixed = $this->getText();
4224 if ( $prefix !== '' ) {
4225 # Separate with a null byte, so the unprefixed part is only used as
4226 # a tiebreaker when two pages have the exact same prefix -- null
4227 # sorts before everything else (hopefully).
4228 return "$prefix\0$unprefixed";
4230 return $unprefixed;