Fix a message key typo in r41961 (!!), which didn't matter before because the relevan...
[mediawiki.git] / includes / Title.php
blob41b8e54078fab19151261802495685a9fa3bb7fd
1 <?php
2 /**
3 * See title.txt
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
31 class Title {
32 /** @name Static cache variables */
33 // @{
34 static private $titleCache = array();
35 // @}
37 /**
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX = 1000;
44 /**
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE = 1;
51 /**
52 * @name Private member variables
53 * Please use the accessor functions instead.
54 * @private
56 // @{
58 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
59 var $mUrlform = ''; // /< URL-encoded form of the main part
60 var $mDbkeyform = ''; // /< Main part with underscores
61 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
62 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
63 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
64 var $mFragment; // /< Title fragment (i.e. the bit after the #)
65 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
66 var $mLatestID = false; // /< ID of most recent revision
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
86 // @}
89 /**
90 * Constructor
92 /*protected*/ function __construct() { }
94 /**
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
103 $t = new Title();
104 $t->mDbkeyform = $key;
105 if ( $t->secureAndSplit() ) {
106 return $t;
107 } else {
108 return null;
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
121 * makeTitleSafe().
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
133 * caching them.
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
138 return Title::$titleCache[$text];
141 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
142 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
144 $t = new Title();
145 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace = $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN ) {
151 if ( $cachedcount >= self::CACHE_MAX ) {
152 # Avoid memory leaks on mass operations...
153 Title::$titleCache = array();
154 $cachedcount = 0;
156 $cachedcount++;
157 Title::$titleCache[$text] =& $t;
159 return $t;
160 } else {
161 $ret = null;
162 return $ret;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
183 $t = new Title();
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform = str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
194 return $t;
195 } else {
196 return null;
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
210 if ( $row !== false ) {
211 $title = Title::newFromRow( $row );
212 } else {
213 $title = null;
215 return $title;
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
226 return array();
228 $dbr = wfGetDB( DB_SLAVE );
230 $res = $dbr->select(
231 'page',
232 array(
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
237 __METHOD__
240 $titles = array();
241 foreach ( $res as $row ) {
242 $titles[] = Title::newFromRow( $row );
244 return $titles;
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self::makeTitle( $row->page_namespace, $row->page_title );
255 $t->loadFromRow( $row );
256 return $t;
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|false database row
264 * @return void
266 public function loadFromRow( $row ) {
267 if ( $row ) { // page found
268 if ( isset( $row->page_id ) )
269 $this->mArticleID = (int)$row->page_id;
270 if ( isset( $row->page_len ) )
271 $this->mLength = (int)$row->page_len;
272 if ( isset( $row->page_is_redirect ) )
273 $this->mRedirect = (bool)$row->page_is_redirect;
274 if ( isset( $row->page_latest ) )
275 $this->mLatestID = (int)$row->page_latest;
276 } else { // page not found
277 $this->mArticleID = 0;
278 $this->mLength = 0;
279 $this->mRedirect = false;
280 $this->mLatestID = 0;
285 * Create a new Title from a namespace index and a DB key.
286 * It's assumed that $ns and $title are *valid*, for instance when
287 * they came directly from the database or a special page name.
288 * For convenience, spaces are converted to underscores so that
289 * eg user_text fields can be used directly.
291 * @param $ns Int the namespace of the article
292 * @param $title String the unprefixed database key form
293 * @param $fragment String the link fragment (after the "#")
294 * @param $interwiki String the interwiki prefix
295 * @return Title the new object
297 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
298 $t = new Title();
299 $t->mInterwiki = $interwiki;
300 $t->mFragment = $fragment;
301 $t->mNamespace = $ns = intval( $ns );
302 $t->mDbkeyform = str_replace( ' ', '_', $title );
303 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
304 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
305 $t->mTextform = str_replace( '_', ' ', $title );
306 return $t;
310 * Create a new Title from a namespace index and a DB key.
311 * The parameters will be checked for validity, which is a bit slower
312 * than makeTitle() but safer for user-provided data.
314 * @param $ns Int the namespace of the article
315 * @param $title String database key form
316 * @param $fragment String the link fragment (after the "#")
317 * @param $interwiki String interwiki prefix
318 * @return Title the new object, or NULL on an error
320 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
321 $t = new Title();
322 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
323 if ( $t->secureAndSplit() ) {
324 return $t;
325 } else {
326 return null;
331 * Create a new Title for the Main Page
333 * @return Title the new object
335 public static function newMainPage() {
336 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
337 // Don't give fatal errors if the message is broken
338 if ( !$title ) {
339 $title = Title::newFromText( 'Main Page' );
341 return $title;
345 * Extract a redirect destination from a string and return the
346 * Title, or null if the text doesn't contain a valid redirect
347 * This will only return the very next target, useful for
348 * the redirect table and other checks that don't need full recursion
350 * @param $text String: Text with possible redirect
351 * @return Title: The corresponding Title
353 public static function newFromRedirect( $text ) {
354 return self::newFromRedirectInternal( $text );
358 * Extract a redirect destination from a string and return the
359 * Title, or null if the text doesn't contain a valid redirect
360 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
361 * in order to provide (hopefully) the Title of the final destination instead of another redirect
363 * @param $text String Text with possible redirect
364 * @return Title
366 public static function newFromRedirectRecurse( $text ) {
367 $titles = self::newFromRedirectArray( $text );
368 return $titles ? array_pop( $titles ) : null;
372 * Extract a redirect destination from a string and return an
373 * array of Titles, or null if the text doesn't contain a valid redirect
374 * The last element in the array is the final destination after all redirects
375 * have been resolved (up to $wgMaxRedirects times)
377 * @param $text String Text with possible redirect
378 * @return Array of Titles, with the destination last
380 public static function newFromRedirectArray( $text ) {
381 global $wgMaxRedirects;
382 $title = self::newFromRedirectInternal( $text );
383 if ( is_null( $title ) ) {
384 return null;
386 // recursive check to follow double redirects
387 $recurse = $wgMaxRedirects;
388 $titles = array( $title );
389 while ( --$recurse > 0 ) {
390 if ( $title->isRedirect() ) {
391 $article = new Article( $title, 0 );
392 $newtitle = $article->getRedirectTarget();
393 } else {
394 break;
396 // Redirects to some special pages are not permitted
397 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
398 // the new title passes the checks, so make that our current title so that further recursion can be checked
399 $title = $newtitle;
400 $titles[] = $newtitle;
401 } else {
402 break;
405 return $titles;
409 * Really extract the redirect destination
410 * Do not call this function directly, use one of the newFromRedirect* functions above
412 * @param $text String Text with possible redirect
413 * @return Title
415 protected static function newFromRedirectInternal( $text ) {
416 global $wgMaxRedirects;
417 if ( $wgMaxRedirects < 1 ) {
418 //redirects are disabled, so quit early
419 return null;
421 $redir = MagicWord::get( 'redirect' );
422 $text = trim( $text );
423 if ( $redir->matchStartAndRemove( $text ) ) {
424 // Extract the first link and see if it's usable
425 // Ensure that it really does come directly after #REDIRECT
426 // Some older redirects included a colon, so don't freak about that!
427 $m = array();
428 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
429 // Strip preceding colon used to "escape" categories, etc.
430 // and URL-decode links
431 if ( strpos( $m[1], '%' ) !== false ) {
432 // Match behavior of inline link parsing here;
433 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
435 $title = Title::newFromText( $m[1] );
436 // If the title is a redirect to bad special pages or is invalid, return null
437 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
438 return null;
440 return $title;
443 return null;
446 # ----------------------------------------------------------------------------
447 # Static functions
448 # ----------------------------------------------------------------------------
451 * Get the prefixed DB key associated with an ID
453 * @param $id Int the page_id of the article
454 * @return Title an object representing the article, or NULL if no such article was found
456 public static function nameOf( $id ) {
457 $dbr = wfGetDB( DB_SLAVE );
459 $s = $dbr->selectRow(
460 'page',
461 array( 'page_namespace', 'page_title' ),
462 array( 'page_id' => $id ),
463 __METHOD__
465 if ( $s === false ) {
466 return null;
469 $n = self::makeName( $s->page_namespace, $s->page_title );
470 return $n;
474 * Get a regex character class describing the legal characters in a link
476 * @return String the list of characters, not delimited
478 public static function legalChars() {
479 global $wgLegalTitleChars;
480 return $wgLegalTitleChars;
484 * Get a string representation of a title suitable for
485 * including in a search index
487 * @param $ns Int a namespace index
488 * @param $title String text-form main part
489 * @return String a stripped-down title string ready for the search index
491 public static function indexTitle( $ns, $title ) {
492 global $wgContLang;
494 $lc = SearchEngine::legalSearchChars() . '&#;';
495 $t = $wgContLang->normalizeForSearch( $title );
496 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
497 $t = $wgContLang->lc( $t );
499 # Handle 's, s'
500 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
501 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
503 $t = preg_replace( "/\\s+/", ' ', $t );
505 if ( $ns == NS_FILE ) {
506 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
508 return trim( $t );
512 * Make a prefixed DB key from a DB key and a namespace index
514 * @param $ns Int numerical representation of the namespace
515 * @param $title String the DB key form the title
516 * @param $fragment String The link fragment (after the "#")
517 * @param $interwiki String The interwiki prefix
518 * @return String the prefixed form of the title
520 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
521 global $wgContLang;
523 $namespace = $wgContLang->getNsText( $ns );
524 $name = $namespace == '' ? $title : "$namespace:$title";
525 if ( strval( $interwiki ) != '' ) {
526 $name = "$interwiki:$name";
528 if ( strval( $fragment ) != '' ) {
529 $name .= '#' . $fragment;
531 return $name;
535 * Determine whether the object refers to a page within
536 * this project.
538 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
540 public function isLocal() {
541 if ( $this->mInterwiki != '' ) {
542 return Interwiki::fetch( $this->mInterwiki )->isLocal();
543 } else {
544 return true;
549 * Determine whether the object refers to a page within
550 * this project and is transcludable.
552 * @return Bool TRUE if this is transcludable
554 public function isTrans() {
555 if ( $this->mInterwiki == '' ) {
556 return false;
559 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
563 * Returns the DB name of the distant wiki which owns the object.
565 * @return String the DB name
567 public function getTransWikiID() {
568 if ( $this->mInterwiki == '' ) {
569 return false;
572 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
576 * Escape a text fragment, say from a link, for a URL
578 * @param $fragment string containing a URL or link fragment (after the "#")
579 * @return String: escaped string
581 static function escapeFragmentForURL( $fragment ) {
582 # Note that we don't urlencode the fragment. urlencoded Unicode
583 # fragments appear not to work in IE (at least up to 7) or in at least
584 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
585 # to care if they aren't encoded.
586 return Sanitizer::escapeId( $fragment, 'noninitial' );
589 # ----------------------------------------------------------------------------
590 # Other stuff
591 # ----------------------------------------------------------------------------
593 /** Simple accessors */
595 * Get the text form (spaces not underscores) of the main part
597 * @return String Main part of the title
599 public function getText() { return $this->mTextform; }
602 * Get the URL-encoded form of the main part
604 * @return String Main part of the title, URL-encoded
606 public function getPartialURL() { return $this->mUrlform; }
609 * Get the main part with underscores
611 * @return String: Main part of the title, with underscores
613 public function getDBkey() { return $this->mDbkeyform; }
616 * Get the namespace index, i.e. one of the NS_xxxx constants.
618 * @return Integer: Namespace index
620 public function getNamespace() { return $this->mNamespace; }
623 * Get the namespace text
625 * @return String: Namespace text
627 public function getNsText() {
628 global $wgContLang;
630 if ( $this->mInterwiki != '' ) {
631 // This probably shouldn't even happen. ohh man, oh yuck.
632 // But for interwiki transclusion it sometimes does.
633 // Shit. Shit shit shit.
635 // Use the canonical namespaces if possible to try to
636 // resolve a foreign namespace.
637 if ( MWNamespace::exists( $this->mNamespace ) ) {
638 return MWNamespace::getCanonicalName( $this->mNamespace );
642 if ( $wgContLang->needsGenderDistinction() &&
643 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
644 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
645 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
648 return $wgContLang->getNsText( $this->mNamespace );
652 * Get the DB key with the initial letter case as specified by the user
654 * @return String DB key
656 function getUserCaseDBKey() {
657 return $this->mUserCaseDBKey;
661 * Get the namespace text of the subject (rather than talk) page
663 * @return String Namespace text
665 public function getSubjectNsText() {
666 global $wgContLang;
667 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
671 * Get the namespace text of the talk page
673 * @return String Namespace text
675 public function getTalkNsText() {
676 global $wgContLang;
677 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
681 * Could this title have a corresponding talk page?
683 * @return Bool TRUE or FALSE
685 public function canTalk() {
686 return( MWNamespace::canTalk( $this->mNamespace ) );
690 * Get the interwiki prefix (or null string)
692 * @return String Interwiki prefix
694 public function getInterwiki() { return $this->mInterwiki; }
697 * Get the Title fragment (i.e.\ the bit after the #) in text form
699 * @return String Title fragment
701 public function getFragment() { return $this->mFragment; }
704 * Get the fragment in URL form, including the "#" character if there is one
705 * @return String Fragment in URL form
707 public function getFragmentForURL() {
708 if ( $this->mFragment == '' ) {
709 return '';
710 } else {
711 return '#' . Title::escapeFragmentForURL( $this->mFragment );
716 * Get the default namespace index, for when there is no namespace
718 * @return Int Default namespace index
720 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
723 * Get title for search index
725 * @return String a stripped-down title string ready for the
726 * search index
728 public function getIndexTitle() {
729 return Title::indexTitle( $this->mNamespace, $this->mTextform );
733 * Get the prefixed database key form
735 * @return String the prefixed title, with underscores and
736 * any interwiki and namespace prefixes
738 public function getPrefixedDBkey() {
739 $s = $this->prefix( $this->mDbkeyform );
740 $s = str_replace( ' ', '_', $s );
741 return $s;
745 * Get the prefixed title with spaces.
746 * This is the form usually used for display
748 * @return String the prefixed title, with spaces
750 public function getPrefixedText() {
751 // @todo FIXME: Bad usage of empty() ?
752 if ( empty( $this->mPrefixedText ) ) {
753 $s = $this->prefix( $this->mTextform );
754 $s = str_replace( '_', ' ', $s );
755 $this->mPrefixedText = $s;
757 return $this->mPrefixedText;
761 * Return the prefixed title with spaces _without_ the interwiki prefix
763 * @return \type{\string} the title, prefixed by the namespace but not by the interwiki prefix, with spaces
765 public function getSemiPrefixedText() {
766 if ( !isset( $this->mSemiPrefixedText ) ){
767 $s = ( $this->mNamespace === NS_MAIN ? '' : $this->getNsText() . ':' ) . $this->mTextform;
768 $s = str_replace( '_', ' ', $s );
769 $this->mSemiPrefixedText = $s;
771 return $this->mSemiPrefixedText;
775 * Get the prefixed title with spaces, plus any fragment
776 * (part beginning with '#')
778 * @return String the prefixed title, with spaces and the fragment, including '#'
780 public function getFullText() {
781 $text = $this->getPrefixedText();
782 if ( $this->mFragment != '' ) {
783 $text .= '#' . $this->mFragment;
785 return $text;
789 * Get the base page name, i.e. the leftmost part before any slashes
791 * @return String Base name
793 public function getBaseText() {
794 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
795 return $this->getText();
798 $parts = explode( '/', $this->getText() );
799 # Don't discard the real title if there's no subpage involved
800 if ( count( $parts ) > 1 ) {
801 unset( $parts[count( $parts ) - 1] );
803 return implode( '/', $parts );
807 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
809 * @return String Subpage name
811 public function getSubpageText() {
812 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
813 return( $this->mTextform );
815 $parts = explode( '/', $this->mTextform );
816 return( $parts[count( $parts ) - 1] );
820 * Get a URL-encoded form of the subpage text
822 * @return String URL-encoded subpage name
824 public function getSubpageUrlForm() {
825 $text = $this->getSubpageText();
826 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
827 return( $text );
831 * Get a URL-encoded title (not an actual URL) including interwiki
833 * @return String the URL-encoded form
835 public function getPrefixedURL() {
836 $s = $this->prefix( $this->mDbkeyform );
837 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
838 return $s;
842 * Get a real URL referring to this title, with interwiki link and
843 * fragment
845 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
846 * links. Can be specified as an associative array as well, e.g.,
847 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
848 * @param $variant String language variant of url (for sr, zh..)
849 * @return String the URL
851 public function getFullURL( $query = '', $variant = false ) {
852 # Hand off all the decisions on urls to getLocalURL
853 $url = $this->getLocalURL( $query, $variant );
855 # Expand the url to make it a full url. Note that getLocalURL has the
856 # potential to output full urls for a variety of reasons, so we use
857 # wfExpandUrl instead of simply prepending $wgServer
858 $url = wfExpandUrl( $url, PROTO_RELATIVE );
860 # Finally, add the fragment.
861 $url .= $this->getFragmentForURL();
863 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
864 return $url;
868 * Get a URL with no fragment or server name. If this page is generated
869 * with action=render, $wgServer is prepended.
871 * @param $query Mixed: an optional query string; if not specified,
872 * $wgArticlePath will be used. Can be specified as an associative array
873 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
874 * URL-escaped).
875 * @param $variant String language variant of url (for sr, zh..)
876 * @return String the URL
878 public function getLocalURL( $query = '', $variant = false ) {
879 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
880 global $wgVariantArticlePath, $wgContLang;
882 if ( is_array( $query ) ) {
883 $query = wfArrayToCGI( $query );
886 $interwiki = Interwiki::fetch( $this->mInterwiki );
887 if ( $interwiki ) {
888 $namespace = $this->getNsText();
889 if ( $namespace != '' ) {
890 # Can this actually happen? Interwikis shouldn't be parsed.
891 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
892 $namespace .= ':';
894 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
895 $url = wfAppendQuery( $url, $query );
896 } else {
897 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
898 if ( $query == '' ) {
899 if ( $variant != false && $wgContLang->hasVariants() ) {
900 if ( !$wgVariantArticlePath ) {
901 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
902 } else {
903 $variantArticlePath = $wgVariantArticlePath;
905 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
906 $url = str_replace( '$1', $dbkey, $url );
907 } else {
908 $url = str_replace( '$1', $dbkey, $wgArticlePath );
909 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
911 } else {
912 global $wgActionPaths;
913 $url = false;
914 $matches = array();
915 if ( !empty( $wgActionPaths ) &&
916 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
918 $action = urldecode( $matches[2] );
919 if ( isset( $wgActionPaths[$action] ) ) {
920 $query = $matches[1];
921 if ( isset( $matches[4] ) ) {
922 $query .= $matches[4];
924 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
925 if ( $query != '' ) {
926 $url = wfAppendQuery( $url, $query );
931 if ( $url === false ) {
932 if ( $query == '-' ) {
933 $query = '';
935 $url = "{$wgScript}?title={$dbkey}&{$query}";
939 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
941 // @todo FIXME: This causes breakage in various places when we
942 // actually expected a local URL and end up with dupe prefixes.
943 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
944 $url = $wgServer . $url;
947 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
948 return $url;
952 * Get a URL that's the simplest URL that will be valid to link, locally,
953 * to the current Title. It includes the fragment, but does not include
954 * the server unless action=render is used (or the link is external). If
955 * there's a fragment but the prefixed text is empty, we just return a link
956 * to the fragment.
958 * The result obviously should not be URL-escaped, but does need to be
959 * HTML-escaped if it's being output in HTML.
961 * @param $query Array of Strings An associative array of key => value pairs for the
962 * query string. Keys and values will be escaped.
963 * @param $variant String language variant of URL (for sr, zh..). Ignored
964 * for external links. Default is "false" (same variant as current page,
965 * for anonymous users).
966 * @return String the URL
968 public function getLinkUrl( $query = array(), $variant = false ) {
969 wfProfileIn( __METHOD__ );
970 if ( $this->isExternal() ) {
971 $ret = $this->getFullURL( $query );
972 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
973 $ret = $this->getFragmentForURL();
974 } else {
975 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
977 wfProfileOut( __METHOD__ );
978 return $ret;
982 * Get an HTML-escaped version of the URL form, suitable for
983 * using in a link, without a server name or fragment
985 * @param $query String an optional query string
986 * @return String the URL
988 public function escapeLocalURL( $query = '' ) {
989 return htmlspecialchars( $this->getLocalURL( $query ) );
993 * Get an HTML-escaped version of the URL form, suitable for
994 * using in a link, including the server name and fragment
996 * @param $query String an optional query string
997 * @return String the URL
999 public function escapeFullURL( $query = '' ) {
1000 return htmlspecialchars( $this->getFullURL( $query ) );
1004 * HTML-escaped version of getCanonicalURL()
1006 public function escapeCanonicalURL( $query = '', $variant = false ) {
1007 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1011 * Get the URL form for an internal link.
1012 * - Used in various Squid-related code, in case we have a different
1013 * internal hostname for the server from the exposed one.
1015 * This uses $wgInternalServer to qualify the path, or $wgServer
1016 * if $wgInternalServer is not set. If the server variable used is
1017 * protocol-relative, the URL will be expanded to http://
1019 * @param $query String an optional query string
1020 * @param $variant String language variant of url (for sr, zh..)
1021 * @return String the URL
1023 public function getInternalURL( $query = '', $variant = false ) {
1024 if ( $this->isExternal( ) ) {
1025 $server = '';
1026 } else {
1027 global $wgInternalServer, $wgServer;
1028 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1030 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP );
1031 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1032 return $url;
1036 * Get the URL for a canonical link, for use in things like IRC and
1037 * e-mail notifications. Uses $wgCanonicalServer and the
1038 * GetCanonicalURL hook.
1040 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1042 * @param $query string An optional query string
1043 * @param $variant string Language variant of URL (for sr, zh, ...)
1044 * @return string The URL
1046 public function getCanonicalURL( $query = '', $variant = false ) {
1047 global $wgCanonicalServer;
1048 $url = $wgCanonicalServer . $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
1049 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1050 return $url;
1054 * Get the edit URL for this Title
1056 * @return String the URL, or a null string if this is an
1057 * interwiki link
1059 public function getEditURL() {
1060 if ( $this->mInterwiki != '' ) {
1061 return '';
1063 $s = $this->getLocalURL( 'action=edit' );
1065 return $s;
1069 * Get the HTML-escaped displayable text form.
1070 * Used for the title field in <a> tags.
1072 * @return String the text, including any prefixes
1074 public function getEscapedText() {
1075 return htmlspecialchars( $this->getPrefixedText() );
1079 * Is this Title interwiki?
1081 * @return Bool
1083 public function isExternal() {
1084 return ( $this->mInterwiki != '' );
1088 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1090 * @param $action String Action to check (default: edit)
1091 * @return Bool
1093 public function isSemiProtected( $action = 'edit' ) {
1094 if ( $this->exists() ) {
1095 $restrictions = $this->getRestrictions( $action );
1096 if ( count( $restrictions ) > 0 ) {
1097 foreach ( $restrictions as $restriction ) {
1098 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1099 return false;
1102 } else {
1103 # Not protected
1104 return false;
1106 return true;
1107 } else {
1108 # If it doesn't exist, it can't be protected
1109 return false;
1114 * Does the title correspond to a protected article?
1116 * @param $action String the action the page is protected from,
1117 * by default checks all actions.
1118 * @return Bool
1120 public function isProtected( $action = '' ) {
1121 global $wgRestrictionLevels;
1123 $restrictionTypes = $this->getRestrictionTypes();
1125 # Special pages have inherent protection
1126 if( $this->getNamespace() == NS_SPECIAL ) {
1127 return true;
1130 # Check regular protection levels
1131 foreach ( $restrictionTypes as $type ) {
1132 if ( $action == $type || $action == '' ) {
1133 $r = $this->getRestrictions( $type );
1134 foreach ( $wgRestrictionLevels as $level ) {
1135 if ( in_array( $level, $r ) && $level != '' ) {
1136 return true;
1142 return false;
1146 * Is this a conversion table for the LanguageConverter?
1148 * @return Bool
1150 public function isConversionTable() {
1152 $this->getNamespace() == NS_MEDIAWIKI &&
1153 strpos( $this->getText(), 'Conversiontable' ) !== false
1156 return true;
1159 return false;
1163 * Is $wgUser watching this page?
1165 * @return Bool
1167 public function userIsWatching() {
1168 global $wgUser;
1170 if ( is_null( $this->mWatched ) ) {
1171 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1172 $this->mWatched = false;
1173 } else {
1174 $this->mWatched = $wgUser->isWatched( $this );
1177 return $this->mWatched;
1181 * Can $wgUser perform $action on this page?
1182 * This skips potentially expensive cascading permission checks
1183 * as well as avoids expensive error formatting
1185 * Suitable for use for nonessential UI controls in common cases, but
1186 * _not_ for functional access control.
1188 * May provide false positives, but should never provide a false negative.
1190 * @param $action String action that permission needs to be checked for
1191 * @return Bool
1193 public function quickUserCan( $action ) {
1194 return $this->userCan( $action, false );
1198 * Determines if $user is unable to edit this page because it has been protected
1199 * by $wgNamespaceProtection.
1201 * @param $user User object to check permissions
1202 * @return Bool
1204 public function isNamespaceProtected( User $user ) {
1205 global $wgNamespaceProtection;
1207 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1208 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1209 if ( $right != '' && !$user->isAllowed( $right ) ) {
1210 return true;
1214 return false;
1218 * Can $wgUser perform $action on this page?
1220 * @param $action String action that permission needs to be checked for
1221 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1222 * @return Bool
1224 public function userCan( $action, $doExpensiveQueries = true ) {
1225 global $wgUser;
1226 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1230 * Can $user perform $action on this page?
1232 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1234 * @param $action String action that permission needs to be checked for
1235 * @param $user User to check
1236 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1237 * skipping checks for cascading protections and user blocks.
1238 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1239 * @return Array of arguments to wfMsg to explain permissions problems.
1241 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1242 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1244 // Remove the errors being ignored.
1245 foreach ( $errors as $index => $error ) {
1246 $error_key = is_array( $error ) ? $error[0] : $error;
1248 if ( in_array( $error_key, $ignoreErrors ) ) {
1249 unset( $errors[$index] );
1253 return $errors;
1257 * Permissions checks that fail most often, and which are easiest to test.
1259 * @param $action String the action to check
1260 * @param $user User user to check
1261 * @param $errors Array list of current errors
1262 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1263 * @param $short Boolean short circuit on first error
1265 * @return Array list of errors
1267 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1268 $ns = $this->getNamespace();
1270 if ( $action == 'create' ) {
1271 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1272 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1273 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1275 } elseif ( $action == 'move' ) {
1276 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1277 && $ns == NS_USER && !$this->isSubpage() ) {
1278 // Show user page-specific message only if the user can move other pages
1279 $errors[] = array( 'cant-move-user-page' );
1282 // Check if user is allowed to move files if it's a file
1283 if ( $ns == NS_FILE && !$user->isAllowed( 'movefile', $ns ) ) {
1284 $errors[] = array( 'movenotallowedfile' );
1287 if ( !$user->isAllowed( 'move', $ns) ) {
1288 // User can't move anything
1290 $userCanMove = in_array( 'move', User::getGroupPermissions(
1291 array( 'user' ), $ns ), true );
1292 $autoconfirmedCanMove = in_array( 'move', User::getGroupPermissions(
1293 array( 'autoconfirmed' ), $ns ), true );
1295 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1296 // custom message if logged-in users without any special rights can move
1297 $errors[] = array( 'movenologintext' );
1298 } else {
1299 $errors[] = array( 'movenotallowed' );
1302 } elseif ( $action == 'move-target' ) {
1303 if ( !$user->isAllowed( 'move', $ns ) ) {
1304 // User can't move anything
1305 $errors[] = array( 'movenotallowed' );
1306 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1307 && $ns == NS_USER && !$this->isSubpage() ) {
1308 // Show user page-specific message only if the user can move other pages
1309 $errors[] = array( 'cant-move-to-user-page' );
1311 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1312 // We avoid expensive display logic for quickUserCan's and such
1313 $groups = false;
1314 if ( !$short ) {
1315 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1316 User::getGroupsWithPermission( $action, $ns ) );
1319 if ( $groups ) {
1320 global $wgLang;
1321 $return = array(
1322 'badaccess-groups',
1323 $wgLang->commaList( $groups ),
1324 count( $groups )
1326 } else {
1327 $return = array( 'badaccess-group0' );
1329 $errors[] = $return;
1332 return $errors;
1336 * Add the resulting error code to the errors array
1338 * @param $errors Array list of current errors
1339 * @param $result Mixed result of errors
1341 * @return Array list of errors
1343 private function resultToError( $errors, $result ) {
1344 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1345 // A single array representing an error
1346 $errors[] = $result;
1347 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1348 // A nested array representing multiple errors
1349 $errors = array_merge( $errors, $result );
1350 } elseif ( $result !== '' && is_string( $result ) ) {
1351 // A string representing a message-id
1352 $errors[] = array( $result );
1353 } elseif ( $result === false ) {
1354 // a generic "We don't want them to do that"
1355 $errors[] = array( 'badaccess-group0' );
1357 return $errors;
1361 * Check various permission hooks
1363 * @param $action String the action to check
1364 * @param $user User user to check
1365 * @param $errors Array list of current errors
1366 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1367 * @param $short Boolean short circuit on first error
1369 * @return Array list of errors
1371 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1372 // Use getUserPermissionsErrors instead
1373 $result = '';
1374 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1375 return $result ? array() : array( array( 'badaccess-group0' ) );
1377 // Check getUserPermissionsErrors hook
1378 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1379 $errors = $this->resultToError( $errors, $result );
1381 // Check getUserPermissionsErrorsExpensive hook
1382 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1383 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1384 $errors = $this->resultToError( $errors, $result );
1387 return $errors;
1391 * Check permissions on special pages & namespaces
1393 * @param $action String the action to check
1394 * @param $user User user to check
1395 * @param $errors Array list of current errors
1396 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1397 * @param $short Boolean short circuit on first error
1399 * @return Array list of errors
1401 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1402 # Only 'createaccount' and 'execute' can be performed on
1403 # special pages, which don't actually exist in the DB.
1404 $specialOKActions = array( 'createaccount', 'execute' );
1405 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1406 $errors[] = array( 'ns-specialprotected' );
1409 # Check $wgNamespaceProtection for restricted namespaces
1410 if ( $this->isNamespaceProtected( $user ) ) {
1411 $ns = $this->mNamespace == NS_MAIN ?
1412 wfMsg( 'nstab-main' ) : $this->getNsText();
1413 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1414 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1417 return $errors;
1421 * Check CSS/JS sub-page permissions
1423 * @param $action String the action to check
1424 * @param $user User user to check
1425 * @param $errors Array list of current errors
1426 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1427 * @param $short Boolean short circuit on first error
1429 * @return Array list of errors
1431 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1432 # Protect css/js subpages of user pages
1433 # XXX: this might be better using restrictions
1434 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1435 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1436 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1437 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1438 $errors[] = array( 'customcssprotected' );
1439 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1440 $errors[] = array( 'customjsprotected' );
1444 return $errors;
1448 * Check against page_restrictions table requirements on this
1449 * page. The user must possess all required rights for this
1450 * action.
1452 * @param $action String the action to check
1453 * @param $user User user to check
1454 * @param $errors Array list of current errors
1455 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1456 * @param $short Boolean short circuit on first error
1458 * @return Array list of errors
1460 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1461 foreach ( $this->getRestrictions( $action ) as $right ) {
1462 // Backwards compatibility, rewrite sysop -> protect
1463 if ( $right == 'sysop' ) {
1464 $right = 'protect';
1466 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace ) ) {
1467 // Users with 'editprotected' permission can edit protected pages
1468 if ( $action == 'edit' && $user->isAllowed( 'editprotected', $this->mNamespace ) ) {
1469 // Users with 'editprotected' permission cannot edit protected pages
1470 // with cascading option turned on.
1471 if ( $this->mCascadeRestriction ) {
1472 $errors[] = array( 'protectedpagetext', $right );
1474 } else {
1475 $errors[] = array( 'protectedpagetext', $right );
1480 return $errors;
1484 * Check restrictions on cascading pages.
1486 * @param $action String the action to check
1487 * @param $user User to check
1488 * @param $errors Array list of current errors
1489 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1490 * @param $short Boolean short circuit on first error
1492 * @return Array list of errors
1494 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1495 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1496 # We /could/ use the protection level on the source page, but it's
1497 # fairly ugly as we have to establish a precedence hierarchy for pages
1498 # included by multiple cascade-protected pages. So just restrict
1499 # it to people with 'protect' permission, as they could remove the
1500 # protection anyway.
1501 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1502 # Cascading protection depends on more than this page...
1503 # Several cascading protected pages may include this page...
1504 # Check each cascading level
1505 # This is only for protection restrictions, not for all actions
1506 if ( isset( $restrictions[$action] ) ) {
1507 foreach ( $restrictions[$action] as $right ) {
1508 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1509 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace ) ) {
1510 $pages = '';
1511 foreach ( $cascadingSources as $page )
1512 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1513 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1519 return $errors;
1523 * Check action permissions not already checked in checkQuickPermissions
1525 * @param $action String the action to check
1526 * @param $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 checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1534 if ( $action == 'protect' ) {
1535 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1536 // If they can't edit, they shouldn't protect.
1537 $errors[] = array( 'protect-cantedit' );
1539 } elseif ( $action == 'create' ) {
1540 $title_protection = $this->getTitleProtection();
1541 if( $title_protection ) {
1542 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1543 $title_protection['pt_create_perm'] = 'protect'; // B/C
1545 if( $title_protection['pt_create_perm'] == '' ||
1546 !$user->isAllowed( $title_protection['pt_create_perm'],
1547 $this->mNamespace ) ) {
1548 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1551 } elseif ( $action == 'move' ) {
1552 // Check for immobile pages
1553 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1554 // Specific message for this case
1555 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1556 } elseif ( !$this->isMovable() ) {
1557 // Less specific message for rarer cases
1558 $errors[] = array( 'immobile-source-page' );
1560 } elseif ( $action == 'move-target' ) {
1561 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1562 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1563 } elseif ( !$this->isMovable() ) {
1564 $errors[] = array( 'immobile-target-page' );
1567 return $errors;
1571 * Check that the user isn't blocked from editting.
1573 * @param $action String the action to check
1574 * @param $user User to check
1575 * @param $errors Array list of current errors
1576 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1577 * @param $short Boolean short circuit on first error
1579 * @return Array list of errors
1581 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1582 if( !$doExpensiveQueries ) {
1583 return $errors;
1586 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1588 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1589 $errors[] = array( 'confirmedittext' );
1592 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1593 // Edit blocks should not affect reading.
1594 // Account creation blocks handled at userlogin.
1595 // Unblocking handled in SpecialUnblock
1596 } elseif( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1597 // Don't block the user from editing their own talk page unless they've been
1598 // explicitly blocked from that too.
1599 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1600 $block = $user->mBlock;
1602 // This is from OutputPage::blockedPage
1603 // Copied at r23888 by werdna
1605 $id = $user->blockedBy();
1606 $reason = $user->blockedFor();
1607 if ( $reason == '' ) {
1608 $reason = wfMsg( 'blockednoreason' );
1610 $ip = $user->getRequest()->getIP();
1612 if ( is_numeric( $id ) ) {
1613 $name = User::whoIs( $id );
1614 } else {
1615 $name = $id;
1618 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1619 $blockid = $block->getId();
1620 $blockExpiry = $user->mBlock->mExpiry;
1621 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1622 if ( $blockExpiry == 'infinity' ) {
1623 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1624 } else {
1625 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1628 $intended = strval( $user->mBlock->getTarget() );
1630 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1631 $blockid, $blockExpiry, $intended, $blockTimestamp );
1634 return $errors;
1638 * Can $user perform $action on this page? This is an internal function,
1639 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1640 * checks on wfReadOnly() and blocks)
1642 * @param $action String action that permission needs to be checked for
1643 * @param $user User to check
1644 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1645 * @param $short Bool Set this to true to stop after the first permission error.
1646 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1648 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1649 wfProfileIn( __METHOD__ );
1651 $errors = array();
1652 $checks = array(
1653 'checkQuickPermissions',
1654 'checkPermissionHooks',
1655 'checkSpecialsAndNSPermissions',
1656 'checkCSSandJSPermissions',
1657 'checkPageRestrictions',
1658 'checkCascadingSourcesRestrictions',
1659 'checkActionPermissions',
1660 'checkUserBlock'
1663 while( count( $checks ) > 0 &&
1664 !( $short && count( $errors ) > 0 ) ) {
1665 $method = array_shift( $checks );
1666 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1669 wfProfileOut( __METHOD__ );
1670 return $errors;
1674 * Is this title subject to title protection?
1675 * Title protection is the one applied against creation of such title.
1677 * @return Mixed An associative array representing any existent title
1678 * protection, or false if there's none.
1680 private function getTitleProtection() {
1681 // Can't protect pages in special namespaces
1682 if ( $this->getNamespace() < 0 ) {
1683 return false;
1686 // Can't protect pages that exist.
1687 if ( $this->exists() ) {
1688 return false;
1691 if ( !isset( $this->mTitleProtection ) ) {
1692 $dbr = wfGetDB( DB_SLAVE );
1693 $res = $dbr->select( 'protected_titles', '*',
1694 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1695 __METHOD__ );
1697 // fetchRow returns false if there are no rows.
1698 $this->mTitleProtection = $dbr->fetchRow( $res );
1700 return $this->mTitleProtection;
1704 * Update the title protection status
1706 * @param $create_perm String Permission required for creation
1707 * @param $reason String Reason for protection
1708 * @param $expiry String Expiry timestamp
1709 * @return boolean true
1711 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1712 global $wgUser, $wgContLang;
1714 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1715 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1716 // No change
1717 return true;
1720 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1722 $dbw = wfGetDB( DB_MASTER );
1724 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1726 $expiry_description = '';
1727 if ( $encodedExpiry != $dbw->getInfinity() ) {
1728 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1729 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1730 } else {
1731 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1734 # Update protection table
1735 if ( $create_perm != '' ) {
1736 $this->mTitleProtection = array(
1737 'pt_namespace' => $namespace,
1738 'pt_title' => $title,
1739 'pt_create_perm' => $create_perm,
1740 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1741 'pt_expiry' => $encodedExpiry,
1742 'pt_user' => $wgUser->getId(),
1743 'pt_reason' => $reason,
1745 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1746 $this->mTitleProtection, __METHOD__ );
1747 } else {
1748 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1749 'pt_title' => $title ), __METHOD__ );
1750 $this->mTitleProtection = false;
1753 # Update the protection log
1754 if ( $dbw->affectedRows() ) {
1755 $log = new LogPage( 'protect' );
1757 if ( $create_perm ) {
1758 $params = array( "[create=$create_perm] $expiry_description", '' );
1759 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1760 } else {
1761 $log->addEntry( 'unprotect', $this, $reason );
1765 return true;
1769 * Remove any title protection due to page existing
1771 public function deleteTitleProtection() {
1772 $dbw = wfGetDB( DB_MASTER );
1774 $dbw->delete(
1775 'protected_titles',
1776 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1777 __METHOD__
1779 $this->mTitleProtection = false;
1783 * Would anybody with sufficient privileges be able to move this page?
1784 * Some pages just aren't movable.
1786 * @return Bool TRUE or FALSE
1788 public function isMovable() {
1789 $result = MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1790 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1791 return $result;
1795 * Can $wgUser read this page?
1797 * @return Bool
1798 * @todo fold these checks into userCan()
1800 public function userCanRead() {
1801 global $wgUser, $wgGroupPermissions;
1803 static $useShortcut = null;
1805 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1806 if ( is_null( $useShortcut ) ) {
1807 global $wgRevokePermissions;
1808 $useShortcut = true;
1809 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1810 # Not a public wiki, so no shortcut
1811 $useShortcut = false;
1812 } elseif ( !empty( $wgRevokePermissions ) ) {
1814 * Iterate through each group with permissions being revoked (key not included since we don't care
1815 * what the group name is), then check if the read permission is being revoked. If it is, then
1816 * we don't use the shortcut below since the user might not be able to read, even though anon
1817 * reading is allowed.
1819 foreach ( $wgRevokePermissions as $perms ) {
1820 if ( !empty( $perms['read'] ) ) {
1821 # We might be removing the read right from the user, so no shortcut
1822 $useShortcut = false;
1823 break;
1829 $result = null;
1830 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1831 if ( $result !== null ) {
1832 return $result;
1835 # Shortcut for public wikis, allows skipping quite a bit of code
1836 if ( $useShortcut ) {
1837 return true;
1840 if ( $wgUser->isAllowed( 'read' ) ) {
1841 return true;
1842 } else {
1843 global $wgWhitelistRead;
1845 # Always grant access to the login page.
1846 # Even anons need to be able to log in.
1847 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'ChangePassword' ) ) {
1848 return true;
1851 # Bail out if there isn't whitelist
1852 if ( !is_array( $wgWhitelistRead ) ) {
1853 return false;
1856 # Check for explicit whitelisting
1857 $name = $this->getPrefixedText();
1858 $dbName = $this->getPrefixedDBKey();
1859 // Check with and without underscores
1860 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1861 return true;
1863 # Old settings might have the title prefixed with
1864 # a colon for main-namespace pages
1865 if ( $this->getNamespace() == NS_MAIN ) {
1866 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1867 return true;
1871 # If it's a special page, ditch the subpage bit and check again
1872 if ( $this->getNamespace() == NS_SPECIAL ) {
1873 $name = $this->getDBkey();
1874 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
1875 if ( $name === false ) {
1876 # Invalid special page, but we show standard login required message
1877 return false;
1880 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1881 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1882 return true;
1887 return false;
1891 * Is this the mainpage?
1892 * @note Title::newFromText seams to be sufficiently optimized by the title
1893 * cache that we don't need to over-optimize by doing direct comparisons and
1894 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1895 * ends up reporting something differently than $title->isMainPage();
1897 * @return Bool
1899 public function isMainPage() {
1900 return $this->equals( Title::newMainPage() );
1904 * Is this a talk page of some sort?
1906 * @return Bool
1908 public function isTalkPage() {
1909 return MWNamespace::isTalk( $this->getNamespace() );
1913 * Is this a subpage?
1915 * @return Bool
1917 public function isSubpage() {
1918 return MWNamespace::hasSubpages( $this->mNamespace )
1919 ? strpos( $this->getText(), '/' ) !== false
1920 : false;
1924 * Does this have subpages? (Warning, usually requires an extra DB query.)
1926 * @return Bool
1928 public function hasSubpages() {
1929 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1930 # Duh
1931 return false;
1934 # We dynamically add a member variable for the purpose of this method
1935 # alone to cache the result. There's no point in having it hanging
1936 # around uninitialized in every Title object; therefore we only add it
1937 # if needed and don't declare it statically.
1938 if ( isset( $this->mHasSubpages ) ) {
1939 return $this->mHasSubpages;
1942 $subpages = $this->getSubpages( 1 );
1943 if ( $subpages instanceof TitleArray ) {
1944 return $this->mHasSubpages = (bool)$subpages->count();
1946 return $this->mHasSubpages = false;
1950 * Get all subpages of this page.
1952 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1953 * @return mixed TitleArray, or empty array if this page's namespace
1954 * doesn't allow subpages
1956 public function getSubpages( $limit = -1 ) {
1957 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1958 return array();
1961 $dbr = wfGetDB( DB_SLAVE );
1962 $conds['page_namespace'] = $this->getNamespace();
1963 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1964 $options = array();
1965 if ( $limit > -1 ) {
1966 $options['LIMIT'] = $limit;
1968 return $this->mSubpages = TitleArray::newFromResult(
1969 $dbr->select( 'page',
1970 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1971 $conds,
1972 __METHOD__,
1973 $options
1979 * Does that page contain wikitext, or it is JS, CSS or whatever?
1981 * @return Bool
1983 public function isWikitextPage() {
1984 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
1985 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
1986 return $retval;
1990 * Could this page contain custom CSS or JavaScript, based
1991 * on the title?
1993 * @return Bool
1995 public function isCssOrJsPage() {
1996 $retval = $this->mNamespace == NS_MEDIAWIKI
1997 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1998 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
1999 return $retval;
2003 * Is this a .css or .js subpage of a user page?
2004 * @return Bool
2006 public function isCssJsSubpage() {
2007 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
2011 * Is this a *valid* .css or .js subpage of a user page?
2013 * @return Bool
2014 * @deprecated since 1.17
2016 public function isValidCssJsSubpage() {
2017 return $this->isCssJsSubpage();
2021 * Trim down a .css or .js subpage title to get the corresponding skin name
2023 * @return string containing skin name from .css or .js subpage title
2025 public function getSkinFromCssJsSubpage() {
2026 $subpage = explode( '/', $this->mTextform );
2027 $subpage = $subpage[ count( $subpage ) - 1 ];
2028 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
2032 * Is this a .css subpage of a user page?
2034 * @return Bool
2036 public function isCssSubpage() {
2037 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
2041 * Is this a .js subpage of a user page?
2043 * @return Bool
2045 public function isJsSubpage() {
2046 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
2050 * Protect css subpages of user pages: can $wgUser edit
2051 * this page?
2053 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2054 * @return Bool
2056 public function userCanEditCssSubpage() {
2057 global $wgUser;
2058 wfDeprecated( __METHOD__ );
2059 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2060 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2064 * Protect js subpages of user pages: can $wgUser edit
2065 * this page?
2067 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2068 * @return Bool
2070 public function userCanEditJsSubpage() {
2071 global $wgUser;
2072 wfDeprecated( __METHOD__ );
2073 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2074 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2078 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2080 * @return Bool If the page is subject to cascading restrictions.
2082 public function isCascadeProtected() {
2083 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2084 return ( $sources > 0 );
2088 * Cascading protection: Get the source of any cascading restrictions on this page.
2090 * @param $getPages Bool Whether or not to retrieve the actual pages
2091 * that the restrictions have come from.
2092 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2093 * have come, false for none, or true if such restrictions exist, but $getPages
2094 * was not set. The restriction array is an array of each type, each of which
2095 * contains a array of unique groups.
2097 public function getCascadeProtectionSources( $getPages = true ) {
2098 global $wgContLang;
2099 $pagerestrictions = array();
2101 if ( isset( $this->mCascadeSources ) && $getPages ) {
2102 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2103 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2104 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2107 wfProfileIn( __METHOD__ );
2109 $dbr = wfGetDB( DB_SLAVE );
2111 if ( $this->getNamespace() == NS_FILE ) {
2112 $tables = array( 'imagelinks', 'page_restrictions' );
2113 $where_clauses = array(
2114 'il_to' => $this->getDBkey(),
2115 'il_from=pr_page',
2116 'pr_cascade' => 1
2118 } else {
2119 $tables = array( 'templatelinks', 'page_restrictions' );
2120 $where_clauses = array(
2121 'tl_namespace' => $this->getNamespace(),
2122 'tl_title' => $this->getDBkey(),
2123 'tl_from=pr_page',
2124 'pr_cascade' => 1
2128 if ( $getPages ) {
2129 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2130 'pr_expiry', 'pr_type', 'pr_level' );
2131 $where_clauses[] = 'page_id=pr_page';
2132 $tables[] = 'page';
2133 } else {
2134 $cols = array( 'pr_expiry' );
2137 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2139 $sources = $getPages ? array() : false;
2140 $now = wfTimestampNow();
2141 $purgeExpired = false;
2143 foreach ( $res as $row ) {
2144 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2145 if ( $expiry > $now ) {
2146 if ( $getPages ) {
2147 $page_id = $row->pr_page;
2148 $page_ns = $row->page_namespace;
2149 $page_title = $row->page_title;
2150 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2151 # Add groups needed for each restriction type if its not already there
2152 # Make sure this restriction type still exists
2154 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2155 $pagerestrictions[$row->pr_type] = array();
2158 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2159 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2160 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2162 } else {
2163 $sources = true;
2165 } else {
2166 // Trigger lazy purge of expired restrictions from the db
2167 $purgeExpired = true;
2170 if ( $purgeExpired ) {
2171 Title::purgeExpiredRestrictions();
2174 if ( $getPages ) {
2175 $this->mCascadeSources = $sources;
2176 $this->mCascadingRestrictions = $pagerestrictions;
2177 } else {
2178 $this->mHasCascadingRestrictions = $sources;
2181 wfProfileOut( __METHOD__ );
2182 return array( $sources, $pagerestrictions );
2186 * Returns cascading restrictions for the current article
2188 * @return Boolean
2190 function areRestrictionsCascading() {
2191 if ( !$this->mRestrictionsLoaded ) {
2192 $this->loadRestrictions();
2195 return $this->mCascadeRestriction;
2199 * Loads a string into mRestrictions array
2201 * @param $res Resource restrictions as an SQL result.
2202 * @param $oldFashionedRestrictions String comma-separated list of page
2203 * restrictions from page table (pre 1.10)
2205 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2206 $rows = array();
2208 foreach ( $res as $row ) {
2209 $rows[] = $row;
2212 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2216 * Compiles list of active page restrictions from both page table (pre 1.10)
2217 * and page_restrictions table for this existing page.
2218 * Public for usage by LiquidThreads.
2220 * @param $rows array of db result objects
2221 * @param $oldFashionedRestrictions string comma-separated list of page
2222 * restrictions from page table (pre 1.10)
2224 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2225 global $wgContLang;
2226 $dbr = wfGetDB( DB_SLAVE );
2228 $restrictionTypes = $this->getRestrictionTypes();
2230 foreach ( $restrictionTypes as $type ) {
2231 $this->mRestrictions[$type] = array();
2232 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2235 $this->mCascadeRestriction = false;
2237 # Backwards-compatibility: also load the restrictions from the page record (old format).
2239 if ( $oldFashionedRestrictions === null ) {
2240 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2241 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2244 if ( $oldFashionedRestrictions != '' ) {
2246 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2247 $temp = explode( '=', trim( $restrict ) );
2248 if ( count( $temp ) == 1 ) {
2249 // old old format should be treated as edit/move restriction
2250 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2251 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2252 } else {
2253 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2257 $this->mOldRestrictions = true;
2261 if ( count( $rows ) ) {
2262 # Current system - load second to make them override.
2263 $now = wfTimestampNow();
2264 $purgeExpired = false;
2266 # Cycle through all the restrictions.
2267 foreach ( $rows as $row ) {
2269 // Don't take care of restrictions types that aren't allowed
2270 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2271 continue;
2273 // This code should be refactored, now that it's being used more generally,
2274 // But I don't really see any harm in leaving it in Block for now -werdna
2275 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2277 // Only apply the restrictions if they haven't expired!
2278 if ( !$expiry || $expiry > $now ) {
2279 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2280 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2282 $this->mCascadeRestriction |= $row->pr_cascade;
2283 } else {
2284 // Trigger a lazy purge of expired restrictions
2285 $purgeExpired = true;
2289 if ( $purgeExpired ) {
2290 Title::purgeExpiredRestrictions();
2294 $this->mRestrictionsLoaded = true;
2298 * Load restrictions from the page_restrictions table
2300 * @param $oldFashionedRestrictions String comma-separated list of page
2301 * restrictions from page table (pre 1.10)
2303 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2304 global $wgContLang;
2305 if ( !$this->mRestrictionsLoaded ) {
2306 if ( $this->exists() ) {
2307 $dbr = wfGetDB( DB_SLAVE );
2309 $res = $dbr->select(
2310 'page_restrictions',
2311 '*',
2312 array( 'pr_page' => $this->getArticleId() ),
2313 __METHOD__
2316 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2317 } else {
2318 $title_protection = $this->getTitleProtection();
2320 if ( $title_protection ) {
2321 $now = wfTimestampNow();
2322 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2324 if ( !$expiry || $expiry > $now ) {
2325 // Apply the restrictions
2326 $this->mRestrictionsExpiry['create'] = $expiry;
2327 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2328 } else { // Get rid of the old restrictions
2329 Title::purgeExpiredRestrictions();
2330 $this->mTitleProtection = false;
2332 } else {
2333 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2335 $this->mRestrictionsLoaded = true;
2341 * Purge expired restrictions from the page_restrictions table
2343 static function purgeExpiredRestrictions() {
2344 $dbw = wfGetDB( DB_MASTER );
2345 $dbw->delete(
2346 'page_restrictions',
2347 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2348 __METHOD__
2351 $dbw->delete(
2352 'protected_titles',
2353 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2354 __METHOD__
2359 * Accessor/initialisation for mRestrictions
2361 * @param $action String action that permission needs to be checked for
2362 * @return Array of Strings the array of groups allowed to edit this article
2364 public function getRestrictions( $action ) {
2365 if ( !$this->mRestrictionsLoaded ) {
2366 $this->loadRestrictions();
2368 return isset( $this->mRestrictions[$action] )
2369 ? $this->mRestrictions[$action]
2370 : array();
2374 * Get the expiry time for the restriction against a given action
2376 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2377 * or not protected at all, or false if the action is not recognised.
2379 public function getRestrictionExpiry( $action ) {
2380 if ( !$this->mRestrictionsLoaded ) {
2381 $this->loadRestrictions();
2383 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2387 * Is there a version of this page in the deletion archive?
2389 * @param $includeSuppressed Boolean Include suppressed revisions?
2390 * @return Int the number of archived revisions
2392 public function isDeleted( $includeSuppressed = false ) {
2393 if ( $this->getNamespace() < 0 ) {
2394 $n = 0;
2395 } else {
2396 $dbr = wfGetDB( DB_SLAVE );
2397 $conditions = array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() );
2399 if( !$includeSuppressed ) {
2400 $suppressedTextBits = Revision::DELETED_TEXT | Revision::DELETED_RESTRICTED;
2401 $conditions[] = $dbr->bitAnd('ar_deleted', $suppressedTextBits ) .
2402 ' != ' . $suppressedTextBits;
2405 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2406 $conditions,
2407 __METHOD__
2409 if ( $this->getNamespace() == NS_FILE ) {
2410 $fconditions = array( 'fa_name' => $this->getDBkey() );
2411 if( !$includeSuppressed ) {
2412 $suppressedTextBits = File::DELETED_FILE | File::DELETED_RESTRICTED;
2413 $fconditions[] = $dbr->bitAnd('fa_deleted', $suppressedTextBits ) .
2414 ' != ' . $suppressedTextBits;
2417 $n += $dbr->selectField( 'filearchive',
2418 'COUNT(*)',
2419 $fconditions,
2420 __METHOD__
2424 return (int)$n;
2428 * Is there a version of this page in the deletion archive?
2430 * @return Boolean
2432 public function isDeletedQuick() {
2433 if ( $this->getNamespace() < 0 ) {
2434 return false;
2436 $dbr = wfGetDB( DB_SLAVE );
2437 $deleted = (bool)$dbr->selectField( 'archive', '1',
2438 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2439 __METHOD__
2441 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2442 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2443 array( 'fa_name' => $this->getDBkey() ),
2444 __METHOD__
2447 return $deleted;
2451 * Get the article ID for this Title from the link cache,
2452 * adding it if necessary
2454 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2455 * for update
2456 * @return Int the ID
2458 public function getArticleID( $flags = 0 ) {
2459 if ( $this->getNamespace() < 0 ) {
2460 return $this->mArticleID = 0;
2462 $linkCache = LinkCache::singleton();
2463 if ( $flags & self::GAID_FOR_UPDATE ) {
2464 $oldUpdate = $linkCache->forUpdate( true );
2465 $linkCache->clearLink( $this );
2466 $this->mArticleID = $linkCache->addLinkObj( $this );
2467 $linkCache->forUpdate( $oldUpdate );
2468 } else {
2469 if ( -1 == $this->mArticleID ) {
2470 $this->mArticleID = $linkCache->addLinkObj( $this );
2473 return $this->mArticleID;
2477 * Is this an article that is a redirect page?
2478 * Uses link cache, adding it if necessary
2480 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2481 * @return Bool
2483 public function isRedirect( $flags = 0 ) {
2484 if ( !is_null( $this->mRedirect ) ) {
2485 return $this->mRedirect;
2487 # Calling getArticleID() loads the field from cache as needed
2488 if ( !$this->getArticleID( $flags ) ) {
2489 return $this->mRedirect = false;
2491 $linkCache = LinkCache::singleton();
2492 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2494 return $this->mRedirect;
2498 * What is the length of this page?
2499 * Uses link cache, adding it if necessary
2501 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2502 * @return Int
2504 public function getLength( $flags = 0 ) {
2505 if ( $this->mLength != -1 ) {
2506 return $this->mLength;
2508 # Calling getArticleID() loads the field from cache as needed
2509 if ( !$this->getArticleID( $flags ) ) {
2510 return $this->mLength = 0;
2512 $linkCache = LinkCache::singleton();
2513 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2515 return $this->mLength;
2519 * What is the page_latest field for this page?
2521 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2522 * @return Int or 0 if the page doesn't exist
2524 public function getLatestRevID( $flags = 0 ) {
2525 if ( $this->mLatestID !== false ) {
2526 return intval( $this->mLatestID );
2528 # Calling getArticleID() loads the field from cache as needed
2529 if ( !$this->getArticleID( $flags ) ) {
2530 return $this->mLatestID = 0;
2532 $linkCache = LinkCache::singleton();
2533 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2535 return $this->mLatestID;
2539 * This clears some fields in this object, and clears any associated
2540 * keys in the "bad links" section of the link cache.
2542 * - This is called from Article::doEdit() and Article::insertOn() to allow
2543 * loading of the new page_id. It's also called from
2544 * Article::doDeleteArticle()
2546 * @param $newid Int the new Article ID
2548 public function resetArticleID( $newid ) {
2549 $linkCache = LinkCache::singleton();
2550 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2552 if ( $newid === false ) {
2553 $this->mArticleID = -1;
2554 } else {
2555 $this->mArticleID = intval( $newid );
2557 $this->mRestrictionsLoaded = false;
2558 $this->mRestrictions = array();
2559 $this->mRedirect = null;
2560 $this->mLength = -1;
2561 $this->mLatestID = false;
2565 * Updates page_touched for this page; called from LinksUpdate.php
2567 * @return Bool true if the update succeded
2569 public function invalidateCache() {
2570 if ( wfReadOnly() ) {
2571 return;
2573 $dbw = wfGetDB( DB_MASTER );
2574 $success = $dbw->update(
2575 'page',
2576 array( 'page_touched' => $dbw->timestamp() ),
2577 $this->pageCond(),
2578 __METHOD__
2580 HTMLFileCache::clearFileCache( $this );
2581 return $success;
2585 * Prefix some arbitrary text with the namespace or interwiki prefix
2586 * of this object
2588 * @param $name String the text
2589 * @return String the prefixed text
2590 * @private
2592 private function prefix( $name ) {
2593 $p = '';
2594 if ( $this->mInterwiki != '' ) {
2595 $p = $this->mInterwiki . ':';
2598 if ( 0 != $this->mNamespace ) {
2599 $p .= $this->getNsText() . ':';
2601 return $p . $name;
2605 * Returns a simple regex that will match on characters and sequences invalid in titles.
2606 * Note that this doesn't pick up many things that could be wrong with titles, but that
2607 * replacing this regex with something valid will make many titles valid.
2609 * @return String regex string
2611 static function getTitleInvalidRegex() {
2612 static $rxTc = false;
2613 if ( !$rxTc ) {
2614 # Matching titles will be held as illegal.
2615 $rxTc = '/' .
2616 # Any character not allowed is forbidden...
2617 '[^' . Title::legalChars() . ']' .
2618 # URL percent encoding sequences interfere with the ability
2619 # to round-trip titles -- you can't link to them consistently.
2620 '|%[0-9A-Fa-f]{2}' .
2621 # XML/HTML character references produce similar issues.
2622 '|&[A-Za-z0-9\x80-\xff]+;' .
2623 '|&#[0-9]+;' .
2624 '|&#x[0-9A-Fa-f]+;' .
2625 '/S';
2628 return $rxTc;
2632 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2634 * @param $text String containing title to capitalize
2635 * @param $ns int namespace index, defaults to NS_MAIN
2636 * @return String containing capitalized title
2638 public static function capitalize( $text, $ns = NS_MAIN ) {
2639 global $wgContLang;
2641 if ( MWNamespace::isCapitalized( $ns ) ) {
2642 return $wgContLang->ucfirst( $text );
2643 } else {
2644 return $text;
2649 * Secure and split - main initialisation function for this object
2651 * Assumes that mDbkeyform has been set, and is urldecoded
2652 * and uses underscores, but not otherwise munged. This function
2653 * removes illegal characters, splits off the interwiki and
2654 * namespace prefixes, sets the other forms, and canonicalizes
2655 * everything.
2657 * @return Bool true on success
2659 private function secureAndSplit() {
2660 global $wgContLang, $wgLocalInterwiki;
2662 # Initialisation
2663 $this->mInterwiki = $this->mFragment = '';
2664 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2666 $dbkey = $this->mDbkeyform;
2668 # Strip Unicode bidi override characters.
2669 # Sometimes they slip into cut-n-pasted page titles, where the
2670 # override chars get included in list displays.
2671 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2673 # Clean up whitespace
2674 # Note: use of the /u option on preg_replace here will cause
2675 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2676 # conveniently disabling them.
2677 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2678 $dbkey = trim( $dbkey, '_' );
2680 if ( $dbkey == '' ) {
2681 return false;
2684 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2685 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2686 return false;
2689 $this->mDbkeyform = $dbkey;
2691 # Initial colon indicates main namespace rather than specified default
2692 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2693 if ( ':' == $dbkey[0] ) {
2694 $this->mNamespace = NS_MAIN;
2695 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2696 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2699 # Namespace or interwiki prefix
2700 $firstPass = true;
2701 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2702 do {
2703 $m = array();
2704 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2705 $p = $m[1];
2706 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2707 # Ordinary namespace
2708 $dbkey = $m[2];
2709 $this->mNamespace = $ns;
2710 # For Talk:X pages, check if X has a "namespace" prefix
2711 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2712 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2713 # Disallow Talk:File:x type titles...
2714 return false;
2715 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
2716 # Disallow Talk:Interwiki:x type titles...
2717 return false;
2720 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2721 if ( !$firstPass ) {
2722 # Can't make a local interwiki link to an interwiki link.
2723 # That's just crazy!
2724 return false;
2727 # Interwiki link
2728 $dbkey = $m[2];
2729 $this->mInterwiki = $wgContLang->lc( $p );
2731 # Redundant interwiki prefix to the local wiki
2732 if ( $wgLocalInterwiki !== false
2733 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2735 if ( $dbkey == '' ) {
2736 # Can't have an empty self-link
2737 return false;
2739 $this->mInterwiki = '';
2740 $firstPass = false;
2741 # Do another namespace split...
2742 continue;
2745 # If there's an initial colon after the interwiki, that also
2746 # resets the default namespace
2747 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2748 $this->mNamespace = NS_MAIN;
2749 $dbkey = substr( $dbkey, 1 );
2752 # If there's no recognized interwiki or namespace,
2753 # then let the colon expression be part of the title.
2755 break;
2756 } while ( true );
2758 # We already know that some pages won't be in the database!
2759 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2760 $this->mArticleID = 0;
2762 $fragment = strstr( $dbkey, '#' );
2763 if ( false !== $fragment ) {
2764 $this->setFragment( $fragment );
2765 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2766 # remove whitespace again: prevents "Foo_bar_#"
2767 # becoming "Foo_bar_"
2768 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2771 # Reject illegal characters.
2772 $rxTc = self::getTitleInvalidRegex();
2773 if ( preg_match( $rxTc, $dbkey ) ) {
2774 return false;
2777 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2778 # reachable due to the way web browsers deal with 'relative' URLs.
2779 # Also, they conflict with subpage syntax. Forbid them explicitly.
2780 if ( strpos( $dbkey, '.' ) !== false &&
2781 ( $dbkey === '.' || $dbkey === '..' ||
2782 strpos( $dbkey, './' ) === 0 ||
2783 strpos( $dbkey, '../' ) === 0 ||
2784 strpos( $dbkey, '/./' ) !== false ||
2785 strpos( $dbkey, '/../' ) !== false ||
2786 substr( $dbkey, -2 ) == '/.' ||
2787 substr( $dbkey, -3 ) == '/..' ) )
2789 return false;
2792 # Magic tilde sequences? Nu-uh!
2793 if ( strpos( $dbkey, '~~~' ) !== false ) {
2794 return false;
2797 # Limit the size of titles to 255 bytes. This is typically the size of the
2798 # underlying database field. We make an exception for special pages, which
2799 # don't need to be stored in the database, and may edge over 255 bytes due
2800 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2801 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2802 strlen( $dbkey ) > 512 )
2804 return false;
2807 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2808 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2809 # other site might be case-sensitive.
2810 $this->mUserCaseDBKey = $dbkey;
2811 if ( $this->mInterwiki == '' ) {
2812 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2815 # Can't make a link to a namespace alone... "empty" local links can only be
2816 # self-links with a fragment identifier.
2817 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2818 return false;
2821 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2822 // IP names are not allowed for accounts, and can only be referring to
2823 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2824 // there are numerous ways to present the same IP. Having sp:contribs scan
2825 // them all is silly and having some show the edits and others not is
2826 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2827 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2828 ? IP::sanitizeIP( $dbkey )
2829 : $dbkey;
2831 // Any remaining initial :s are illegal.
2832 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2833 return false;
2836 # Fill fields
2837 $this->mDbkeyform = $dbkey;
2838 $this->mUrlform = wfUrlencode( $dbkey );
2840 $this->mTextform = str_replace( '_', ' ', $dbkey );
2842 return true;
2846 * Set the fragment for this title. Removes the first character from the
2847 * specified fragment before setting, so it assumes you're passing it with
2848 * an initial "#".
2850 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2851 * Still in active use privately.
2853 * @param $fragment String text
2855 public function setFragment( $fragment ) {
2856 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2859 public function setInterwiki( $interwiki ) {
2860 $this->mInterwiki = $interwiki;
2864 * Get a Title object associated with the talk page of this article
2866 * @return Title the object for the talk page
2868 public function getTalkPage() {
2869 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2873 * Get a title object associated with the subject page of this
2874 * talk page
2876 * @return Title the object for the subject page
2878 public function getSubjectPage() {
2879 // Is this the same title?
2880 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2881 if ( $this->getNamespace() == $subjectNS ) {
2882 return $this;
2884 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2888 * Get an array of Title objects linking to this Title
2889 * Also stores the IDs in the link cache.
2891 * WARNING: do not use this function on arbitrary user-supplied titles!
2892 * On heavily-used templates it will max out the memory.
2894 * @param $options Array: may be FOR UPDATE
2895 * @param $table String: table name
2896 * @param $prefix String: fields prefix
2897 * @return Array of Title objects linking here
2899 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2900 $linkCache = LinkCache::singleton();
2902 if ( count( $options ) > 0 ) {
2903 $db = wfGetDB( DB_MASTER );
2904 } else {
2905 $db = wfGetDB( DB_SLAVE );
2908 $res = $db->select(
2909 array( 'page', $table ),
2910 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2911 array(
2912 "{$prefix}_from=page_id",
2913 "{$prefix}_namespace" => $this->getNamespace(),
2914 "{$prefix}_title" => $this->getDBkey() ),
2915 __METHOD__,
2916 $options
2919 $retVal = array();
2920 if ( $db->numRows( $res ) ) {
2921 foreach ( $res as $row ) {
2922 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2923 if ( $titleObj ) {
2924 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2925 $retVal[] = $titleObj;
2929 return $retVal;
2933 * Get an array of Title objects using this Title as a template
2934 * Also stores the IDs in the link cache.
2936 * WARNING: do not use this function on arbitrary user-supplied titles!
2937 * On heavily-used templates it will max out the memory.
2939 * @param $options Array: may be FOR UPDATE
2940 * @return Array of Title the Title objects linking here
2942 public function getTemplateLinksTo( $options = array() ) {
2943 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2947 * Get an array of Title objects referring to non-existent articles linked from this page
2949 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2950 * @return Array of Title the Title objects
2952 public function getBrokenLinksFrom() {
2953 if ( $this->getArticleId() == 0 ) {
2954 # All links from article ID 0 are false positives
2955 return array();
2958 $dbr = wfGetDB( DB_SLAVE );
2959 $res = $dbr->select(
2960 array( 'page', 'pagelinks' ),
2961 array( 'pl_namespace', 'pl_title' ),
2962 array(
2963 'pl_from' => $this->getArticleId(),
2964 'page_namespace IS NULL'
2966 __METHOD__, array(),
2967 array(
2968 'page' => array(
2969 'LEFT JOIN',
2970 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2975 $retVal = array();
2976 foreach ( $res as $row ) {
2977 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2979 return $retVal;
2984 * Get a list of URLs to purge from the Squid cache when this
2985 * page changes
2987 * @return Array of String the URLs
2989 public function getSquidURLs() {
2990 global $wgContLang;
2992 $urls = array(
2993 $this->getInternalURL(),
2994 $this->getInternalURL( 'action=history' )
2997 // purge variant urls as well
2998 if ( $wgContLang->hasVariants() ) {
2999 $variants = $wgContLang->getVariants();
3000 foreach ( $variants as $vCode ) {
3001 $urls[] = $this->getInternalURL( '', $vCode );
3005 return $urls;
3009 * Purge all applicable Squid URLs
3011 public function purgeSquid() {
3012 global $wgUseSquid;
3013 if ( $wgUseSquid ) {
3014 $urls = $this->getSquidURLs();
3015 $u = new SquidUpdate( $urls );
3016 $u->doUpdate();
3021 * Move this page without authentication
3023 * @param $nt Title the new page Title
3024 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3026 public function moveNoAuth( &$nt ) {
3027 return $this->moveTo( $nt, false );
3031 * Check whether a given move operation would be valid.
3032 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3034 * @param $nt Title the new title
3035 * @param $auth Bool indicates whether $wgUser's permissions
3036 * should be checked
3037 * @param $reason String is the log summary of the move, used for spam checking
3038 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3040 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3041 global $wgUser;
3043 $errors = array();
3044 if ( !$nt ) {
3045 // Normally we'd add this to $errors, but we'll get
3046 // lots of syntax errors if $nt is not an object
3047 return array( array( 'badtitletext' ) );
3049 if ( $this->equals( $nt ) ) {
3050 $errors[] = array( 'selfmove' );
3052 if ( !$this->isMovable() ) {
3053 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3055 if ( $nt->getInterwiki() != '' ) {
3056 $errors[] = array( 'immobile-target-namespace-iw' );
3058 if ( !$nt->isMovable() ) {
3059 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3062 $oldid = $this->getArticleID();
3063 $newid = $nt->getArticleID();
3065 if ( strlen( $nt->getDBkey() ) < 1 ) {
3066 $errors[] = array( 'articleexists' );
3068 if ( ( $this->getDBkey() == '' ) ||
3069 ( !$oldid ) ||
3070 ( $nt->getDBkey() == '' ) ) {
3071 $errors[] = array( 'badarticleerror' );
3074 // Image-specific checks
3075 if ( $this->getNamespace() == NS_FILE ) {
3076 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3079 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3080 $errors[] = array( 'nonfile-cannot-move-to-file' );
3083 if ( $auth ) {
3084 $errors = wfMergeErrorArrays( $errors,
3085 $this->getUserPermissionsErrors( 'move', $wgUser ),
3086 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3087 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3088 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3091 $match = EditPage::matchSummarySpamRegex( $reason );
3092 if ( $match !== false ) {
3093 // This is kind of lame, won't display nice
3094 $errors[] = array( 'spamprotectiontext' );
3097 $err = null;
3098 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3099 $errors[] = array( 'hookaborted', $err );
3102 # The move is allowed only if (1) the target doesn't exist, or
3103 # (2) the target is a redirect to the source, and has no history
3104 # (so we can undo bad moves right after they're done).
3106 if ( 0 != $newid ) { # Target exists; check for validity
3107 if ( !$this->isValidMoveTarget( $nt ) ) {
3108 $errors[] = array( 'articleexists' );
3110 } else {
3111 $tp = $nt->getTitleProtection();
3112 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3113 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3114 $errors[] = array( 'cantmove-titleprotected' );
3117 if ( empty( $errors ) ) {
3118 return true;
3120 return $errors;
3124 * Check if the requested move target is a valid file move target
3125 * @param Title $nt Target title
3126 * @return array List of errors
3128 protected function validateFileMoveOperation( $nt ) {
3129 global $wgUser;
3131 $errors = array();
3133 if ( $nt->getNamespace() != NS_FILE ) {
3134 $errors[] = array( 'imagenocrossnamespace' );
3137 $file = wfLocalFile( $this );
3138 if ( $file->exists() ) {
3139 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3140 $errors[] = array( 'imageinvalidfilename' );
3142 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3143 $errors[] = array( 'imagetypemismatch' );
3147 $destFile = wfLocalFile( $nt );
3148 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3149 $errors[] = array( 'file-exists-sharedrepo' );
3152 return $errors;
3156 * Move a title to a new location
3158 * @param $nt Title the new title
3159 * @param $auth Bool indicates whether $wgUser's permissions
3160 * should be checked
3161 * @param $reason String the reason for the move
3162 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3163 * Ignored if the user doesn't have the suppressredirect right.
3164 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3166 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3167 global $wgEnableInterwikiTemplatesTracking, $wgGlobalDatabase;
3169 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3170 if ( is_array( $err ) ) {
3171 return $err;
3174 // If it is a file, move it first. It is done before all other moving stuff is
3175 // done because it's hard to revert
3176 $dbw = wfGetDB( DB_MASTER );
3177 if ( $this->getNamespace() == NS_FILE ) {
3178 $file = wfLocalFile( $this );
3179 if ( $file->exists() ) {
3180 $status = $file->move( $nt );
3181 if ( !$status->isOk() ) {
3182 return $status->getErrorsArray();
3187 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3188 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3189 $protected = $this->isProtected();
3190 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3192 // Do the actual move
3193 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
3194 if ( is_array( $err ) ) {
3195 # @todo FIXME: What about the File we have already moved?
3196 $dbw->rollback();
3197 return $err;
3200 $redirid = $this->getArticleID();
3202 // Refresh the sortkey for this row. Be careful to avoid resetting
3203 // cl_timestamp, which may disturb time-based lists on some sites.
3204 $prefixes = $dbw->select(
3205 'categorylinks',
3206 array( 'cl_sortkey_prefix', 'cl_to' ),
3207 array( 'cl_from' => $pageid ),
3208 __METHOD__
3210 foreach ( $prefixes as $prefixRow ) {
3211 $prefix = $prefixRow->cl_sortkey_prefix;
3212 $catTo = $prefixRow->cl_to;
3213 $dbw->update( 'categorylinks',
3214 array(
3215 'cl_sortkey' => Collation::singleton()->getSortKey(
3216 $nt->getCategorySortkey( $prefix ) ),
3217 'cl_timestamp=cl_timestamp' ),
3218 array(
3219 'cl_from' => $pageid,
3220 'cl_to' => $catTo ),
3221 __METHOD__
3225 if ( $wgEnableInterwikiTemplatesTracking && $wgGlobalDatabase ) {
3226 $dbw2 = wfGetDB( DB_MASTER, array(), $wgGlobalDatabase );
3227 $dbw2->update( 'globaltemplatelinks',
3228 array( 'gtl_from_namespace' => $nt->getNamespace(),
3229 'gtl_from_title' => $nt->getText() ),
3230 array ( 'gtl_from_page' => $pageid ),
3231 __METHOD__ );
3234 if ( $protected ) {
3235 # Protect the redirect title as the title used to be...
3236 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3237 array(
3238 'pr_page' => $redirid,
3239 'pr_type' => 'pr_type',
3240 'pr_level' => 'pr_level',
3241 'pr_cascade' => 'pr_cascade',
3242 'pr_user' => 'pr_user',
3243 'pr_expiry' => 'pr_expiry'
3245 array( 'pr_page' => $pageid ),
3246 __METHOD__,
3247 array( 'IGNORE' )
3249 # Update the protection log
3250 $log = new LogPage( 'protect' );
3251 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3252 if ( $reason ) {
3253 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3255 // @todo FIXME: $params?
3256 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3259 # Update watchlists
3260 $oldnamespace = $this->getNamespace() & ~1;
3261 $newnamespace = $nt->getNamespace() & ~1;
3262 $oldtitle = $this->getDBkey();
3263 $newtitle = $nt->getDBkey();
3265 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3266 WatchedItem::duplicateEntries( $this, $nt );
3269 # Update search engine
3270 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3271 $u->doUpdate();
3272 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3273 $u->doUpdate();
3275 $dbw->commit();
3277 # Update site_stats
3278 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3279 # No longer a content page
3280 # Not viewed, edited, removing
3281 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3282 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3283 # Now a content page
3284 # Not viewed, edited, adding
3285 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3286 } elseif ( $pageCountChange ) {
3287 # Redirect added
3288 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3289 } else {
3290 # Nothing special
3291 $u = false;
3293 if ( $u ) {
3294 $u->doUpdate();
3297 # Update message cache for interface messages
3298 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3299 # @bug 17860: old article can be deleted, if this the case,
3300 # delete it from message cache
3301 if ( $this->getArticleID() === 0 ) {
3302 MessageCache::singleton()->replace( $this->getDBkey(), false );
3303 } else {
3304 $oldarticle = new Article( $this );
3305 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3308 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3309 $newarticle = new Article( $nt );
3310 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3313 global $wgUser;
3314 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3315 return true;
3319 * Move page to a title which is either a redirect to the
3320 * source page or nonexistent
3322 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3323 * @param $reason String The reason for the move
3324 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3325 * if the user doesn't have the suppressredirect right
3327 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3328 global $wgUser, $wgContLang, $wgEnableInterwikiTemplatesTracking, $wgGlobalDatabase;
3330 $moveOverRedirect = $nt->exists();
3332 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3333 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3335 if ( $reason ) {
3336 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3338 # Truncate for whole multibyte characters.
3339 $comment = $wgContLang->truncate( $comment, 255 );
3341 $oldid = $this->getArticleID();
3342 $latest = $this->getLatestRevID();
3344 $dbw = wfGetDB( DB_MASTER );
3346 if ( $moveOverRedirect ) {
3347 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3349 $newid = $nt->getArticleID();
3350 $newns = $nt->getNamespace();
3351 $newdbk = $nt->getDBkey();
3353 # Delete the old redirect. We don't save it to history since
3354 # by definition if we've got here it's rather uninteresting.
3355 # We have to remove it so that the next step doesn't trigger
3356 # a conflict on the unique namespace+title index...
3357 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3358 if ( !$dbw->cascadingDeletes() ) {
3359 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3360 global $wgUseTrackbacks;
3361 if ( $wgUseTrackbacks ) {
3362 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3364 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3365 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3366 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3367 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3368 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3369 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3370 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3371 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__ );
3373 // If the target page was recently created, it may have an entry in recentchanges still
3374 $dbw->delete( 'recentchanges',
3375 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3376 __METHOD__
3379 if ( $wgEnableInterwikiTemplatesTracking && $wgGlobalDatabase ) {
3380 $dbw2 = wfGetDB( DB_MASTER, array(), $wgGlobalDatabase );
3381 $dbw2->delete( 'globaltemplatelinks',
3382 array( 'gtl_from_wiki' => wfGetID(),
3383 'gtl_from_page' => $newid ),
3384 __METHOD__ );
3388 # Save a null revision in the page's history notifying of the move
3389 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3390 if ( !is_object( $nullRevision ) ) {
3391 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3393 $nullRevId = $nullRevision->insertOn( $dbw );
3395 $now = wfTimestampNow();
3396 # Change the name of the target page:
3397 $dbw->update( 'page',
3398 /* SET */ array(
3399 'page_touched' => $dbw->timestamp( $now ),
3400 'page_namespace' => $nt->getNamespace(),
3401 'page_title' => $nt->getDBkey(),
3402 'page_latest' => $nullRevId,
3404 /* WHERE */ array( 'page_id' => $oldid ),
3405 __METHOD__
3407 $nt->resetArticleID( $oldid );
3409 $article = new Article( $nt );
3410 wfRunHooks( 'NewRevisionFromEditComplete',
3411 array( $article, $nullRevision, $latest, $wgUser ) );
3412 $article->setCachedLastEditTime( $now );
3414 # Recreate the redirect, this time in the other direction.
3415 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3416 $mwRedir = MagicWord::get( 'redirect' );
3417 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3418 $redirectArticle = new Article( $this );
3419 $newid = $redirectArticle->insertOn( $dbw );
3420 if ( $newid ) { // sanity
3421 $redirectRevision = new Revision( array(
3422 'page' => $newid,
3423 'comment' => $comment,
3424 'text' => $redirectText ) );
3425 $redirectRevision->insertOn( $dbw );
3426 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3428 wfRunHooks( 'NewRevisionFromEditComplete',
3429 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3431 # Now, we record the link from the redirect to the new title.
3432 # It should have no other outgoing links...
3433 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3434 $dbw->insert( 'pagelinks',
3435 array(
3436 'pl_from' => $newid,
3437 'pl_namespace' => $nt->getNamespace(),
3438 'pl_title' => $nt->getDBkey() ),
3439 __METHOD__ );
3441 $redirectSuppressed = false;
3442 } else {
3443 $this->resetArticleID( 0 );
3444 $redirectSuppressed = true;
3447 # Log the move
3448 $log = new LogPage( 'move' );
3449 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3450 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3452 # Purge caches for old and new titles
3453 if ( $moveOverRedirect ) {
3454 # A simple purge is enough when moving over a redirect
3455 $nt->purgeSquid();
3456 } else {
3457 # Purge caches as per article creation, including any pages that link to this title
3458 Article::onArticleCreate( $nt );
3460 $this->purgeSquid();
3464 * Move this page's subpages to be subpages of $nt
3466 * @param $nt Title Move target
3467 * @param $auth bool Whether $wgUser's permissions should be checked
3468 * @param $reason string The reason for the move
3469 * @param $createRedirect bool Whether to create redirects from the old subpages to
3470 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3471 * @return mixed array with old page titles as keys, and strings (new page titles) or
3472 * arrays (errors) as values, or an error array with numeric indices if no pages
3473 * were moved
3475 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3476 global $wgMaximumMovedPages;
3477 // Check permissions
3478 if ( !$this->userCan( 'move-subpages' ) ) {
3479 return array( 'cant-move-subpages' );
3481 // Do the source and target namespaces support subpages?
3482 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3483 return array( 'namespace-nosubpages',
3484 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3486 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3487 return array( 'namespace-nosubpages',
3488 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3491 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3492 $retval = array();
3493 $count = 0;
3494 foreach ( $subpages as $oldSubpage ) {
3495 $count++;
3496 if ( $count > $wgMaximumMovedPages ) {
3497 $retval[$oldSubpage->getPrefixedTitle()] =
3498 array( 'movepage-max-pages',
3499 $wgMaximumMovedPages );
3500 break;
3503 // We don't know whether this function was called before
3504 // or after moving the root page, so check both
3505 // $this and $nt
3506 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3507 $oldSubpage->getArticleID() == $nt->getArticleId() )
3509 // When moving a page to a subpage of itself,
3510 // don't move it twice
3511 continue;
3513 $newPageName = preg_replace(
3514 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3515 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3516 $oldSubpage->getDBkey() );
3517 if ( $oldSubpage->isTalkPage() ) {
3518 $newNs = $nt->getTalkPage()->getNamespace();
3519 } else {
3520 $newNs = $nt->getSubjectPage()->getNamespace();
3522 # Bug 14385: we need makeTitleSafe because the new page names may
3523 # be longer than 255 characters.
3524 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3526 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3527 if ( $success === true ) {
3528 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3529 } else {
3530 $retval[$oldSubpage->getPrefixedText()] = $success;
3533 return $retval;
3537 * Checks if this page is just a one-rev redirect.
3538 * Adds lock, so don't use just for light purposes.
3540 * @return Bool
3542 public function isSingleRevRedirect() {
3543 $dbw = wfGetDB( DB_MASTER );
3544 # Is it a redirect?
3545 $row = $dbw->selectRow( 'page',
3546 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3547 $this->pageCond(),
3548 __METHOD__,
3549 array( 'FOR UPDATE' )
3551 # Cache some fields we may want
3552 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3553 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3554 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3555 if ( !$this->mRedirect ) {
3556 return false;
3558 # Does the article have a history?
3559 $row = $dbw->selectField( array( 'page', 'revision' ),
3560 'rev_id',
3561 array( 'page_namespace' => $this->getNamespace(),
3562 'page_title' => $this->getDBkey(),
3563 'page_id=rev_page',
3564 'page_latest != rev_id'
3566 __METHOD__,
3567 array( 'FOR UPDATE' )
3569 # Return true if there was no history
3570 return ( $row === false );
3574 * Checks if $this can be moved to a given Title
3575 * - Selects for update, so don't call it unless you mean business
3577 * @param $nt Title the new title to check
3578 * @return Bool
3580 public function isValidMoveTarget( $nt ) {
3581 # Is it an existing file?
3582 if ( $nt->getNamespace() == NS_FILE ) {
3583 $file = wfLocalFile( $nt );
3584 if ( $file->exists() ) {
3585 wfDebug( __METHOD__ . ": file exists\n" );
3586 return false;
3589 # Is it a redirect with no history?
3590 if ( !$nt->isSingleRevRedirect() ) {
3591 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3592 return false;
3594 # Get the article text
3595 $rev = Revision::newFromTitle( $nt );
3596 $text = $rev->getText();
3597 # Does the redirect point to the source?
3598 # Or is it a broken self-redirect, usually caused by namespace collisions?
3599 $m = array();
3600 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3601 $redirTitle = Title::newFromText( $m[1] );
3602 if ( !is_object( $redirTitle ) ||
3603 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3604 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3605 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3606 return false;
3608 } else {
3609 # Fail safe
3610 wfDebug( __METHOD__ . ": failsafe\n" );
3611 return false;
3613 return true;
3617 * Can this title be added to a user's watchlist?
3619 * @return Bool TRUE or FALSE
3621 public function isWatchable() {
3622 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3626 * Get categories to which this Title belongs and return an array of
3627 * categories' names.
3629 * @return Array of parents in the form:
3630 * $parent => $currentarticle
3632 public function getParentCategories() {
3633 global $wgContLang;
3635 $data = array();
3637 $titleKey = $this->getArticleId();
3639 if ( $titleKey === 0 ) {
3640 return $data;
3643 $dbr = wfGetDB( DB_SLAVE );
3645 $res = $dbr->select( 'categorylinks', '*',
3646 array(
3647 'cl_from' => $titleKey,
3649 __METHOD__,
3650 array()
3653 if ( $dbr->numRows( $res ) > 0 ) {
3654 foreach ( $res as $row ) {
3655 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3656 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3659 return $data;
3663 * Get a tree of parent categories
3665 * @param $children Array with the children in the keys, to check for circular refs
3666 * @return Array Tree of parent categories
3668 public function getParentCategoryTree( $children = array() ) {
3669 $stack = array();
3670 $parents = $this->getParentCategories();
3672 if ( $parents ) {
3673 foreach ( $parents as $parent => $current ) {
3674 if ( array_key_exists( $parent, $children ) ) {
3675 # Circular reference
3676 $stack[$parent] = array();
3677 } else {
3678 $nt = Title::newFromText( $parent );
3679 if ( $nt ) {
3680 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3686 return $stack;
3690 * Get an associative array for selecting this title from
3691 * the "page" table
3693 * @return Array suitable for the $where parameter of DB::select()
3695 public function pageCond() {
3696 if ( $this->mArticleID > 0 ) {
3697 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3698 return array( 'page_id' => $this->mArticleID );
3699 } else {
3700 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3705 * Get the revision ID of the previous revision
3707 * @param $revId Int Revision ID. Get the revision that was before this one.
3708 * @param $flags Int Title::GAID_FOR_UPDATE
3709 * @return Int|Bool Old revision ID, or FALSE if none exists
3711 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3712 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3713 return $db->selectField( 'revision', 'rev_id',
3714 array(
3715 'rev_page' => $this->getArticleId( $flags ),
3716 'rev_id < ' . intval( $revId )
3718 __METHOD__,
3719 array( 'ORDER BY' => 'rev_id DESC' )
3724 * Get the revision ID of the next revision
3726 * @param $revId Int Revision ID. Get the revision that was after this one.
3727 * @param $flags Int Title::GAID_FOR_UPDATE
3728 * @return Int|Bool Next revision ID, or FALSE if none exists
3730 public function getNextRevisionID( $revId, $flags = 0 ) {
3731 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3732 return $db->selectField( 'revision', 'rev_id',
3733 array(
3734 'rev_page' => $this->getArticleId( $flags ),
3735 'rev_id > ' . intval( $revId )
3737 __METHOD__,
3738 array( 'ORDER BY' => 'rev_id' )
3743 * Get the first revision of the page
3745 * @param $flags Int Title::GAID_FOR_UPDATE
3746 * @return Revision|Null if page doesn't exist
3748 public function getFirstRevision( $flags = 0 ) {
3749 $pageId = $this->getArticleId( $flags );
3750 if ( $pageId ) {
3751 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3752 $row = $db->selectRow( 'revision', '*',
3753 array( 'rev_page' => $pageId ),
3754 __METHOD__,
3755 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3757 if ( $row ) {
3758 return new Revision( $row );
3761 return null;
3765 * Get the oldest revision timestamp of this page
3767 * @param $flags Int Title::GAID_FOR_UPDATE
3768 * @return String: MW timestamp
3770 public function getEarliestRevTime( $flags = 0 ) {
3771 $rev = $this->getFirstRevision( $flags );
3772 return $rev ? $rev->getTimestamp() : null;
3776 * Check if this is a new page
3778 * @return bool
3780 public function isNewPage() {
3781 $dbr = wfGetDB( DB_SLAVE );
3782 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3786 * Get the number of revisions between the given revision.
3787 * Used for diffs and other things that really need it.
3789 * @param $old int|Revision Old revision or rev ID (first before range)
3790 * @param $new int|Revision New revision or rev ID (first after range)
3791 * @return Int Number of revisions between these revisions.
3793 public function countRevisionsBetween( $old, $new ) {
3794 if ( !( $old instanceof Revision ) ) {
3795 $old = Revision::newFromTitle( $this, (int)$old );
3797 if ( !( $new instanceof Revision ) ) {
3798 $new = Revision::newFromTitle( $this, (int)$new );
3800 if ( !$old || !$new ) {
3801 return 0; // nothing to compare
3803 $dbr = wfGetDB( DB_SLAVE );
3804 return (int)$dbr->selectField( 'revision', 'count(*)',
3805 array(
3806 'rev_page' => $this->getArticleId(),
3807 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3808 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3810 __METHOD__
3815 * Get the number of authors between the given revision IDs.
3816 * Used for diffs and other things that really need it.
3818 * @param $old int|Revision Old revision or rev ID (first before range)
3819 * @param $new int|Revision New revision or rev ID (first after range)
3820 * @param $limit Int Maximum number of authors
3821 * @return Int Number of revision authors between these revisions.
3823 public function countAuthorsBetween( $old, $new, $limit ) {
3824 if ( !( $old instanceof Revision ) ) {
3825 $old = Revision::newFromTitle( $this, (int)$old );
3827 if ( !( $new instanceof Revision ) ) {
3828 $new = Revision::newFromTitle( $this, (int)$new );
3830 if ( !$old || !$new ) {
3831 return 0; // nothing to compare
3833 $dbr = wfGetDB( DB_SLAVE );
3834 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3835 array(
3836 'rev_page' => $this->getArticleID(),
3837 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3838 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3839 ), __METHOD__,
3840 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
3842 return (int)$dbr->numRows( $res );
3846 * Compare with another title.
3848 * @param $title Title
3849 * @return Bool
3851 public function equals( Title $title ) {
3852 // Note: === is necessary for proper matching of number-like titles.
3853 return $this->getInterwiki() === $title->getInterwiki()
3854 && $this->getNamespace() == $title->getNamespace()
3855 && $this->getDBkey() === $title->getDBkey();
3859 * Callback for usort() to do title sorts by (namespace, title)
3861 * @param $a Title
3862 * @param $b Title
3864 * @return Integer: result of string comparison, or namespace comparison
3866 public static function compare( $a, $b ) {
3867 if ( $a->getNamespace() == $b->getNamespace() ) {
3868 return strcmp( $a->getText(), $b->getText() );
3869 } else {
3870 return $a->getNamespace() - $b->getNamespace();
3875 * Return a string representation of this title
3877 * @return String representation of this title
3879 public function __toString() {
3880 return $this->getPrefixedText();
3884 * Check if page exists. For historical reasons, this function simply
3885 * checks for the existence of the title in the page table, and will
3886 * thus return false for interwiki links, special pages and the like.
3887 * If you want to know if a title can be meaningfully viewed, you should
3888 * probably call the isKnown() method instead.
3890 * @return Bool
3892 public function exists() {
3893 return $this->getArticleId() != 0;
3897 * Should links to this title be shown as potentially viewable (i.e. as
3898 * "bluelinks"), even if there's no record by this title in the page
3899 * table?
3901 * This function is semi-deprecated for public use, as well as somewhat
3902 * misleadingly named. You probably just want to call isKnown(), which
3903 * calls this function internally.
3905 * (ISSUE: Most of these checks are cheap, but the file existence check
3906 * can potentially be quite expensive. Including it here fixes a lot of
3907 * existing code, but we might want to add an optional parameter to skip
3908 * it and any other expensive checks.)
3910 * @return Bool
3912 public function isAlwaysKnown() {
3913 if ( $this->mInterwiki != '' ) {
3914 return true; // any interwiki link might be viewable, for all we know
3916 switch( $this->mNamespace ) {
3917 case NS_MEDIA:
3918 case NS_FILE:
3919 // file exists, possibly in a foreign repo
3920 return (bool)wfFindFile( $this );
3921 case NS_SPECIAL:
3922 // valid special page
3923 return SpecialPageFactory::exists( $this->getDBkey() );
3924 case NS_MAIN:
3925 // selflink, possibly with fragment
3926 return $this->mDbkeyform == '';
3927 case NS_MEDIAWIKI:
3928 // known system message
3929 return $this->getDefaultMessageText() !== false;
3930 default:
3931 return false;
3936 * Does this title refer to a page that can (or might) be meaningfully
3937 * viewed? In particular, this function may be used to determine if
3938 * links to the title should be rendered as "bluelinks" (as opposed to
3939 * "redlinks" to non-existent pages).
3941 * @return Bool
3943 public function isKnown() {
3944 return $this->isAlwaysKnown() || $this->exists();
3948 * Does this page have source text?
3950 * @return Boolean
3952 public function hasSourceText() {
3953 if ( $this->exists() ) {
3954 return true;
3957 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3958 // If the page doesn't exist but is a known system message, default
3959 // message content will be displayed, same for language subpages
3960 return $this->getDefaultMessageText() !== false;
3963 return false;
3967 * Get the default message text or false if the message doesn't exist
3969 * @return String or false
3971 public function getDefaultMessageText() {
3972 global $wgContLang;
3974 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3975 return false;
3978 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3979 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3981 if ( $message->exists() ) {
3982 return $message->plain();
3983 } else {
3984 return false;
3989 * Is this in a namespace that allows actual pages?
3991 * @return Bool
3992 * @internal note -- uses hardcoded namespace index instead of constants
3994 public function canExist() {
3995 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3999 * Update page_touched timestamps and send squid purge messages for
4000 * pages linking to this title. May be sent to the job queue depending
4001 * on the number of links. Typically called on create and delete.
4003 public function touchLinks() {
4004 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4005 $u->doUpdate();
4007 if ( $this->getNamespace() == NS_CATEGORY ) {
4008 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4009 $u->doUpdate();
4014 * Get the last touched timestamp
4016 * @param $db DatabaseBase: optional db
4017 * @return String last-touched timestamp
4019 public function getTouched( $db = null ) {
4020 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4021 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4022 return $touched;
4026 * Get the timestamp when this page was updated since the user last saw it.
4028 * @param $user User
4029 * @return String|Null
4031 public function getNotificationTimestamp( $user = null ) {
4032 global $wgUser, $wgShowUpdatedMarker;
4033 // Assume current user if none given
4034 if ( !$user ) {
4035 $user = $wgUser;
4037 // Check cache first
4038 $uid = $user->getId();
4039 // avoid isset here, as it'll return false for null entries
4040 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4041 return $this->mNotificationTimestamp[$uid];
4043 if ( !$uid || !$wgShowUpdatedMarker ) {
4044 return $this->mNotificationTimestamp[$uid] = false;
4046 // Don't cache too much!
4047 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4048 $this->mNotificationTimestamp = array();
4050 $dbr = wfGetDB( DB_SLAVE );
4051 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4052 'wl_notificationtimestamp',
4053 array( 'wl_namespace' => $this->getNamespace(),
4054 'wl_title' => $this->getDBkey(),
4055 'wl_user' => $user->getId()
4057 __METHOD__
4059 return $this->mNotificationTimestamp[$uid];
4063 * Get the trackback URL for this page
4065 * @return String Trackback URL
4067 public function trackbackURL() {
4068 global $wgScriptPath, $wgServer, $wgScriptExtension;
4070 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
4071 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
4075 * Get the trackback RDF for this page
4077 * @return String Trackback RDF
4079 public function trackbackRDF() {
4080 $url = htmlspecialchars( $this->getFullURL() );
4081 $title = htmlspecialchars( $this->getText() );
4082 $tburl = $this->trackbackURL();
4084 // Autodiscovery RDF is placed in comments so HTML validator
4085 // won't barf. This is a rather icky workaround, but seems
4086 // frequently used by this kind of RDF thingy.
4088 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
4089 return "<!--
4090 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
4091 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
4092 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
4093 <rdf:Description
4094 rdf:about=\"$url\"
4095 dc:identifier=\"$url\"
4096 dc:title=\"$title\"
4097 trackback:ping=\"$tburl\" />
4098 </rdf:RDF>
4099 -->";
4103 * Generate strings used for xml 'id' names in monobook tabs
4105 * @param $prepend string defaults to 'nstab-'
4106 * @return String XML 'id' name
4108 public function getNamespaceKey( $prepend = 'nstab-' ) {
4109 global $wgContLang;
4110 // Gets the subject namespace if this title
4111 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4112 // Checks if cononical namespace name exists for namespace
4113 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4114 // Uses canonical namespace name
4115 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4116 } else {
4117 // Uses text of namespace
4118 $namespaceKey = $this->getSubjectNsText();
4120 // Makes namespace key lowercase
4121 $namespaceKey = $wgContLang->lc( $namespaceKey );
4122 // Uses main
4123 if ( $namespaceKey == '' ) {
4124 $namespaceKey = 'main';
4126 // Changes file to image for backwards compatibility
4127 if ( $namespaceKey == 'file' ) {
4128 $namespaceKey = 'image';
4130 return $prepend . $namespaceKey;
4134 * Returns true if this is a special page.
4136 * @return boolean
4138 public function isSpecialPage() {
4139 return $this->getNamespace() == NS_SPECIAL;
4143 * Returns true if this title resolves to the named special page
4145 * @param $name String The special page name
4146 * @return boolean
4148 public function isSpecial( $name ) {
4149 if ( $this->getNamespace() == NS_SPECIAL ) {
4150 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
4151 if ( $name == $thisName ) {
4152 return true;
4155 return false;
4159 * If the Title refers to a special page alias which is not the local default, resolve
4160 * the alias, and localise the name as necessary. Otherwise, return $this
4162 * @return Title
4164 public function fixSpecialName() {
4165 if ( $this->getNamespace() == NS_SPECIAL ) {
4166 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
4167 if ( $canonicalName ) {
4168 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName );
4169 if ( $localName != $this->mDbkeyform ) {
4170 return Title::makeTitle( NS_SPECIAL, $localName );
4174 return $this;
4178 * Is this Title in a namespace which contains content?
4179 * In other words, is this a content page, for the purposes of calculating
4180 * statistics, etc?
4182 * @return Boolean
4184 public function isContentPage() {
4185 return MWNamespace::isContent( $this->getNamespace() );
4189 * Get all extant redirects to this Title
4191 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4192 * @return Array of Title redirects to this title
4194 public function getRedirectsHere( $ns = null ) {
4195 $redirs = array();
4197 $dbr = wfGetDB( DB_SLAVE );
4198 $where = array(
4199 'rd_namespace' => $this->getNamespace(),
4200 'rd_title' => $this->getDBkey(),
4201 'rd_from = page_id'
4203 if ( !is_null( $ns ) ) {
4204 $where['page_namespace'] = $ns;
4207 $res = $dbr->select(
4208 array( 'redirect', 'page' ),
4209 array( 'page_namespace', 'page_title' ),
4210 $where,
4211 __METHOD__
4214 foreach ( $res as $row ) {
4215 $redirs[] = self::newFromRow( $row );
4217 return $redirs;
4221 * Check if this Title is a valid redirect target
4223 * @return Bool
4225 public function isValidRedirectTarget() {
4226 global $wgInvalidRedirectTargets;
4228 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4229 if ( $this->isSpecial( 'Userlogout' ) ) {
4230 return false;
4233 foreach ( $wgInvalidRedirectTargets as $target ) {
4234 if ( $this->isSpecial( $target ) ) {
4235 return false;
4239 return true;
4243 * Get a backlink cache object
4245 * @return object BacklinkCache
4247 function getBacklinkCache() {
4248 if ( is_null( $this->mBacklinkCache ) ) {
4249 $this->mBacklinkCache = new BacklinkCache( $this );
4251 return $this->mBacklinkCache;
4255 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4257 * @return Boolean
4259 public function canUseNoindex() {
4260 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4262 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4263 ? $wgContentNamespaces
4264 : $wgExemptFromUserRobotsControl;
4266 return !in_array( $this->mNamespace, $bannedNamespaces );
4271 * Returns restriction types for the current Title
4273 * @return array applicable restriction types
4275 public function getRestrictionTypes() {
4276 if ( $this->getNamespace() == NS_SPECIAL ) {
4277 return array();
4280 $types = self::getFilteredRestrictionTypes( $this->exists() );
4282 if ( $this->getNamespace() != NS_FILE ) {
4283 # Remove the upload restriction for non-file titles
4284 $types = array_diff( $types, array( 'upload' ) );
4287 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4289 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4290 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4292 return $types;
4295 * Get a filtered list of all restriction types supported by this wiki.
4296 * @param bool $exists True to get all restriction types that apply to
4297 * titles that do exist, False for all restriction types that apply to
4298 * titles that do not exist
4299 * @return array
4301 public static function getFilteredRestrictionTypes( $exists = true ) {
4302 global $wgRestrictionTypes;
4303 $types = $wgRestrictionTypes;
4304 if ( $exists ) {
4305 # Remove the create restriction for existing titles
4306 $types = array_diff( $types, array( 'create' ) );
4307 } else {
4308 # Only the create and upload restrictions apply to non-existing titles
4309 $types = array_intersect( $types, array( 'create', 'upload' ) );
4311 return $types;
4315 * Returns the raw sort key to be used for categories, with the specified
4316 * prefix. This will be fed to Collation::getSortKey() to get a
4317 * binary sortkey that can be used for actual sorting.
4319 * @param $prefix string The prefix to be used, specified using
4320 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4321 * prefix.
4322 * @return string
4324 public function getCategorySortkey( $prefix = '' ) {
4325 $unprefixed = $this->getText();
4327 // Anything that uses this hook should only depend
4328 // on the Title object passed in, and should probably
4329 // tell the users to run updateCollations.php --force
4330 // in order to re-sort existing category relations.
4331 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4332 if ( $prefix !== '' ) {
4333 # Separate with a line feed, so the unprefixed part is only used as
4334 # a tiebreaker when two pages have the exact same prefix.
4335 # In UCA, tab is the only character that can sort above LF
4336 # so we strip both of them from the original prefix.
4337 $prefix = strtr( $prefix, "\n\t", ' ' );
4338 return "$prefix\n$unprefixed";
4340 return $unprefixed;
4344 * Get the language in which the content of this page is written.
4345 * Defaults to $wgContLang, but in certain cases it can be e.g.
4346 * $wgLang (such as special pages, which are in the user language).
4348 * @since 1.18
4349 * @return object Language
4351 public function getPageLanguage() {
4352 global $wgLang;
4353 if ( $this->getNamespace() == NS_SPECIAL ) {
4354 // special pages are in the user language
4355 return $wgLang;
4356 } elseif ( $this->isRedirect() ) {
4357 // the arrow on a redirect page is aligned according to the user language
4358 return $wgLang;
4359 } elseif ( $this->isCssOrJsPage() ) {
4360 // css/js should always be LTR and is, in fact, English
4361 return wfGetLangObj( 'en' );
4362 } elseif ( $this->getNamespace() == NS_MEDIAWIKI ) {
4363 // Parse mediawiki messages with correct target language
4364 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $this->getText() );
4365 return wfGetLangObj( $lang );
4367 global $wgContLang;
4368 // If nothing special, it should be in the wiki content language
4369 $pageLang = $wgContLang;
4370 // Hook at the end because we don't want to override the above stuff
4371 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4372 return wfGetLangObj( $pageLang );