3 * Representation a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
31 * @internal documentation reviewed 15 Mar 2010
34 /** @name Static cache variables */
36 static private $titleCache = array();
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
83 # Zero except in {{transclusion}} tags
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mHasSubpage; // /< Whether a page has any subpages
95 /*protected*/ function __construct() { }
98 * Create a new Title from a prefixed DB key
100 * @param $key String the database key, which has underscores
101 * instead of spaces, possibly including namespace and
103 * @return Title, or NULL on an error
105 public static function newFromDBkey( $key ) {
107 $t->mDbkeyform
= $key;
108 if ( $t->secureAndSplit() ) {
116 * Create a new Title from text, such as what one would find in a link. De-
117 * codes any HTML entities in the text.
119 * @param $text String the link text; spaces, prefixes, and an
120 * initial ':' indicating the main namespace are accepted.
121 * @param $defaultNamespace Int the namespace to use if none is speci-
122 * fied by a prefix. If you want to force a specific namespace even if
123 * $text might begin with a namespace prefix, use makeTitle() or
125 * @throws MWException
126 * @return Title|null - Title or null on an error.
128 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
129 if ( is_object( $text ) ) {
130 throw new MWException( 'Title::newFromText given an object' );
134 * Wiki pages often contain multiple links to the same page.
135 * Title normalization and parsing can become expensive on
136 * pages with many links, so we can save a little time by
139 * In theory these are value objects and won't get changed...
141 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
142 return Title
::$titleCache[$text];
145 # Convert things like é ā or 〗 into normalized (bug 14952) text
146 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
149 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
150 $t->mDefaultNamespace
= $defaultNamespace;
152 static $cachedcount = 0;
153 if ( $t->secureAndSplit() ) {
154 if ( $defaultNamespace == NS_MAIN
) {
155 if ( $cachedcount >= self
::CACHE_MAX
) {
156 # Avoid memory leaks on mass operations...
157 Title
::$titleCache = array();
161 Title
::$titleCache[$text] =& $t;
171 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
173 * Example of wrong and broken code:
174 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
176 * Example of right code:
177 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
179 * Create a new Title from URL-encoded text. Ensures that
180 * the given title's length does not exceed the maximum.
182 * @param $url String the title, as might be taken from a URL
183 * @return Title the new object, or NULL on an error
185 public static function newFromURL( $url ) {
188 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
189 # but some URLs used it as a space replacement and they still come
190 # from some external search tools.
191 if ( strpos( self
::legalChars(), '+' ) === false ) {
192 $url = str_replace( '+', ' ', $url );
195 $t->mDbkeyform
= str_replace( ' ', '_', $url );
196 if ( $t->secureAndSplit() ) {
204 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
205 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
209 protected static function getSelectFields() {
210 global $wgContentHandlerUseDB;
213 'page_namespace', 'page_title', 'page_id',
214 'page_len', 'page_is_redirect', 'page_latest',
217 if ( $wgContentHandlerUseDB ) {
218 $fields[] = 'page_content_model';
225 * Create a new Title from an article ID
227 * @param $id Int the page_id corresponding to the Title to create
228 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
229 * @return Title the new object, or NULL on an error
231 public static function newFromID( $id, $flags = 0 ) {
232 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
233 $row = $db->selectRow(
235 self
::getSelectFields(),
236 array( 'page_id' => $id ),
239 if ( $row !== false ) {
240 $title = Title
::newFromRow( $row );
248 * Make an array of titles from an array of IDs
250 * @param $ids Array of Int Array of IDs
251 * @return Array of Titles
253 public static function newFromIDs( $ids ) {
254 if ( !count( $ids ) ) {
257 $dbr = wfGetDB( DB_SLAVE
);
261 self
::getSelectFields(),
262 array( 'page_id' => $ids ),
267 foreach ( $res as $row ) {
268 $titles[] = Title
::newFromRow( $row );
274 * Make a Title object from a DB row
276 * @param $row Object database row (needs at least page_title,page_namespace)
277 * @return Title corresponding Title
279 public static function newFromRow( $row ) {
280 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
281 $t->loadFromRow( $row );
286 * Load Title object fields from a DB row.
287 * If false is given, the title will be treated as non-existing.
289 * @param $row Object|bool database row
291 public function loadFromRow( $row ) {
292 if ( $row ) { // page found
293 if ( isset( $row->page_id
) )
294 $this->mArticleID
= (int)$row->page_id
;
295 if ( isset( $row->page_len
) )
296 $this->mLength
= (int)$row->page_len
;
297 if ( isset( $row->page_is_redirect
) )
298 $this->mRedirect
= (bool)$row->page_is_redirect
;
299 if ( isset( $row->page_latest
) )
300 $this->mLatestID
= (int)$row->page_latest
;
301 if ( isset( $row->page_content_model
) )
302 $this->mContentModel
= strval( $row->page_content_model
);
304 $this->mContentModel
= false; # initialized lazily in getContentModel()
305 } else { // page not found
306 $this->mArticleID
= 0;
308 $this->mRedirect
= false;
309 $this->mLatestID
= 0;
310 $this->mContentModel
= false; # initialized lazily in getContentModel()
315 * Create a new Title from a namespace index and a DB key.
316 * It's assumed that $ns and $title are *valid*, for instance when
317 * they came directly from the database or a special page name.
318 * For convenience, spaces are converted to underscores so that
319 * eg user_text fields can be used directly.
321 * @param $ns Int the namespace of the article
322 * @param $title String the unprefixed database key form
323 * @param $fragment String the link fragment (after the "#")
324 * @param $interwiki String the interwiki prefix
325 * @return Title the new object
327 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
329 $t->mInterwiki
= $interwiki;
330 $t->mFragment
= $fragment;
331 $t->mNamespace
= $ns = intval( $ns );
332 $t->mDbkeyform
= str_replace( ' ', '_', $title );
333 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
334 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
335 $t->mTextform
= str_replace( '_', ' ', $title );
336 $t->mContentModel
= false; # initialized lazily in getContentModel()
341 * Create a new Title from a namespace index and a DB key.
342 * The parameters will be checked for validity, which is a bit slower
343 * than makeTitle() but safer for user-provided data.
345 * @param $ns Int the namespace of the article
346 * @param $title String database key form
347 * @param $fragment String the link fragment (after the "#")
348 * @param $interwiki String interwiki prefix
349 * @return Title the new object, or NULL on an error
351 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
352 if ( !MWNamespace
::exists( $ns ) ) {
357 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
358 if ( $t->secureAndSplit() ) {
366 * Create a new Title for the Main Page
368 * @return Title the new object
370 public static function newMainPage() {
371 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
372 // Don't give fatal errors if the message is broken
374 $title = Title
::newFromText( 'Main Page' );
380 * Extract a redirect destination from a string and return the
381 * Title, or null if the text doesn't contain a valid redirect
382 * This will only return the very next target, useful for
383 * the redirect table and other checks that don't need full recursion
385 * @param $text String: Text with possible redirect
386 * @return Title: The corresponding Title
387 * @deprecated since 1.21, use Content::getRedirectTarget instead.
389 public static function newFromRedirect( $text ) {
390 ContentHandler
::deprecated( __METHOD__
, '1.21' );
392 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
393 return $content->getRedirectTarget();
397 * Extract a redirect destination from a string and return the
398 * Title, or null if the text doesn't contain a valid redirect
399 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
400 * in order to provide (hopefully) the Title of the final destination instead of another redirect
402 * @param $text String Text with possible redirect
404 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
406 public static function newFromRedirectRecurse( $text ) {
407 ContentHandler
::deprecated( __METHOD__
, '1.21' );
409 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
410 return $content->getUltimateRedirectTarget();
414 * Extract a redirect destination from a string and return an
415 * array of Titles, or null if the text doesn't contain a valid redirect
416 * The last element in the array is the final destination after all redirects
417 * have been resolved (up to $wgMaxRedirects times)
419 * @param $text String Text with possible redirect
420 * @return Array of Titles, with the destination last
421 * @deprecated since 1.21, use Content::getRedirectChain instead.
423 public static function newFromRedirectArray( $text ) {
424 ContentHandler
::deprecated( __METHOD__
, '1.21' );
426 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
427 return $content->getRedirectChain();
431 * Get the prefixed DB key associated with an ID
433 * @param $id Int the page_id of the article
434 * @return Title an object representing the article, or NULL if no such article was found
436 public static function nameOf( $id ) {
437 $dbr = wfGetDB( DB_SLAVE
);
439 $s = $dbr->selectRow(
441 array( 'page_namespace', 'page_title' ),
442 array( 'page_id' => $id ),
445 if ( $s === false ) {
449 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
454 * Get a regex character class describing the legal characters in a link
456 * @return String the list of characters, not delimited
458 public static function legalChars() {
459 global $wgLegalTitleChars;
460 return $wgLegalTitleChars;
464 * Returns a simple regex that will match on characters and sequences invalid in titles.
465 * Note that this doesn't pick up many things that could be wrong with titles, but that
466 * replacing this regex with something valid will make many titles valid.
468 * @return String regex string
470 static function getTitleInvalidRegex() {
471 static $rxTc = false;
473 # Matching titles will be held as illegal.
475 # Any character not allowed is forbidden...
476 '[^' . self
::legalChars() . ']' .
477 # URL percent encoding sequences interfere with the ability
478 # to round-trip titles -- you can't link to them consistently.
480 # XML/HTML character references produce similar issues.
481 '|&[A-Za-z0-9\x80-\xff]+;' .
483 '|&#x[0-9A-Fa-f]+;' .
491 * Get a string representation of a title suitable for
492 * including in a search index
494 * @param $ns Int a namespace index
495 * @param $title String text-form main part
496 * @return String a stripped-down title string ready for the search index
498 public static function indexTitle( $ns, $title ) {
501 $lc = SearchEngine
::legalSearchChars() . '&#;';
502 $t = $wgContLang->normalizeForSearch( $title );
503 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
504 $t = $wgContLang->lc( $t );
507 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
508 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
510 $t = preg_replace( "/\\s+/", ' ', $t );
512 if ( $ns == NS_FILE
) {
513 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
519 * Make a prefixed DB key from a DB key and a namespace index
521 * @param $ns Int numerical representation of the namespace
522 * @param $title String the DB key form the title
523 * @param $fragment String The link fragment (after the "#")
524 * @param $interwiki String The interwiki prefix
525 * @return String the prefixed form of the title
527 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
530 $namespace = $wgContLang->getNsText( $ns );
531 $name = $namespace == '' ?
$title : "$namespace:$title";
532 if ( strval( $interwiki ) != '' ) {
533 $name = "$interwiki:$name";
535 if ( strval( $fragment ) != '' ) {
536 $name .= '#' . $fragment;
542 * Escape a text fragment, say from a link, for a URL
544 * @param $fragment string containing a URL or link fragment (after the "#")
545 * @return String: escaped string
547 static function escapeFragmentForURL( $fragment ) {
548 # Note that we don't urlencode the fragment. urlencoded Unicode
549 # fragments appear not to work in IE (at least up to 7) or in at least
550 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
551 # to care if they aren't encoded.
552 return Sanitizer
::escapeId( $fragment, 'noninitial' );
556 * Callback for usort() to do title sorts by (namespace, title)
561 * @return Integer: result of string comparison, or namespace comparison
563 public static function compare( $a, $b ) {
564 if ( $a->getNamespace() == $b->getNamespace() ) {
565 return strcmp( $a->getText(), $b->getText() );
567 return $a->getNamespace() - $b->getNamespace();
572 * Determine whether the object refers to a page within
575 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
577 public function isLocal() {
578 if ( $this->mInterwiki
!= '' ) {
579 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
586 * Is this Title interwiki?
590 public function isExternal() {
591 return ( $this->mInterwiki
!= '' );
595 * Get the interwiki prefix (or null string)
597 * @return String Interwiki prefix
599 public function getInterwiki() {
600 return $this->mInterwiki
;
604 * Determine whether the object refers to a page within
605 * this project and is transcludable.
607 * @return Bool TRUE if this is transcludable
609 public function isTrans() {
610 if ( $this->mInterwiki
== '' ) {
614 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
618 * Returns the DB name of the distant wiki which owns the object.
620 * @return String the DB name
622 public function getTransWikiID() {
623 if ( $this->mInterwiki
== '' ) {
627 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
631 * Get the text form (spaces not underscores) of the main part
633 * @return String Main part of the title
635 public function getText() {
636 return $this->mTextform
;
640 * Get the URL-encoded form of the main part
642 * @return String Main part of the title, URL-encoded
644 public function getPartialURL() {
645 return $this->mUrlform
;
649 * Get the main part with underscores
651 * @return String: Main part of the title, with underscores
653 public function getDBkey() {
654 return $this->mDbkeyform
;
658 * Get the DB key with the initial letter case as specified by the user
660 * @return String DB key
662 function getUserCaseDBKey() {
663 return $this->mUserCaseDBKey
;
667 * Get the namespace index, i.e. one of the NS_xxxx constants.
669 * @return Integer: Namespace index
671 public function getNamespace() {
672 return $this->mNamespace
;
676 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
678 * @throws MWException
679 * @return String: Content model id
681 public function getContentModel() {
682 if ( !$this->mContentModel
) {
683 $linkCache = LinkCache
::singleton();
684 $linkCache->addLinkObj( $this );
685 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
688 if ( !$this->mContentModel
) {
689 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
692 if( !$this->mContentModel
) {
693 throw new MWException( 'Failed to determine content model!' );
696 return $this->mContentModel
;
700 * Convenience method for checking a title's content model name
702 * @param String $id The content model ID (use the CONTENT_MODEL_XXX constants).
703 * @return Boolean true if $this->getContentModel() == $id
705 public function hasContentModel( $id ) {
706 return $this->getContentModel() == $id;
710 * Get the namespace text
712 * @return String: Namespace text
714 public function getNsText() {
717 if ( $this->mInterwiki
!= '' ) {
718 // This probably shouldn't even happen. ohh man, oh yuck.
719 // But for interwiki transclusion it sometimes does.
720 // Shit. Shit shit shit.
722 // Use the canonical namespaces if possible to try to
723 // resolve a foreign namespace.
724 if ( MWNamespace
::exists( $this->mNamespace
) ) {
725 return MWNamespace
::getCanonicalName( $this->mNamespace
);
729 if ( $wgContLang->needsGenderDistinction() &&
730 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
731 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
732 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
735 return $wgContLang->getNsText( $this->mNamespace
);
739 * Get the namespace text of the subject (rather than talk) page
741 * @return String Namespace text
743 public function getSubjectNsText() {
745 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
749 * Get the namespace text of the talk page
751 * @return String Namespace text
753 public function getTalkNsText() {
755 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
759 * Could this title have a corresponding talk page?
761 * @return Bool TRUE or FALSE
763 public function canTalk() {
764 return( MWNamespace
::canTalk( $this->mNamespace
) );
768 * Is this in a namespace that allows actual pages?
771 * @internal note -- uses hardcoded namespace index instead of constants
773 public function canExist() {
774 return $this->mNamespace
>= NS_MAIN
;
778 * Can this title be added to a user's watchlist?
780 * @return Bool TRUE or FALSE
782 public function isWatchable() {
783 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
787 * Returns true if this is a special page.
791 public function isSpecialPage() {
792 return $this->getNamespace() == NS_SPECIAL
;
796 * Returns true if this title resolves to the named special page
798 * @param $name String The special page name
801 public function isSpecial( $name ) {
802 if ( $this->isSpecialPage() ) {
803 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
804 if ( $name == $thisName ) {
812 * If the Title refers to a special page alias which is not the local default, resolve
813 * the alias, and localise the name as necessary. Otherwise, return $this
817 public function fixSpecialName() {
818 if ( $this->isSpecialPage() ) {
819 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
820 if ( $canonicalName ) {
821 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
822 if ( $localName != $this->mDbkeyform
) {
823 return Title
::makeTitle( NS_SPECIAL
, $localName );
831 * Returns true if the title is inside the specified namespace.
833 * Please make use of this instead of comparing to getNamespace()
834 * This function is much more resistant to changes we may make
835 * to namespaces than code that makes direct comparisons.
836 * @param $ns int The namespace
840 public function inNamespace( $ns ) {
841 return MWNamespace
::equals( $this->getNamespace(), $ns );
845 * Returns true if the title is inside one of the specified namespaces.
847 * @param ...$namespaces The namespaces to check for
851 public function inNamespaces( /* ... */ ) {
852 $namespaces = func_get_args();
853 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
854 $namespaces = $namespaces[0];
857 foreach ( $namespaces as $ns ) {
858 if ( $this->inNamespace( $ns ) ) {
867 * Returns true if the title has the same subject namespace as the
868 * namespace specified.
869 * For example this method will take NS_USER and return true if namespace
870 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
871 * as their subject namespace.
873 * This is MUCH simpler than individually testing for equivilance
874 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
879 public function hasSubjectNamespace( $ns ) {
880 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
884 * Is this Title in a namespace which contains content?
885 * In other words, is this a content page, for the purposes of calculating
890 public function isContentPage() {
891 return MWNamespace
::isContent( $this->getNamespace() );
895 * Would anybody with sufficient privileges be able to move this page?
896 * Some pages just aren't movable.
898 * @return Bool TRUE or FALSE
900 public function isMovable() {
901 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
902 // Interwiki title or immovable namespace. Hooks don't get to override here
907 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
912 * Is this the mainpage?
913 * @note Title::newFromText seems to be sufficiently optimized by the title
914 * cache that we don't need to over-optimize by doing direct comparisons and
915 * acidentally creating new bugs where $title->equals( Title::newFromText() )
916 * ends up reporting something differently than $title->isMainPage();
921 public function isMainPage() {
922 return $this->equals( Title
::newMainPage() );
930 public function isSubpage() {
931 return MWNamespace
::hasSubpages( $this->mNamespace
)
932 ?
strpos( $this->getText(), '/' ) !== false
937 * Is this a conversion table for the LanguageConverter?
941 public function isConversionTable() {
942 //@todo: ConversionTable should become a separate content model.
944 return $this->getNamespace() == NS_MEDIAWIKI
&&
945 strpos( $this->getText(), 'Conversiontable/' ) === 0;
949 * Does that page contain wikitext, or it is JS, CSS or whatever?
953 public function isWikitextPage() {
954 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
958 * Could this page contain custom CSS or JavaScript for the global UI.
959 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
960 * or CONTENT_MODEL_JAVASCRIPT.
962 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
964 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
968 public function isCssOrJsPage() {
969 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
970 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
971 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
973 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
974 # hook funktions can force this method to return true even outside the mediawiki namespace.
976 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
978 return $isCssOrJsPage;
982 * Is this a .css or .js subpage of a user page?
985 public function isCssJsSubpage() {
986 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
987 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
988 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
992 * Trim down a .css or .js subpage title to get the corresponding skin name
994 * @return string containing skin name from .css or .js subpage title
996 public function getSkinFromCssJsSubpage() {
997 $subpage = explode( '/', $this->mTextform
);
998 $subpage = $subpage[ count( $subpage ) - 1 ];
999 $lastdot = strrpos( $subpage, '.' );
1000 if ( $lastdot === false )
1001 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1002 return substr( $subpage, 0, $lastdot );
1006 * Is this a .css subpage of a user page?
1010 public function isCssSubpage() {
1011 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1012 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1016 * Is this a .js subpage of a user page?
1020 public function isJsSubpage() {
1021 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1022 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1026 * Is this a talk page of some sort?
1030 public function isTalkPage() {
1031 return MWNamespace
::isTalk( $this->getNamespace() );
1035 * Get a Title object associated with the talk page of this article
1037 * @return Title the object for the talk page
1039 public function getTalkPage() {
1040 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1044 * Get a title object associated with the subject page of this
1047 * @return Title the object for the subject page
1049 public function getSubjectPage() {
1050 // Is this the same title?
1051 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1052 if ( $this->getNamespace() == $subjectNS ) {
1055 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1059 * Get the default namespace index, for when there is no namespace
1061 * @return Int Default namespace index
1063 public function getDefaultNamespace() {
1064 return $this->mDefaultNamespace
;
1068 * Get title for search index
1070 * @return String a stripped-down title string ready for the
1073 public function getIndexTitle() {
1074 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1078 * Get the Title fragment (i.e.\ the bit after the #) in text form
1080 * @return String Title fragment
1082 public function getFragment() {
1083 return $this->mFragment
;
1087 * Get the fragment in URL form, including the "#" character if there is one
1088 * @return String Fragment in URL form
1090 public function getFragmentForURL() {
1091 if ( $this->mFragment
== '' ) {
1094 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1099 * Set the fragment for this title. Removes the first character from the
1100 * specified fragment before setting, so it assumes you're passing it with
1103 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1104 * Still in active use privately.
1106 * @param $fragment String text
1108 public function setFragment( $fragment ) {
1109 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1113 * Prefix some arbitrary text with the namespace or interwiki prefix
1116 * @param $name String the text
1117 * @return String the prefixed text
1120 private function prefix( $name ) {
1122 if ( $this->mInterwiki
!= '' ) {
1123 $p = $this->mInterwiki
. ':';
1126 if ( 0 != $this->mNamespace
) {
1127 $p .= $this->getNsText() . ':';
1133 * Get the prefixed database key form
1135 * @return String the prefixed title, with underscores and
1136 * any interwiki and namespace prefixes
1138 public function getPrefixedDBkey() {
1139 $s = $this->prefix( $this->mDbkeyform
);
1140 $s = str_replace( ' ', '_', $s );
1145 * Get the prefixed title with spaces.
1146 * This is the form usually used for display
1148 * @return String the prefixed title, with spaces
1150 public function getPrefixedText() {
1151 // @todo FIXME: Bad usage of empty() ?
1152 if ( empty( $this->mPrefixedText
) ) {
1153 $s = $this->prefix( $this->mTextform
);
1154 $s = str_replace( '_', ' ', $s );
1155 $this->mPrefixedText
= $s;
1157 return $this->mPrefixedText
;
1161 * Return a string representation of this title
1163 * @return String representation of this title
1165 public function __toString() {
1166 return $this->getPrefixedText();
1170 * Get the prefixed title with spaces, plus any fragment
1171 * (part beginning with '#')
1173 * @return String the prefixed title, with spaces and the fragment, including '#'
1175 public function getFullText() {
1176 $text = $this->getPrefixedText();
1177 if ( $this->mFragment
!= '' ) {
1178 $text .= '#' . $this->mFragment
;
1184 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1188 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1192 * @return String Root name
1195 public function getRootText() {
1196 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1197 return $this->getText();
1200 return strtok( $this->getText(), '/' );
1204 * Get the root page name title, i.e. the leftmost part before any slashes
1208 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1209 * # returns: Title{User:Foo}
1212 * @return Title Root title
1215 public function getRootTitle() {
1216 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1220 * Get the base page name without a namespace, i.e. the part before the subpage name
1224 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1225 * # returns: 'Foo/Bar'
1228 * @return String Base name
1230 public function getBaseText() {
1231 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1232 return $this->getText();
1235 $parts = explode( '/', $this->getText() );
1236 # Don't discard the real title if there's no subpage involved
1237 if ( count( $parts ) > 1 ) {
1238 unset( $parts[count( $parts ) - 1] );
1240 return implode( '/', $parts );
1244 * Get the base page name title, i.e. the part before the subpage name
1248 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1249 * # returns: Title{User:Foo/Bar}
1252 * @return Title Base title
1255 public function getBaseTitle() {
1256 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1260 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1264 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1268 * @return String Subpage name
1270 public function getSubpageText() {
1271 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1272 return( $this->mTextform
);
1274 $parts = explode( '/', $this->mTextform
);
1275 return( $parts[count( $parts ) - 1] );
1279 * Get the title for a subpage of the current page
1283 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1284 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1287 * @param $text String The subpage name to add to the title
1288 * @return Title Subpage title
1291 public function getSubpage( $text ) {
1292 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1296 * Get the HTML-escaped displayable text form.
1297 * Used for the title field in <a> tags.
1299 * @return String the text, including any prefixes
1301 public function getEscapedText() {
1302 wfDeprecated( __METHOD__
, '1.19' );
1303 return htmlspecialchars( $this->getPrefixedText() );
1307 * Get a URL-encoded form of the subpage text
1309 * @return String URL-encoded subpage name
1311 public function getSubpageUrlForm() {
1312 $text = $this->getSubpageText();
1313 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1318 * Get a URL-encoded title (not an actual URL) including interwiki
1320 * @return String the URL-encoded form
1322 public function getPrefixedURL() {
1323 $s = $this->prefix( $this->mDbkeyform
);
1324 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1329 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1330 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1331 * second argument named variant. This was deprecated in favor
1332 * of passing an array of option with a "variant" key
1333 * Once $query2 is removed for good, this helper can be dropped
1334 * andthe wfArrayToCgi moved to getLocalURL();
1336 * @since 1.19 (r105919)
1338 * @param $query2 bool
1341 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1342 if( $query2 !== false ) {
1343 wfDeprecated( "Title::get{Canonical,Full,Link,Local} method called with a second parameter is deprecated. Add your parameter to an array passed as the first parameter.", "1.19" );
1345 if ( is_array( $query ) ) {
1346 $query = wfArrayToCgi( $query );
1349 if ( is_string( $query2 ) ) {
1350 // $query2 is a string, we will consider this to be
1351 // a deprecated $variant argument and add it to the query
1352 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1354 $query2 = wfArrayToCgi( $query2 );
1356 // If we have $query content add a & to it first
1360 // Now append the queries together
1367 * Get a real URL referring to this title, with interwiki link and
1370 * See getLocalURL for the arguments.
1372 * @see self::getLocalURL
1375 * @param $query2 bool
1376 * @param $proto Protocol type to use in URL
1377 * @return String the URL
1379 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1380 $query = self
::fixUrlQueryArgs( $query, $query2 );
1382 # Hand off all the decisions on urls to getLocalURL
1383 $url = $this->getLocalURL( $query );
1385 # Expand the url to make it a full url. Note that getLocalURL has the
1386 # potential to output full urls for a variety of reasons, so we use
1387 # wfExpandUrl instead of simply prepending $wgServer
1388 $url = wfExpandUrl( $url, $proto );
1390 # Finally, add the fragment.
1391 $url .= $this->getFragmentForURL();
1393 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1398 * Get a URL with no fragment or server name. If this page is generated
1399 * with action=render, $wgServer is prepended.
1402 * @param $query string|array an optional query string,
1403 * not used for interwiki links. Can be specified as an associative array as well,
1404 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1405 * Some query patterns will trigger various shorturl path replacements.
1406 * @param $query2 Mixed: An optional secondary query array. This one MUST
1407 * be an array. If a string is passed it will be interpreted as a deprecated
1408 * variant argument and urlencoded into a variant= argument.
1409 * This second query argument will be added to the $query
1410 * The second parameter is deprecated since 1.19. Pass it as a key,value
1411 * pair in the first parameter array instead.
1413 * @return String the URL
1415 public function getLocalURL( $query = '', $query2 = false ) {
1416 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1418 $query = self
::fixUrlQueryArgs( $query, $query2 );
1420 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1422 $namespace = $this->getNsText();
1423 if ( $namespace != '' ) {
1424 # Can this actually happen? Interwikis shouldn't be parsed.
1425 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1428 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1429 $url = wfAppendQuery( $url, $query );
1431 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1432 if ( $query == '' ) {
1433 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1434 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1436 global $wgVariantArticlePath, $wgActionPaths;
1440 if ( !empty( $wgActionPaths ) &&
1441 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1443 $action = urldecode( $matches[2] );
1444 if ( isset( $wgActionPaths[$action] ) ) {
1445 $query = $matches[1];
1446 if ( isset( $matches[4] ) ) {
1447 $query .= $matches[4];
1449 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1450 if ( $query != '' ) {
1451 $url = wfAppendQuery( $url, $query );
1456 if ( $url === false &&
1457 $wgVariantArticlePath &&
1458 $this->getPageLanguage()->hasVariants() &&
1459 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1461 $variant = urldecode( $matches[1] );
1462 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1463 // Only do the variant replacement if the given variant is a valid
1464 // variant for the page's language.
1465 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1466 $url = str_replace( '$1', $dbkey, $url );
1470 if ( $url === false ) {
1471 if ( $query == '-' ) {
1474 $url = "{$wgScript}?title={$dbkey}&{$query}";
1478 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1480 // @todo FIXME: This causes breakage in various places when we
1481 // actually expected a local URL and end up with dupe prefixes.
1482 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1483 $url = $wgServer . $url;
1486 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1491 * Get a URL that's the simplest URL that will be valid to link, locally,
1492 * to the current Title. It includes the fragment, but does not include
1493 * the server unless action=render is used (or the link is external). If
1494 * there's a fragment but the prefixed text is empty, we just return a link
1497 * The result obviously should not be URL-escaped, but does need to be
1498 * HTML-escaped if it's being output in HTML.
1500 * See getLocalURL for the arguments.
1503 * @param $query2 bool
1504 * @param $proto Protocol to use; setting this will cause a full URL to be used
1505 * @see self::getLocalURL
1506 * @return String the URL
1508 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1509 wfProfileIn( __METHOD__
);
1510 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1511 $ret = $this->getFullURL( $query, $query2, $proto );
1512 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1513 $ret = $this->getFragmentForURL();
1515 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1517 wfProfileOut( __METHOD__
);
1522 * Get an HTML-escaped version of the URL form, suitable for
1523 * using in a link, without a server name or fragment
1525 * See getLocalURL for the arguments.
1527 * @see self::getLocalURL
1528 * @param $query string
1529 * @param $query2 bool|string
1530 * @return String the URL
1532 public function escapeLocalURL( $query = '', $query2 = false ) {
1533 wfDeprecated( __METHOD__
, '1.19' );
1534 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1538 * Get an HTML-escaped version of the URL form, suitable for
1539 * using in a link, including the server name and fragment
1541 * See getLocalURL for the arguments.
1543 * @see self::getLocalURL
1544 * @return String the URL
1546 public function escapeFullURL( $query = '', $query2 = false ) {
1547 wfDeprecated( __METHOD__
, '1.19' );
1548 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1552 * Get the URL form for an internal link.
1553 * - Used in various Squid-related code, in case we have a different
1554 * internal hostname for the server from the exposed one.
1556 * This uses $wgInternalServer to qualify the path, or $wgServer
1557 * if $wgInternalServer is not set. If the server variable used is
1558 * protocol-relative, the URL will be expanded to http://
1560 * See getLocalURL for the arguments.
1562 * @see self::getLocalURL
1563 * @return String the URL
1565 public function getInternalURL( $query = '', $query2 = false ) {
1566 global $wgInternalServer, $wgServer;
1567 $query = self
::fixUrlQueryArgs( $query, $query2 );
1568 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1569 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1570 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1575 * Get the URL for a canonical link, for use in things like IRC and
1576 * e-mail notifications. Uses $wgCanonicalServer and the
1577 * GetCanonicalURL hook.
1579 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1581 * See getLocalURL for the arguments.
1583 * @see self::getLocalURL
1584 * @return string The URL
1587 public function getCanonicalURL( $query = '', $query2 = false ) {
1588 $query = self
::fixUrlQueryArgs( $query, $query2 );
1589 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1590 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1595 * HTML-escaped version of getCanonicalURL()
1597 * See getLocalURL for the arguments.
1599 * @see self::getLocalURL
1603 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1604 wfDeprecated( __METHOD__
, '1.19' );
1605 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1609 * Get the edit URL for this Title
1611 * @return String the URL, or a null string if this is an
1614 public function getEditURL() {
1615 if ( $this->mInterwiki
!= '' ) {
1618 $s = $this->getLocalURL( 'action=edit' );
1624 * Is $wgUser watching this page?
1626 * @deprecated in 1.20; use User::isWatched() instead.
1629 public function userIsWatching() {
1632 if ( is_null( $this->mWatched
) ) {
1633 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1634 $this->mWatched
= false;
1636 $this->mWatched
= $wgUser->isWatched( $this );
1639 return $this->mWatched
;
1643 * Can $wgUser read this page?
1645 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1647 * @todo fold these checks into userCan()
1649 public function userCanRead() {
1650 wfDeprecated( __METHOD__
, '1.19' );
1651 return $this->userCan( 'read' );
1655 * Can $user perform $action on this page?
1656 * This skips potentially expensive cascading permission checks
1657 * as well as avoids expensive error formatting
1659 * Suitable for use for nonessential UI controls in common cases, but
1660 * _not_ for functional access control.
1662 * May provide false positives, but should never provide a false negative.
1664 * @param $action String action that permission needs to be checked for
1665 * @param $user User to check (since 1.19); $wgUser will be used if not
1669 public function quickUserCan( $action, $user = null ) {
1670 return $this->userCan( $action, $user, false );
1674 * Can $user perform $action on this page?
1676 * @param $action String action that permission needs to be checked for
1677 * @param $user User to check (since 1.19); $wgUser will be used if not
1679 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1680 * unnecessary queries.
1683 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1684 if ( !$user instanceof User
) {
1688 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1692 * Can $user perform $action on this page?
1694 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1696 * @param $action String action that permission needs to be checked for
1697 * @param $user User to check
1698 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1699 * queries by skipping checks for cascading protections and user blocks.
1700 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1701 * whose corresponding errors may be ignored.
1702 * @return Array of arguments to wfMessage to explain permissions problems.
1704 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1705 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1707 // Remove the errors being ignored.
1708 foreach ( $errors as $index => $error ) {
1709 $error_key = is_array( $error ) ?
$error[0] : $error;
1711 if ( in_array( $error_key, $ignoreErrors ) ) {
1712 unset( $errors[$index] );
1720 * Permissions checks that fail most often, and which are easiest to test.
1722 * @param $action String the action to check
1723 * @param $user User user to check
1724 * @param $errors Array list of current errors
1725 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1726 * @param $short Boolean short circuit on first error
1728 * @return Array list of errors
1730 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1731 if ( $action == 'create' ) {
1732 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1733 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1734 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1736 } elseif ( $action == 'move' ) {
1737 if ( !$user->isAllowed( 'move-rootuserpages' )
1738 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1739 // Show user page-specific message only if the user can move other pages
1740 $errors[] = array( 'cant-move-user-page' );
1743 // Check if user is allowed to move files if it's a file
1744 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1745 $errors[] = array( 'movenotallowedfile' );
1748 if ( !$user->isAllowed( 'move' ) ) {
1749 // User can't move anything
1750 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1751 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1752 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1753 // custom message if logged-in users without any special rights can move
1754 $errors[] = array( 'movenologintext' );
1756 $errors[] = array( 'movenotallowed' );
1759 } elseif ( $action == 'move-target' ) {
1760 if ( !$user->isAllowed( 'move' ) ) {
1761 // User can't move anything
1762 $errors[] = array( 'movenotallowed' );
1763 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1764 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1765 // Show user page-specific message only if the user can move other pages
1766 $errors[] = array( 'cant-move-to-user-page' );
1768 } elseif ( !$user->isAllowed( $action ) ) {
1769 $errors[] = $this->missingPermissionError( $action, $short );
1776 * Add the resulting error code to the errors array
1778 * @param $errors Array list of current errors
1779 * @param $result Mixed result of errors
1781 * @return Array list of errors
1783 private function resultToError( $errors, $result ) {
1784 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1785 // A single array representing an error
1786 $errors[] = $result;
1787 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1788 // A nested array representing multiple errors
1789 $errors = array_merge( $errors, $result );
1790 } elseif ( $result !== '' && is_string( $result ) ) {
1791 // A string representing a message-id
1792 $errors[] = array( $result );
1793 } elseif ( $result === false ) {
1794 // a generic "We don't want them to do that"
1795 $errors[] = array( 'badaccess-group0' );
1801 * Check various permission hooks
1803 * @param $action String the action to check
1804 * @param $user User user to check
1805 * @param $errors Array list of current errors
1806 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1807 * @param $short Boolean short circuit on first error
1809 * @return Array list of errors
1811 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1812 // Use getUserPermissionsErrors instead
1814 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1815 return $result ?
array() : array( array( 'badaccess-group0' ) );
1817 // Check getUserPermissionsErrors hook
1818 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1819 $errors = $this->resultToError( $errors, $result );
1821 // Check getUserPermissionsErrorsExpensive hook
1822 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1823 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1824 $errors = $this->resultToError( $errors, $result );
1831 * Check permissions on special pages & namespaces
1833 * @param $action String the action to check
1834 * @param $user User user to check
1835 * @param $errors Array list of current errors
1836 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1837 * @param $short Boolean short circuit on first error
1839 * @return Array list of errors
1841 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1842 # Only 'createaccount' can be performed on special pages,
1843 # which don't actually exist in the DB.
1844 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
1845 $errors[] = array( 'ns-specialprotected' );
1848 # Check $wgNamespaceProtection for restricted namespaces
1849 if ( $this->isNamespaceProtected( $user ) ) {
1850 $ns = $this->mNamespace
== NS_MAIN ?
1851 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1852 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1853 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1860 * Check CSS/JS sub-page permissions
1862 * @param $action String the action to check
1863 * @param $user User user to check
1864 * @param $errors Array list of current errors
1865 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1866 * @param $short Boolean short circuit on first error
1868 * @return Array list of errors
1870 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1871 # Protect css/js subpages of user pages
1872 # XXX: this might be better using restrictions
1873 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1874 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1875 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1876 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1877 $errors[] = array( 'customcssprotected' );
1878 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1879 $errors[] = array( 'customjsprotected' );
1887 * Check against page_restrictions table requirements on this
1888 * page. The user must possess all required rights for this
1891 * @param $action String the action to check
1892 * @param $user User user to check
1893 * @param $errors Array list of current errors
1894 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1895 * @param $short Boolean short circuit on first error
1897 * @return Array list of errors
1899 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1900 foreach ( $this->getRestrictions( $action ) as $right ) {
1901 // Backwards compatibility, rewrite sysop -> protect
1902 if ( $right == 'sysop' ) {
1905 if ( $right != '' && !$user->isAllowed( $right ) ) {
1906 // Users with 'editprotected' permission can edit protected pages
1907 // without cascading option turned on.
1908 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1909 ||
$this->mCascadeRestriction
)
1911 $errors[] = array( 'protectedpagetext', $right );
1920 * Check restrictions on cascading pages.
1922 * @param $action String the action to check
1923 * @param $user User to check
1924 * @param $errors Array list of current errors
1925 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1926 * @param $short Boolean short circuit on first error
1928 * @return Array list of errors
1930 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1931 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1932 # We /could/ use the protection level on the source page, but it's
1933 # fairly ugly as we have to establish a precedence hierarchy for pages
1934 # included by multiple cascade-protected pages. So just restrict
1935 # it to people with 'protect' permission, as they could remove the
1936 # protection anyway.
1937 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1938 # Cascading protection depends on more than this page...
1939 # Several cascading protected pages may include this page...
1940 # Check each cascading level
1941 # This is only for protection restrictions, not for all actions
1942 if ( isset( $restrictions[$action] ) ) {
1943 foreach ( $restrictions[$action] as $right ) {
1944 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1945 if ( $right != '' && !$user->isAllowed( $right ) ) {
1947 foreach ( $cascadingSources as $page )
1948 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1949 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1959 * Check action permissions not already checked in checkQuickPermissions
1961 * @param $action String the action to check
1962 * @param $user User to check
1963 * @param $errors Array list of current errors
1964 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1965 * @param $short Boolean short circuit on first error
1967 * @return Array list of errors
1969 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1970 global $wgDeleteRevisionsLimit, $wgLang;
1972 if ( $action == 'protect' ) {
1973 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1974 // If they can't edit, they shouldn't protect.
1975 $errors[] = array( 'protect-cantedit' );
1977 } elseif ( $action == 'create' ) {
1978 $title_protection = $this->getTitleProtection();
1979 if( $title_protection ) {
1980 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1981 $title_protection['pt_create_perm'] = 'protect'; // B/C
1983 if( $title_protection['pt_create_perm'] == '' ||
1984 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1986 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1989 } elseif ( $action == 'move' ) {
1990 // Check for immobile pages
1991 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1992 // Specific message for this case
1993 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1994 } elseif ( !$this->isMovable() ) {
1995 // Less specific message for rarer cases
1996 $errors[] = array( 'immobile-source-page' );
1998 } elseif ( $action == 'move-target' ) {
1999 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2000 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2001 } elseif ( !$this->isMovable() ) {
2002 $errors[] = array( 'immobile-target-page' );
2004 } elseif ( $action == 'delete' ) {
2005 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2006 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
2008 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2015 * Check that the user isn't blocked from editting.
2017 * @param $action String the action to check
2018 * @param $user User to check
2019 * @param $errors Array list of current errors
2020 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2021 * @param $short Boolean short circuit on first error
2023 * @return Array list of errors
2025 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2026 // Account creation blocks handled at userlogin.
2027 // Unblocking handled in SpecialUnblock
2028 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2032 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
2034 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2035 $errors[] = array( 'confirmedittext' );
2038 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2039 // Don't block the user from editing their own talk page unless they've been
2040 // explicitly blocked from that too.
2041 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2042 $block = $user->getBlock();
2044 // This is from OutputPage::blockedPage
2045 // Copied at r23888 by werdna
2047 $id = $user->blockedBy();
2048 $reason = $user->blockedFor();
2049 if ( $reason == '' ) {
2050 $reason = wfMessage( 'blockednoreason' )->text();
2052 $ip = $user->getRequest()->getIP();
2054 if ( is_numeric( $id ) ) {
2055 $name = User
::whoIs( $id );
2060 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
2061 $blockid = $block->getId();
2062 $blockExpiry = $block->getExpiry();
2063 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
2064 if ( $blockExpiry == 'infinity' ) {
2065 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2067 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2070 $intended = strval( $block->getTarget() );
2072 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2073 $blockid, $blockExpiry, $intended, $blockTimestamp );
2080 * Check that the user is allowed to read this page.
2082 * @param $action String the action to check
2083 * @param $user User to check
2084 * @param $errors Array list of current errors
2085 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2086 * @param $short Boolean short circuit on first error
2088 * @return Array list of errors
2090 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2091 global $wgWhitelistRead, $wgWhitelistReadRegexp, $wgRevokePermissions;
2092 static $useShortcut = null;
2094 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2095 if ( is_null( $useShortcut ) ) {
2096 $useShortcut = true;
2097 if ( !User
::groupHasPermission( '*', 'read' ) ) {
2098 # Not a public wiki, so no shortcut
2099 $useShortcut = false;
2100 } elseif ( !empty( $wgRevokePermissions ) ) {
2102 * Iterate through each group with permissions being revoked (key not included since we don't care
2103 * what the group name is), then check if the read permission is being revoked. If it is, then
2104 * we don't use the shortcut below since the user might not be able to read, even though anon
2105 * reading is allowed.
2107 foreach ( $wgRevokePermissions as $perms ) {
2108 if ( !empty( $perms['read'] ) ) {
2109 # We might be removing the read right from the user, so no shortcut
2110 $useShortcut = false;
2117 $whitelisted = false;
2118 if ( $useShortcut ) {
2119 # Shortcut for public wikis, allows skipping quite a bit of code
2120 $whitelisted = true;
2121 } elseif ( $user->isAllowed( 'read' ) ) {
2122 # If the user is allowed to read pages, he is allowed to read all pages
2123 $whitelisted = true;
2124 } elseif ( $this->isSpecial( 'Userlogin' )
2125 ||
$this->isSpecial( 'ChangePassword' )
2126 ||
$this->isSpecial( 'PasswordReset' )
2128 # Always grant access to the login page.
2129 # Even anons need to be able to log in.
2130 $whitelisted = true;
2131 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2132 # Time to check the whitelist
2133 # Only do these checks is there's something to check against
2134 $name = $this->getPrefixedText();
2135 $dbName = $this->getPrefixedDBKey();
2137 // Check for explicit whitelisting with and without underscores
2138 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2139 $whitelisted = true;
2140 } elseif ( $this->getNamespace() == NS_MAIN
) {
2141 # Old settings might have the title prefixed with
2142 # a colon for main-namespace pages
2143 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2144 $whitelisted = true;
2146 } elseif ( $this->isSpecialPage() ) {
2147 # If it's a special page, ditch the subpage bit and check again
2148 $name = $this->getDBkey();
2149 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2151 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2152 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2153 $whitelisted = true;
2159 if( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2160 $name = $this->getPrefixedText();
2161 // Check for regex whitelisting
2162 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2163 if ( preg_match( $listItem, $name ) ) {
2164 $whitelisted = true;
2170 if ( !$whitelisted ) {
2171 # If the title is not whitelisted, give extensions a chance to do so...
2172 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2173 if ( !$whitelisted ) {
2174 $errors[] = $this->missingPermissionError( $action, $short );
2182 * Get a description array when the user doesn't have the right to perform
2183 * $action (i.e. when User::isAllowed() returns false)
2185 * @param $action String the action to check
2186 * @param $short Boolean short circuit on first error
2187 * @return Array list of errors
2189 private function missingPermissionError( $action, $short ) {
2190 // We avoid expensive display logic for quickUserCan's and such
2192 return array( 'badaccess-group0' );
2195 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2196 User
::getGroupsWithPermission( $action ) );
2198 if ( count( $groups ) ) {
2202 $wgLang->commaList( $groups ),
2206 return array( 'badaccess-group0' );
2211 * Can $user perform $action on this page? This is an internal function,
2212 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2213 * checks on wfReadOnly() and blocks)
2215 * @param $action String action that permission needs to be checked for
2216 * @param $user User to check
2217 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2218 * @param $short Bool Set this to true to stop after the first permission error.
2219 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2221 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2222 wfProfileIn( __METHOD__
);
2224 # Read has special handling
2225 if ( $action == 'read' ) {
2227 'checkPermissionHooks',
2228 'checkReadPermissions',
2232 'checkQuickPermissions',
2233 'checkPermissionHooks',
2234 'checkSpecialsAndNSPermissions',
2235 'checkCSSandJSPermissions',
2236 'checkPageRestrictions',
2237 'checkCascadingSourcesRestrictions',
2238 'checkActionPermissions',
2244 while( count( $checks ) > 0 &&
2245 !( $short && count( $errors ) > 0 ) ) {
2246 $method = array_shift( $checks );
2247 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2250 wfProfileOut( __METHOD__
);
2255 * Protect css subpages of user pages: can $wgUser edit
2258 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2261 public function userCanEditCssSubpage() {
2263 wfDeprecated( __METHOD__
, '1.19' );
2264 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2265 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2269 * Protect js subpages of user pages: can $wgUser edit
2272 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2275 public function userCanEditJsSubpage() {
2277 wfDeprecated( __METHOD__
, '1.19' );
2278 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2279 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2283 * Get a filtered list of all restriction types supported by this wiki.
2284 * @param bool $exists True to get all restriction types that apply to
2285 * titles that do exist, False for all restriction types that apply to
2286 * titles that do not exist
2289 public static function getFilteredRestrictionTypes( $exists = true ) {
2290 global $wgRestrictionTypes;
2291 $types = $wgRestrictionTypes;
2293 # Remove the create restriction for existing titles
2294 $types = array_diff( $types, array( 'create' ) );
2296 # Only the create and upload restrictions apply to non-existing titles
2297 $types = array_intersect( $types, array( 'create', 'upload' ) );
2303 * Returns restriction types for the current Title
2305 * @return array applicable restriction types
2307 public function getRestrictionTypes() {
2308 if ( $this->isSpecialPage() ) {
2312 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2314 if ( $this->getNamespace() != NS_FILE
) {
2315 # Remove the upload restriction for non-file titles
2316 $types = array_diff( $types, array( 'upload' ) );
2319 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2321 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2322 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2328 * Is this title subject to title protection?
2329 * Title protection is the one applied against creation of such title.
2331 * @return Mixed An associative array representing any existent title
2332 * protection, or false if there's none.
2334 private function getTitleProtection() {
2335 // Can't protect pages in special namespaces
2336 if ( $this->getNamespace() < 0 ) {
2340 // Can't protect pages that exist.
2341 if ( $this->exists() ) {
2345 if ( !isset( $this->mTitleProtection
) ) {
2346 $dbr = wfGetDB( DB_SLAVE
);
2347 $res = $dbr->select(
2349 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2350 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2354 // fetchRow returns false if there are no rows.
2355 $this->mTitleProtection
= $dbr->fetchRow( $res );
2357 return $this->mTitleProtection
;
2361 * Update the title protection status
2363 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2364 * @param $create_perm String Permission required for creation
2365 * @param $reason String Reason for protection
2366 * @param $expiry String Expiry timestamp
2367 * @return boolean true
2369 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2370 wfDeprecated( __METHOD__
, '1.19' );
2374 $limit = array( 'create' => $create_perm );
2375 $expiry = array( 'create' => $expiry );
2377 $page = WikiPage
::factory( $this );
2379 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2381 return $status->isOK();
2385 * Remove any title protection due to page existing
2387 public function deleteTitleProtection() {
2388 $dbw = wfGetDB( DB_MASTER
);
2392 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2395 $this->mTitleProtection
= false;
2399 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2401 * @param $action String Action to check (default: edit)
2404 public function isSemiProtected( $action = 'edit' ) {
2405 if ( $this->exists() ) {
2406 $restrictions = $this->getRestrictions( $action );
2407 if ( count( $restrictions ) > 0 ) {
2408 foreach ( $restrictions as $restriction ) {
2409 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2419 # If it doesn't exist, it can't be protected
2425 * Does the title correspond to a protected article?
2427 * @param $action String the action the page is protected from,
2428 * by default checks all actions.
2431 public function isProtected( $action = '' ) {
2432 global $wgRestrictionLevels;
2434 $restrictionTypes = $this->getRestrictionTypes();
2436 # Special pages have inherent protection
2437 if( $this->isSpecialPage() ) {
2441 # Check regular protection levels
2442 foreach ( $restrictionTypes as $type ) {
2443 if ( $action == $type ||
$action == '' ) {
2444 $r = $this->getRestrictions( $type );
2445 foreach ( $wgRestrictionLevels as $level ) {
2446 if ( in_array( $level, $r ) && $level != '' ) {
2457 * Determines if $user is unable to edit this page because it has been protected
2458 * by $wgNamespaceProtection.
2460 * @param $user User object to check permissions
2463 public function isNamespaceProtected( User
$user ) {
2464 global $wgNamespaceProtection;
2466 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2467 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2468 if ( $right != '' && !$user->isAllowed( $right ) ) {
2477 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2479 * @return Bool If the page is subject to cascading restrictions.
2481 public function isCascadeProtected() {
2482 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2483 return ( $sources > 0 );
2487 * Cascading protection: Get the source of any cascading restrictions on this page.
2489 * @param $getPages Bool Whether or not to retrieve the actual pages
2490 * that the restrictions have come from.
2491 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2492 * have come, false for none, or true if such restrictions exist, but $getPages
2493 * was not set. The restriction array is an array of each type, each of which
2494 * contains a array of unique groups.
2496 public function getCascadeProtectionSources( $getPages = true ) {
2498 $pagerestrictions = array();
2500 if ( isset( $this->mCascadeSources
) && $getPages ) {
2501 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2502 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2503 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2506 wfProfileIn( __METHOD__
);
2508 $dbr = wfGetDB( DB_SLAVE
);
2510 if ( $this->getNamespace() == NS_FILE
) {
2511 $tables = array( 'imagelinks', 'page_restrictions' );
2512 $where_clauses = array(
2513 'il_to' => $this->getDBkey(),
2518 $tables = array( 'templatelinks', 'page_restrictions' );
2519 $where_clauses = array(
2520 'tl_namespace' => $this->getNamespace(),
2521 'tl_title' => $this->getDBkey(),
2528 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2529 'pr_expiry', 'pr_type', 'pr_level' );
2530 $where_clauses[] = 'page_id=pr_page';
2533 $cols = array( 'pr_expiry' );
2536 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2538 $sources = $getPages ?
array() : false;
2539 $now = wfTimestampNow();
2540 $purgeExpired = false;
2542 foreach ( $res as $row ) {
2543 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2544 if ( $expiry > $now ) {
2546 $page_id = $row->pr_page
;
2547 $page_ns = $row->page_namespace
;
2548 $page_title = $row->page_title
;
2549 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2550 # Add groups needed for each restriction type if its not already there
2551 # Make sure this restriction type still exists
2553 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2554 $pagerestrictions[$row->pr_type
] = array();
2557 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2558 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2559 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2565 // Trigger lazy purge of expired restrictions from the db
2566 $purgeExpired = true;
2569 if ( $purgeExpired ) {
2570 Title
::purgeExpiredRestrictions();
2574 $this->mCascadeSources
= $sources;
2575 $this->mCascadingRestrictions
= $pagerestrictions;
2577 $this->mHasCascadingRestrictions
= $sources;
2580 wfProfileOut( __METHOD__
);
2581 return array( $sources, $pagerestrictions );
2585 * Accessor/initialisation for mRestrictions
2587 * @param $action String action that permission needs to be checked for
2588 * @return Array of Strings the array of groups allowed to edit this article
2590 public function getRestrictions( $action ) {
2591 if ( !$this->mRestrictionsLoaded
) {
2592 $this->loadRestrictions();
2594 return isset( $this->mRestrictions
[$action] )
2595 ?
$this->mRestrictions
[$action]
2600 * Get the expiry time for the restriction against a given action
2603 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2604 * or not protected at all, or false if the action is not recognised.
2606 public function getRestrictionExpiry( $action ) {
2607 if ( !$this->mRestrictionsLoaded
) {
2608 $this->loadRestrictions();
2610 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2614 * Returns cascading restrictions for the current article
2618 function areRestrictionsCascading() {
2619 if ( !$this->mRestrictionsLoaded
) {
2620 $this->loadRestrictions();
2623 return $this->mCascadeRestriction
;
2627 * Loads a string into mRestrictions array
2629 * @param $res Resource restrictions as an SQL result.
2630 * @param $oldFashionedRestrictions String comma-separated list of page
2631 * restrictions from page table (pre 1.10)
2633 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2636 foreach ( $res as $row ) {
2640 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2644 * Compiles list of active page restrictions from both page table (pre 1.10)
2645 * and page_restrictions table for this existing page.
2646 * Public for usage by LiquidThreads.
2648 * @param $rows array of db result objects
2649 * @param $oldFashionedRestrictions string comma-separated list of page
2650 * restrictions from page table (pre 1.10)
2652 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2654 $dbr = wfGetDB( DB_SLAVE
);
2656 $restrictionTypes = $this->getRestrictionTypes();
2658 foreach ( $restrictionTypes as $type ) {
2659 $this->mRestrictions
[$type] = array();
2660 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2663 $this->mCascadeRestriction
= false;
2665 # Backwards-compatibility: also load the restrictions from the page record (old format).
2667 if ( $oldFashionedRestrictions === null ) {
2668 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2669 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2672 if ( $oldFashionedRestrictions != '' ) {
2674 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2675 $temp = explode( '=', trim( $restrict ) );
2676 if ( count( $temp ) == 1 ) {
2677 // old old format should be treated as edit/move restriction
2678 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2679 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2681 $restriction = trim( $temp[1] );
2682 if( $restriction != '' ) { //some old entries are empty
2683 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2688 $this->mOldRestrictions
= true;
2692 if ( count( $rows ) ) {
2693 # Current system - load second to make them override.
2694 $now = wfTimestampNow();
2695 $purgeExpired = false;
2697 # Cycle through all the restrictions.
2698 foreach ( $rows as $row ) {
2700 // Don't take care of restrictions types that aren't allowed
2701 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2704 // This code should be refactored, now that it's being used more generally,
2705 // But I don't really see any harm in leaving it in Block for now -werdna
2706 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2708 // Only apply the restrictions if they haven't expired!
2709 if ( !$expiry ||
$expiry > $now ) {
2710 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2711 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2713 $this->mCascadeRestriction |
= $row->pr_cascade
;
2715 // Trigger a lazy purge of expired restrictions
2716 $purgeExpired = true;
2720 if ( $purgeExpired ) {
2721 Title
::purgeExpiredRestrictions();
2725 $this->mRestrictionsLoaded
= true;
2729 * Load restrictions from the page_restrictions table
2731 * @param $oldFashionedRestrictions String comma-separated list of page
2732 * restrictions from page table (pre 1.10)
2734 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2736 if ( !$this->mRestrictionsLoaded
) {
2737 if ( $this->exists() ) {
2738 $dbr = wfGetDB( DB_SLAVE
);
2740 $res = $dbr->select(
2741 'page_restrictions',
2742 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2743 array( 'pr_page' => $this->getArticleID() ),
2747 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2749 $title_protection = $this->getTitleProtection();
2751 if ( $title_protection ) {
2752 $now = wfTimestampNow();
2753 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2755 if ( !$expiry ||
$expiry > $now ) {
2756 // Apply the restrictions
2757 $this->mRestrictionsExpiry
['create'] = $expiry;
2758 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2759 } else { // Get rid of the old restrictions
2760 Title
::purgeExpiredRestrictions();
2761 $this->mTitleProtection
= false;
2764 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2766 $this->mRestrictionsLoaded
= true;
2772 * Flush the protection cache in this object and force reload from the database.
2773 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2775 public function flushRestrictions() {
2776 $this->mRestrictionsLoaded
= false;
2777 $this->mTitleProtection
= null;
2781 * Purge expired restrictions from the page_restrictions table
2783 static function purgeExpiredRestrictions() {
2784 if ( wfReadOnly() ) {
2788 $dbw = wfGetDB( DB_MASTER
);
2790 'page_restrictions',
2791 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2797 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2803 * Does this have subpages? (Warning, usually requires an extra DB query.)
2807 public function hasSubpages() {
2808 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2813 # We dynamically add a member variable for the purpose of this method
2814 # alone to cache the result. There's no point in having it hanging
2815 # around uninitialized in every Title object; therefore we only add it
2816 # if needed and don't declare it statically.
2817 if ( isset( $this->mHasSubpages
) ) {
2818 return $this->mHasSubpages
;
2821 $subpages = $this->getSubpages( 1 );
2822 if ( $subpages instanceof TitleArray
) {
2823 return $this->mHasSubpages
= (bool)$subpages->count();
2825 return $this->mHasSubpages
= false;
2829 * Get all subpages of this page.
2831 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2832 * @return mixed TitleArray, or empty array if this page's namespace
2833 * doesn't allow subpages
2835 public function getSubpages( $limit = -1 ) {
2836 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2840 $dbr = wfGetDB( DB_SLAVE
);
2841 $conds['page_namespace'] = $this->getNamespace();
2842 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2844 if ( $limit > -1 ) {
2845 $options['LIMIT'] = $limit;
2847 return $this->mSubpages
= TitleArray
::newFromResult(
2848 $dbr->select( 'page',
2849 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2858 * Is there a version of this page in the deletion archive?
2860 * @return Int the number of archived revisions
2862 public function isDeleted() {
2863 if ( $this->getNamespace() < 0 ) {
2866 $dbr = wfGetDB( DB_SLAVE
);
2868 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2869 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2872 if ( $this->getNamespace() == NS_FILE
) {
2873 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2874 array( 'fa_name' => $this->getDBkey() ),
2883 * Is there a version of this page in the deletion archive?
2887 public function isDeletedQuick() {
2888 if ( $this->getNamespace() < 0 ) {
2891 $dbr = wfGetDB( DB_SLAVE
);
2892 $deleted = (bool)$dbr->selectField( 'archive', '1',
2893 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2896 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2897 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2898 array( 'fa_name' => $this->getDBkey() ),
2906 * Get the article ID for this Title from the link cache,
2907 * adding it if necessary
2909 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2911 * @return Int the ID
2913 public function getArticleID( $flags = 0 ) {
2914 if ( $this->getNamespace() < 0 ) {
2915 return $this->mArticleID
= 0;
2917 $linkCache = LinkCache
::singleton();
2918 if ( $flags & self
::GAID_FOR_UPDATE
) {
2919 $oldUpdate = $linkCache->forUpdate( true );
2920 $linkCache->clearLink( $this );
2921 $this->mArticleID
= $linkCache->addLinkObj( $this );
2922 $linkCache->forUpdate( $oldUpdate );
2924 if ( -1 == $this->mArticleID
) {
2925 $this->mArticleID
= $linkCache->addLinkObj( $this );
2928 return $this->mArticleID
;
2932 * Is this an article that is a redirect page?
2933 * Uses link cache, adding it if necessary
2935 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2938 public function isRedirect( $flags = 0 ) {
2939 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && !is_null( $this->mRedirect
) ) {
2940 return $this->mRedirect
;
2943 if ( !$this->getArticleID( $flags ) ) {
2944 return $this->mRedirect
= false;
2947 $linkCache = LinkCache
::singleton();
2948 $linkCache->addLinkObj( $this );
2949 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2951 if ( $cached === null ) {
2952 // Should not happen
2953 throw new MWException( "LinkCache doesn't know redirect status of this title: " . $this->getPrefixedDBkey() );
2956 $this->mRedirect
= (bool)$cached;
2958 return $this->mRedirect
;
2962 * What is the length of this page?
2963 * Uses link cache, adding it if necessary
2965 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2968 public function getLength( $flags = 0 ) {
2969 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLength
!= -1 ) {
2970 return $this->mLength
;
2973 if ( !$this->getArticleID( $flags ) ) {
2974 return $this->mLength
= 0;
2977 $linkCache = LinkCache
::singleton();
2978 $linkCache->addLinkObj( $this );
2979 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2981 if ( $cached === null ) {
2982 // Should not happen
2983 throw new MWException( "LinkCache doesn't know redirect status of this title: " . $this->getPrefixedDBkey() );
2986 $this->mLength
= intval( $cached );
2988 return $this->mLength
;
2992 * What is the page_latest field for this page?
2994 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2995 * @throws MWException
2996 * @return Int or 0 if the page doesn't exist
2998 public function getLatestRevID( $flags = 0 ) {
2999 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3000 return intval( $this->mLatestID
);
3003 if ( !$this->getArticleID( $flags ) ) {
3004 return $this->mLatestID
= 0;
3007 $linkCache = LinkCache
::singleton();
3008 $linkCache->addLinkObj( $this );
3009 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3011 if ( $cached === null ) {
3012 // Should not happen
3013 throw new MWException( "LinkCache doesn't know latest revision ID of this title: " . $this->getPrefixedDBkey() );
3016 $this->mLatestID
= intval( $cached );
3018 return $this->mLatestID
;
3022 * This clears some fields in this object, and clears any associated
3023 * keys in the "bad links" section of the link cache.
3025 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3026 * loading of the new page_id. It's also called from
3027 * WikiPage::doDeleteArticleReal()
3029 * @param $newid Int the new Article ID
3031 public function resetArticleID( $newid ) {
3032 $linkCache = LinkCache
::singleton();
3033 $linkCache->clearLink( $this );
3035 if ( $newid === false ) {
3036 $this->mArticleID
= -1;
3038 $this->mArticleID
= intval( $newid );
3040 $this->mRestrictionsLoaded
= false;
3041 $this->mRestrictions
= array();
3042 $this->mRedirect
= null;
3043 $this->mLength
= -1;
3044 $this->mLatestID
= false;
3045 $this->mContentModel
= false;
3046 $this->mEstimateRevisions
= null;
3050 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3052 * @param $text String containing title to capitalize
3053 * @param $ns int namespace index, defaults to NS_MAIN
3054 * @return String containing capitalized title
3056 public static function capitalize( $text, $ns = NS_MAIN
) {
3059 if ( MWNamespace
::isCapitalized( $ns ) ) {
3060 return $wgContLang->ucfirst( $text );
3067 * Secure and split - main initialisation function for this object
3069 * Assumes that mDbkeyform has been set, and is urldecoded
3070 * and uses underscores, but not otherwise munged. This function
3071 * removes illegal characters, splits off the interwiki and
3072 * namespace prefixes, sets the other forms, and canonicalizes
3075 * @return Bool true on success
3077 private function secureAndSplit() {
3078 global $wgContLang, $wgLocalInterwiki;
3081 $this->mInterwiki
= $this->mFragment
= '';
3082 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3084 $dbkey = $this->mDbkeyform
;
3086 # Strip Unicode bidi override characters.
3087 # Sometimes they slip into cut-n-pasted page titles, where the
3088 # override chars get included in list displays.
3089 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
3091 # Clean up whitespace
3092 # Note: use of the /u option on preg_replace here will cause
3093 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3094 # conveniently disabling them.
3095 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3096 $dbkey = trim( $dbkey, '_' );
3098 if ( $dbkey == '' ) {
3102 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3103 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3107 $this->mDbkeyform
= $dbkey;
3109 # Initial colon indicates main namespace rather than specified default
3110 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3111 if ( ':' == $dbkey[0] ) {
3112 $this->mNamespace
= NS_MAIN
;
3113 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3114 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3117 # Namespace or interwiki prefix
3119 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3122 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3124 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3125 # Ordinary namespace
3127 $this->mNamespace
= $ns;
3128 # For Talk:X pages, check if X has a "namespace" prefix
3129 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3130 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3131 # Disallow Talk:File:x type titles...
3133 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3134 # Disallow Talk:Interwiki:x type titles...
3138 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3139 if ( !$firstPass ) {
3140 # Can't make a local interwiki link to an interwiki link.
3141 # That's just crazy!
3147 $this->mInterwiki
= $wgContLang->lc( $p );
3149 # Redundant interwiki prefix to the local wiki
3150 if ( $wgLocalInterwiki !== false
3151 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3153 if ( $dbkey == '' ) {
3154 # Can't have an empty self-link
3157 $this->mInterwiki
= '';
3159 # Do another namespace split...
3163 # If there's an initial colon after the interwiki, that also
3164 # resets the default namespace
3165 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3166 $this->mNamespace
= NS_MAIN
;
3167 $dbkey = substr( $dbkey, 1 );
3170 # If there's no recognized interwiki or namespace,
3171 # then let the colon expression be part of the title.
3176 # We already know that some pages won't be in the database!
3177 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3178 $this->mArticleID
= 0;
3180 $fragment = strstr( $dbkey, '#' );
3181 if ( false !== $fragment ) {
3182 $this->setFragment( $fragment );
3183 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3184 # remove whitespace again: prevents "Foo_bar_#"
3185 # becoming "Foo_bar_"
3186 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3189 # Reject illegal characters.
3190 $rxTc = self
::getTitleInvalidRegex();
3191 if ( preg_match( $rxTc, $dbkey ) ) {
3195 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3196 # reachable due to the way web browsers deal with 'relative' URLs.
3197 # Also, they conflict with subpage syntax. Forbid them explicitly.
3198 if ( strpos( $dbkey, '.' ) !== false &&
3199 ( $dbkey === '.' ||
$dbkey === '..' ||
3200 strpos( $dbkey, './' ) === 0 ||
3201 strpos( $dbkey, '../' ) === 0 ||
3202 strpos( $dbkey, '/./' ) !== false ||
3203 strpos( $dbkey, '/../' ) !== false ||
3204 substr( $dbkey, -2 ) == '/.' ||
3205 substr( $dbkey, -3 ) == '/..' ) )
3210 # Magic tilde sequences? Nu-uh!
3211 if ( strpos( $dbkey, '~~~' ) !== false ) {
3215 # Limit the size of titles to 255 bytes. This is typically the size of the
3216 # underlying database field. We make an exception for special pages, which
3217 # don't need to be stored in the database, and may edge over 255 bytes due
3218 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3219 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3220 strlen( $dbkey ) > 512 )
3225 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3226 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3227 # other site might be case-sensitive.
3228 $this->mUserCaseDBKey
= $dbkey;
3229 if ( $this->mInterwiki
== '' ) {
3230 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3233 # Can't make a link to a namespace alone... "empty" local links can only be
3234 # self-links with a fragment identifier.
3235 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3239 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3240 // IP names are not allowed for accounts, and can only be referring to
3241 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3242 // there are numerous ways to present the same IP. Having sp:contribs scan
3243 // them all is silly and having some show the edits and others not is
3244 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3245 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3246 ? IP
::sanitizeIP( $dbkey )
3249 // Any remaining initial :s are illegal.
3250 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3255 $this->mDbkeyform
= $dbkey;
3256 $this->mUrlform
= wfUrlencode( $dbkey );
3258 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3264 * Get an array of Title objects linking to this Title
3265 * Also stores the IDs in the link cache.
3267 * WARNING: do not use this function on arbitrary user-supplied titles!
3268 * On heavily-used templates it will max out the memory.
3270 * @param $options Array: may be FOR UPDATE
3271 * @param $table String: table name
3272 * @param $prefix String: fields prefix
3273 * @return Array of Title objects linking here
3275 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3276 if ( count( $options ) > 0 ) {
3277 $db = wfGetDB( DB_MASTER
);
3279 $db = wfGetDB( DB_SLAVE
);
3283 array( 'page', $table ),
3284 self
::getSelectFields(),
3286 "{$prefix}_from=page_id",
3287 "{$prefix}_namespace" => $this->getNamespace(),
3288 "{$prefix}_title" => $this->getDBkey() ),
3294 if ( $res->numRows() ) {
3295 $linkCache = LinkCache
::singleton();
3296 foreach ( $res as $row ) {
3297 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3299 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3300 $retVal[] = $titleObj;
3308 * Get an array of Title objects using this Title as a template
3309 * Also stores the IDs in the link cache.
3311 * WARNING: do not use this function on arbitrary user-supplied titles!
3312 * On heavily-used templates it will max out the memory.
3314 * @param $options Array: may be FOR UPDATE
3315 * @return Array of Title the Title objects linking here
3317 public function getTemplateLinksTo( $options = array() ) {
3318 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3322 * Get an array of Title objects linked from this Title
3323 * Also stores the IDs in the link cache.
3325 * WARNING: do not use this function on arbitrary user-supplied titles!
3326 * On heavily-used templates it will max out the memory.
3328 * @param $options Array: may be FOR UPDATE
3329 * @param $table String: table name
3330 * @param $prefix String: fields prefix
3331 * @return Array of Title objects linking here
3333 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3334 global $wgContentHandlerUseDB;
3336 $id = $this->getArticleID();
3338 # If the page doesn't exist; there can't be any link from this page
3343 if ( count( $options ) > 0 ) {
3344 $db = wfGetDB( DB_MASTER
);
3346 $db = wfGetDB( DB_SLAVE
);
3349 $namespaceFiled = "{$prefix}_namespace";
3350 $titleField = "{$prefix}_title";
3352 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3353 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3356 array( $table, 'page' ),
3358 array( "{$prefix}_from" => $id ),
3361 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3365 if ( $res->numRows() ) {
3366 $linkCache = LinkCache
::singleton();
3367 foreach ( $res as $row ) {
3368 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3370 if ( $row->page_id
) {
3371 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3373 $linkCache->addBadLinkObj( $titleObj );
3375 $retVal[] = $titleObj;
3383 * Get an array of Title objects used on this Title as a template
3384 * Also stores the IDs in the link cache.
3386 * WARNING: do not use this function on arbitrary user-supplied titles!
3387 * On heavily-used templates it will max out the memory.
3389 * @param $options Array: may be FOR UPDATE
3390 * @return Array of Title the Title objects used here
3392 public function getTemplateLinksFrom( $options = array() ) {
3393 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3397 * Get an array of Title objects referring to non-existent articles linked from this page
3399 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3400 * @return Array of Title the Title objects
3402 public function getBrokenLinksFrom() {
3403 if ( $this->getArticleID() == 0 ) {
3404 # All links from article ID 0 are false positives
3408 $dbr = wfGetDB( DB_SLAVE
);
3409 $res = $dbr->select(
3410 array( 'page', 'pagelinks' ),
3411 array( 'pl_namespace', 'pl_title' ),
3413 'pl_from' => $this->getArticleID(),
3414 'page_namespace IS NULL'
3416 __METHOD__
, array(),
3420 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3426 foreach ( $res as $row ) {
3427 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3434 * Get a list of URLs to purge from the Squid cache when this
3437 * @return Array of String the URLs
3439 public function getSquidURLs() {
3441 $this->getInternalURL(),
3442 $this->getInternalURL( 'action=history' )
3445 $pageLang = $this->getPageLanguage();
3446 if ( $pageLang->hasVariants() ) {
3447 $variants = $pageLang->getVariants();
3448 foreach ( $variants as $vCode ) {
3449 $urls[] = $this->getInternalURL( '', $vCode );
3457 * Purge all applicable Squid URLs
3459 public function purgeSquid() {
3461 if ( $wgUseSquid ) {
3462 $urls = $this->getSquidURLs();
3463 $u = new SquidUpdate( $urls );
3469 * Move this page without authentication
3471 * @param $nt Title the new page Title
3472 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3474 public function moveNoAuth( &$nt ) {
3475 return $this->moveTo( $nt, false );
3479 * Check whether a given move operation would be valid.
3480 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3482 * @param $nt Title the new title
3483 * @param $auth Bool indicates whether $wgUser's permissions
3485 * @param $reason String is the log summary of the move, used for spam checking
3486 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3488 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3489 global $wgUser, $wgContentHandlerUseDB;
3493 // Normally we'd add this to $errors, but we'll get
3494 // lots of syntax errors if $nt is not an object
3495 return array( array( 'badtitletext' ) );
3497 if ( $this->equals( $nt ) ) {
3498 $errors[] = array( 'selfmove' );
3500 if ( !$this->isMovable() ) {
3501 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3503 if ( $nt->getInterwiki() != '' ) {
3504 $errors[] = array( 'immobile-target-namespace-iw' );
3506 if ( !$nt->isMovable() ) {
3507 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3510 $oldid = $this->getArticleID();
3511 $newid = $nt->getArticleID();
3513 if ( strlen( $nt->getDBkey() ) < 1 ) {
3514 $errors[] = array( 'articleexists' );
3516 if ( ( $this->getDBkey() == '' ) ||
3518 ( $nt->getDBkey() == '' ) ) {
3519 $errors[] = array( 'badarticleerror' );
3522 // Content model checks
3523 if ( !$wgContentHandlerUseDB &&
3524 $this->getContentModel() !== $nt->getContentModel() ) {
3525 // can't move a page if that would change the page's content model
3528 ContentHandler
::getLocalizedName( $this->getContentModel() ),
3529 ContentHandler
::getLocalizedName( $nt->getContentModel() )
3533 // Image-specific checks
3534 if ( $this->getNamespace() == NS_FILE
) {
3535 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3538 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3539 $errors[] = array( 'nonfile-cannot-move-to-file' );
3543 $errors = wfMergeErrorArrays( $errors,
3544 $this->getUserPermissionsErrors( 'move', $wgUser ),
3545 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3546 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3547 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3550 $match = EditPage
::matchSummarySpamRegex( $reason );
3551 if ( $match !== false ) {
3552 // This is kind of lame, won't display nice
3553 $errors[] = array( 'spamprotectiontext' );
3557 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3558 $errors[] = array( 'hookaborted', $err );
3561 # The move is allowed only if (1) the target doesn't exist, or
3562 # (2) the target is a redirect to the source, and has no history
3563 # (so we can undo bad moves right after they're done).
3565 if ( 0 != $newid ) { # Target exists; check for validity
3566 if ( !$this->isValidMoveTarget( $nt ) ) {
3567 $errors[] = array( 'articleexists' );
3570 $tp = $nt->getTitleProtection();
3571 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3572 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3573 $errors[] = array( 'cantmove-titleprotected' );
3576 if ( empty( $errors ) ) {
3583 * Check if the requested move target is a valid file move target
3584 * @param Title $nt Target title
3585 * @return array List of errors
3587 protected function validateFileMoveOperation( $nt ) {
3592 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3594 $file = wfLocalFile( $this );
3595 if ( $file->exists() ) {
3596 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3597 $errors[] = array( 'imageinvalidfilename' );
3599 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3600 $errors[] = array( 'imagetypemismatch' );
3604 if ( $nt->getNamespace() != NS_FILE
) {
3605 $errors[] = array( 'imagenocrossnamespace' );
3606 // From here we want to do checks on a file object, so if we can't
3607 // create one, we must return.
3611 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3613 $destFile = wfLocalFile( $nt );
3614 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3615 $errors[] = array( 'file-exists-sharedrepo' );
3622 * Move a title to a new location
3624 * @param $nt Title the new title
3625 * @param $auth Bool indicates whether $wgUser's permissions
3627 * @param $reason String the reason for the move
3628 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3629 * Ignored if the user doesn't have the suppressredirect right.
3630 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3632 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3634 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3635 if ( is_array( $err ) ) {
3636 // Auto-block user's IP if the account was "hard" blocked
3637 $wgUser->spreadAnyEditBlock();
3640 // Check suppressredirect permission
3641 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3642 $createRedirect = true;
3645 // If it is a file, move it first.
3646 // It is done before all other moving stuff is done because it's hard to revert.
3647 $dbw = wfGetDB( DB_MASTER
);
3648 if ( $this->getNamespace() == NS_FILE
) {
3649 $file = wfLocalFile( $this );
3650 if ( $file->exists() ) {
3651 $status = $file->move( $nt );
3652 if ( !$status->isOk() ) {
3653 return $status->getErrorsArray();
3656 // Clear RepoGroup process cache
3657 RepoGroup
::singleton()->clearCache( $this );
3658 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3661 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3662 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3663 $protected = $this->isProtected();
3665 // Do the actual move
3666 $this->moveToInternal( $nt, $reason, $createRedirect );
3668 // Refresh the sortkey for this row. Be careful to avoid resetting
3669 // cl_timestamp, which may disturb time-based lists on some sites.
3670 $prefixes = $dbw->select(
3672 array( 'cl_sortkey_prefix', 'cl_to' ),
3673 array( 'cl_from' => $pageid ),
3676 foreach ( $prefixes as $prefixRow ) {
3677 $prefix = $prefixRow->cl_sortkey_prefix
;
3678 $catTo = $prefixRow->cl_to
;
3679 $dbw->update( 'categorylinks',
3681 'cl_sortkey' => Collation
::singleton()->getSortKey(
3682 $nt->getCategorySortkey( $prefix ) ),
3683 'cl_timestamp=cl_timestamp' ),
3685 'cl_from' => $pageid,
3686 'cl_to' => $catTo ),
3691 $redirid = $this->getArticleID();
3694 # Protect the redirect title as the title used to be...
3695 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3697 'pr_page' => $redirid,
3698 'pr_type' => 'pr_type',
3699 'pr_level' => 'pr_level',
3700 'pr_cascade' => 'pr_cascade',
3701 'pr_user' => 'pr_user',
3702 'pr_expiry' => 'pr_expiry'
3704 array( 'pr_page' => $pageid ),
3708 # Update the protection log
3709 $log = new LogPage( 'protect' );
3710 $comment = wfMessage(
3712 $this->getPrefixedText(),
3713 $nt->getPrefixedText()
3714 )->inContentLanguage()->text();
3716 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3718 // @todo FIXME: $params?
3719 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3723 $oldnamespace = MWNamespace
::getSubject( $this->getNamespace() );
3724 $newnamespace = MWNamespace
::getSubject( $nt->getNamespace() );
3725 $oldtitle = $this->getDBkey();
3726 $newtitle = $nt->getDBkey();
3728 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3729 WatchedItem
::duplicateEntries( $this, $nt );
3732 $dbw->commit( __METHOD__
);
3734 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3739 * Move page to a title which is either a redirect to the
3740 * source page or nonexistent
3742 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3743 * @param $reason String The reason for the move
3744 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3745 * if the user has the suppressredirect right
3746 * @throws MWException
3748 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3749 global $wgUser, $wgContLang;
3751 if ( $nt->exists() ) {
3752 $moveOverRedirect = true;
3753 $logType = 'move_redir';
3755 $moveOverRedirect = false;
3759 if ( $createRedirect ) {
3760 $contentHandler = ContentHandler
::getForTitle( $this );
3761 $redirectContent = $contentHandler->makeRedirectContent( $nt );
3763 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3765 $redirectContent = null;
3768 $logEntry = new ManualLogEntry( 'move', $logType );
3769 $logEntry->setPerformer( $wgUser );
3770 $logEntry->setTarget( $this );
3771 $logEntry->setComment( $reason );
3772 $logEntry->setParameters( array(
3773 '4::target' => $nt->getPrefixedText(),
3774 '5::noredir' => $redirectContent ?
'0': '1',
3777 $formatter = LogFormatter
::newFromEntry( $logEntry );
3778 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3779 $comment = $formatter->getPlainActionText();
3781 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3783 # Truncate for whole multibyte characters.
3784 $comment = $wgContLang->truncate( $comment, 255 );
3786 $oldid = $this->getArticleID();
3788 $dbw = wfGetDB( DB_MASTER
);
3790 $newpage = WikiPage
::factory( $nt );
3792 if ( $moveOverRedirect ) {
3793 $newid = $nt->getArticleID();
3795 # Delete the old redirect. We don't save it to history since
3796 # by definition if we've got here it's rather uninteresting.
3797 # We have to remove it so that the next step doesn't trigger
3798 # a conflict on the unique namespace+title index...
3799 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3801 $newpage->doDeleteUpdates( $newid );
3804 # Save a null revision in the page's history notifying of the move
3805 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3806 if ( !is_object( $nullRevision ) ) {
3807 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3810 $nullRevision->insertOn( $dbw );
3812 # Change the name of the target page:
3813 $dbw->update( 'page',
3815 'page_namespace' => $nt->getNamespace(),
3816 'page_title' => $nt->getDBkey(),
3818 /* WHERE */ array( 'page_id' => $oldid ),
3822 $this->resetArticleID( 0 );
3823 $nt->resetArticleID( $oldid );
3825 $newpage->updateRevisionOn( $dbw, $nullRevision );
3827 wfRunHooks( 'NewRevisionFromEditComplete',
3828 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3830 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3832 if ( !$moveOverRedirect ) {
3833 WikiPage
::onArticleCreate( $nt );
3836 # Recreate the redirect, this time in the other direction.
3837 if ( !$redirectContent ) {
3838 WikiPage
::onArticleDelete( $this );
3840 $redirectArticle = WikiPage
::factory( $this );
3841 $newid = $redirectArticle->insertOn( $dbw );
3842 if ( $newid ) { // sanity
3843 $redirectRevision = new Revision( array(
3844 'title' => $this, // for determining the default content model
3846 'comment' => $comment,
3847 'content' => $redirectContent ) );
3848 $redirectRevision->insertOn( $dbw );
3849 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3851 wfRunHooks( 'NewRevisionFromEditComplete',
3852 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3854 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3859 $logid = $logEntry->insert();
3860 $logEntry->publish( $logid );
3864 * Move this page's subpages to be subpages of $nt
3866 * @param $nt Title Move target
3867 * @param $auth bool Whether $wgUser's permissions should be checked
3868 * @param $reason string The reason for the move
3869 * @param $createRedirect bool Whether to create redirects from the old subpages to
3870 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3871 * @return mixed array with old page titles as keys, and strings (new page titles) or
3872 * arrays (errors) as values, or an error array with numeric indices if no pages
3875 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3876 global $wgMaximumMovedPages;
3877 // Check permissions
3878 if ( !$this->userCan( 'move-subpages' ) ) {
3879 return array( 'cant-move-subpages' );
3881 // Do the source and target namespaces support subpages?
3882 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3883 return array( 'namespace-nosubpages',
3884 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3886 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3887 return array( 'namespace-nosubpages',
3888 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3891 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3894 foreach ( $subpages as $oldSubpage ) {
3896 if ( $count > $wgMaximumMovedPages ) {
3897 $retval[$oldSubpage->getPrefixedTitle()] =
3898 array( 'movepage-max-pages',
3899 $wgMaximumMovedPages );
3903 // We don't know whether this function was called before
3904 // or after moving the root page, so check both
3906 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3907 $oldSubpage->getArticleID() == $nt->getArticleID() )
3909 // When moving a page to a subpage of itself,
3910 // don't move it twice
3913 $newPageName = preg_replace(
3914 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3915 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3916 $oldSubpage->getDBkey() );
3917 if ( $oldSubpage->isTalkPage() ) {
3918 $newNs = $nt->getTalkPage()->getNamespace();
3920 $newNs = $nt->getSubjectPage()->getNamespace();
3922 # Bug 14385: we need makeTitleSafe because the new page names may
3923 # be longer than 255 characters.
3924 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3926 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3927 if ( $success === true ) {
3928 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3930 $retval[$oldSubpage->getPrefixedText()] = $success;
3937 * Checks if this page is just a one-rev redirect.
3938 * Adds lock, so don't use just for light purposes.
3942 public function isSingleRevRedirect() {
3943 global $wgContentHandlerUseDB;
3945 $dbw = wfGetDB( DB_MASTER
);
3948 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3949 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3951 $row = $dbw->selectRow( 'page',
3955 array( 'FOR UPDATE' )
3957 # Cache some fields we may want
3958 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3959 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3960 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3961 $this->mContentModel
= $row && isset( $row->page_content_model
) ?
strval( $row->page_content_model
) : false;
3962 if ( !$this->mRedirect
) {
3965 # Does the article have a history?
3966 $row = $dbw->selectField( array( 'page', 'revision' ),
3968 array( 'page_namespace' => $this->getNamespace(),
3969 'page_title' => $this->getDBkey(),
3971 'page_latest != rev_id'
3974 array( 'FOR UPDATE' )
3976 # Return true if there was no history
3977 return ( $row === false );
3981 * Checks if $this can be moved to a given Title
3982 * - Selects for update, so don't call it unless you mean business
3984 * @param $nt Title the new title to check
3987 public function isValidMoveTarget( $nt ) {
3988 # Is it an existing file?
3989 if ( $nt->getNamespace() == NS_FILE
) {
3990 $file = wfLocalFile( $nt );
3991 if ( $file->exists() ) {
3992 wfDebug( __METHOD__
. ": file exists\n" );
3996 # Is it a redirect with no history?
3997 if ( !$nt->isSingleRevRedirect() ) {
3998 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4001 # Get the article text
4002 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4003 if( !is_object( $rev ) ) {
4006 $content = $rev->getContent();
4007 # Does the redirect point to the source?
4008 # Or is it a broken self-redirect, usually caused by namespace collisions?
4009 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4011 if ( $redirTitle ) {
4012 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4013 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4014 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4020 # Fail safe (not a redirect after all. strange.)
4021 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4022 " is a redirect, but it doesn't contain a valid redirect.\n" );
4028 * Get categories to which this Title belongs and return an array of
4029 * categories' names.
4031 * @return Array of parents in the form:
4032 * $parent => $currentarticle
4034 public function getParentCategories() {
4039 $titleKey = $this->getArticleID();
4041 if ( $titleKey === 0 ) {
4045 $dbr = wfGetDB( DB_SLAVE
);
4047 $res = $dbr->select(
4050 array( 'cl_from' => $titleKey ),
4054 if ( $res->numRows() > 0 ) {
4055 foreach ( $res as $row ) {
4056 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
4057 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4064 * Get a tree of parent categories
4066 * @param $children Array with the children in the keys, to check for circular refs
4067 * @return Array Tree of parent categories
4069 public function getParentCategoryTree( $children = array() ) {
4071 $parents = $this->getParentCategories();
4074 foreach ( $parents as $parent => $current ) {
4075 if ( array_key_exists( $parent, $children ) ) {
4076 # Circular reference
4077 $stack[$parent] = array();
4079 $nt = Title
::newFromText( $parent );
4081 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
4091 * Get an associative array for selecting this title from
4094 * @return Array suitable for the $where parameter of DB::select()
4096 public function pageCond() {
4097 if ( $this->mArticleID
> 0 ) {
4098 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4099 return array( 'page_id' => $this->mArticleID
);
4101 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4106 * Get the revision ID of the previous revision
4108 * @param $revId Int Revision ID. Get the revision that was before this one.
4109 * @param $flags Int Title::GAID_FOR_UPDATE
4110 * @return Int|Bool Old revision ID, or FALSE if none exists
4112 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4113 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4114 $revId = $db->selectField( 'revision', 'rev_id',
4116 'rev_page' => $this->getArticleID( $flags ),
4117 'rev_id < ' . intval( $revId )
4120 array( 'ORDER BY' => 'rev_id DESC' )
4123 if ( $revId === false ) {
4126 return intval( $revId );
4131 * Get the revision ID of the next revision
4133 * @param $revId Int Revision ID. Get the revision that was after this one.
4134 * @param $flags Int Title::GAID_FOR_UPDATE
4135 * @return Int|Bool Next revision ID, or FALSE if none exists
4137 public function getNextRevisionID( $revId, $flags = 0 ) {
4138 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4139 $revId = $db->selectField( 'revision', 'rev_id',
4141 'rev_page' => $this->getArticleID( $flags ),
4142 'rev_id > ' . intval( $revId )
4145 array( 'ORDER BY' => 'rev_id' )
4148 if ( $revId === false ) {
4151 return intval( $revId );
4156 * Get the first revision of the page
4158 * @param $flags Int Title::GAID_FOR_UPDATE
4159 * @return Revision|Null if page doesn't exist
4161 public function getFirstRevision( $flags = 0 ) {
4162 $pageId = $this->getArticleID( $flags );
4164 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4165 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4166 array( 'rev_page' => $pageId ),
4168 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4171 return new Revision( $row );
4178 * Get the oldest revision timestamp of this page
4180 * @param $flags Int Title::GAID_FOR_UPDATE
4181 * @return String: MW timestamp
4183 public function getEarliestRevTime( $flags = 0 ) {
4184 $rev = $this->getFirstRevision( $flags );
4185 return $rev ?
$rev->getTimestamp() : null;
4189 * Check if this is a new page
4193 public function isNewPage() {
4194 $dbr = wfGetDB( DB_SLAVE
);
4195 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4199 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4203 public function isBigDeletion() {
4204 global $wgDeleteRevisionsLimit;
4206 if ( !$wgDeleteRevisionsLimit ) {
4210 $revCount = $this->estimateRevisionCount();
4211 return $revCount > $wgDeleteRevisionsLimit;
4215 * Get the approximate revision count of this page.
4219 public function estimateRevisionCount() {
4220 if ( !$this->exists() ) {
4224 if ( $this->mEstimateRevisions
=== null ) {
4225 $dbr = wfGetDB( DB_SLAVE
);
4226 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4227 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4230 return $this->mEstimateRevisions
;
4234 * Get the number of revisions between the given revision.
4235 * Used for diffs and other things that really need it.
4237 * @param $old int|Revision Old revision or rev ID (first before range)
4238 * @param $new int|Revision New revision or rev ID (first after range)
4239 * @return Int Number of revisions between these revisions.
4241 public function countRevisionsBetween( $old, $new ) {
4242 if ( !( $old instanceof Revision
) ) {
4243 $old = Revision
::newFromTitle( $this, (int)$old );
4245 if ( !( $new instanceof Revision
) ) {
4246 $new = Revision
::newFromTitle( $this, (int)$new );
4248 if ( !$old ||
!$new ) {
4249 return 0; // nothing to compare
4251 $dbr = wfGetDB( DB_SLAVE
);
4252 return (int)$dbr->selectField( 'revision', 'count(*)',
4254 'rev_page' => $this->getArticleID(),
4255 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4256 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4263 * Get the number of authors between the given revisions or revision IDs.
4264 * Used for diffs and other things that really need it.
4266 * @param $old int|Revision Old revision or rev ID (first before range by default)
4267 * @param $new int|Revision New revision or rev ID (first after range by default)
4268 * @param $limit int Maximum number of authors
4269 * @param $options string|array (Optional): Single option, or an array of options:
4270 * 'include_old' Include $old in the range; $new is excluded.
4271 * 'include_new' Include $new in the range; $old is excluded.
4272 * 'include_both' Include both $old and $new in the range.
4273 * Unknown option values are ignored.
4274 * @return int Number of revision authors in the range; zero if not both revisions exist
4276 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4277 if ( !( $old instanceof Revision
) ) {
4278 $old = Revision
::newFromTitle( $this, (int)$old );
4280 if ( !( $new instanceof Revision
) ) {
4281 $new = Revision
::newFromTitle( $this, (int)$new );
4283 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4284 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4285 // in the sanity check below?
4286 if ( !$old ||
!$new ) {
4287 return 0; // nothing to compare
4291 $options = (array) $options;
4292 if ( in_array( 'include_old', $options ) ) {
4295 if ( in_array( 'include_new', $options ) ) {
4298 if ( in_array( 'include_both', $options ) ) {
4302 // No DB query needed if $old and $new are the same or successive revisions:
4303 if ( $old->getId() === $new->getId() ) {
4304 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4305 } else if ( $old->getId() === $new->getParentId() ) {
4306 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4307 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4309 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4311 $dbr = wfGetDB( DB_SLAVE
);
4312 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4314 'rev_page' => $this->getArticleID(),
4315 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4316 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4318 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4320 return (int)$dbr->numRows( $res );
4324 * Compare with another title.
4326 * @param $title Title
4329 public function equals( Title
$title ) {
4330 // Note: === is necessary for proper matching of number-like titles.
4331 return $this->getInterwiki() === $title->getInterwiki()
4332 && $this->getNamespace() == $title->getNamespace()
4333 && $this->getDBkey() === $title->getDBkey();
4337 * Check if this title is a subpage of another title
4339 * @param $title Title
4342 public function isSubpageOf( Title
$title ) {
4343 return $this->getInterwiki() === $title->getInterwiki()
4344 && $this->getNamespace() == $title->getNamespace()
4345 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4349 * Check if page exists. For historical reasons, this function simply
4350 * checks for the existence of the title in the page table, and will
4351 * thus return false for interwiki links, special pages and the like.
4352 * If you want to know if a title can be meaningfully viewed, you should
4353 * probably call the isKnown() method instead.
4357 public function exists() {
4358 return $this->getArticleID() != 0;
4362 * Should links to this title be shown as potentially viewable (i.e. as
4363 * "bluelinks"), even if there's no record by this title in the page
4366 * This function is semi-deprecated for public use, as well as somewhat
4367 * misleadingly named. You probably just want to call isKnown(), which
4368 * calls this function internally.
4370 * (ISSUE: Most of these checks are cheap, but the file existence check
4371 * can potentially be quite expensive. Including it here fixes a lot of
4372 * existing code, but we might want to add an optional parameter to skip
4373 * it and any other expensive checks.)
4377 public function isAlwaysKnown() {
4381 * Allows overriding default behaviour for determining if a page exists.
4382 * If $isKnown is kept as null, regular checks happen. If it's
4383 * a boolean, this value is returned by the isKnown method.
4387 * @param Title $title
4388 * @param boolean|null $isKnown
4390 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4392 if ( !is_null( $isKnown ) ) {
4396 if ( $this->mInterwiki
!= '' ) {
4397 return true; // any interwiki link might be viewable, for all we know
4400 switch( $this->mNamespace
) {
4403 // file exists, possibly in a foreign repo
4404 return (bool)wfFindFile( $this );
4406 // valid special page
4407 return SpecialPageFactory
::exists( $this->getDBkey() );
4409 // selflink, possibly with fragment
4410 return $this->mDbkeyform
== '';
4412 // known system message
4413 return $this->hasSourceText() !== false;
4420 * Does this title refer to a page that can (or might) be meaningfully
4421 * viewed? In particular, this function may be used to determine if
4422 * links to the title should be rendered as "bluelinks" (as opposed to
4423 * "redlinks" to non-existent pages).
4424 * Adding something else to this function will cause inconsistency
4425 * since LinkHolderArray calls isAlwaysKnown() and does its own
4426 * page existence check.
4430 public function isKnown() {
4431 return $this->isAlwaysKnown() ||
$this->exists();
4435 * Does this page have source text?
4439 public function hasSourceText() {
4440 if ( $this->exists() ) {
4444 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4445 // If the page doesn't exist but is a known system message, default
4446 // message content will be displayed, same for language subpages-
4447 // Use always content language to avoid loading hundreds of languages
4448 // to get the link color.
4450 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4451 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4452 return $message->exists();
4459 * Get the default message text or false if the message doesn't exist
4461 * @return String or false
4463 public function getDefaultMessageText() {
4466 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4470 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4471 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4473 if ( $message->exists() ) {
4474 return $message->plain();
4481 * Updates page_touched for this page; called from LinksUpdate.php
4483 * @return Bool true if the update succeded
4485 public function invalidateCache() {
4487 if ( wfReadOnly() ) {
4490 $dbw = wfGetDB( DB_MASTER
);
4491 $success = $dbw->update(
4493 array( 'page_touched' => $dbw->timestamp() ),
4497 HTMLFileCache
::clearFileCache( $this );
4500 $revision = WikiPage
::factory( $this )->getRevision();
4501 if( $revision !== null ) {
4502 $memcKey = wfMemcKey( 'infoaction', $this->getPrefixedText(), $revision->getId() );
4503 $success = $success && $wgMemc->delete( $memcKey );
4510 * Update page_touched timestamps and send squid purge messages for
4511 * pages linking to this title. May be sent to the job queue depending
4512 * on the number of links. Typically called on create and delete.
4514 public function touchLinks() {
4515 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4518 if ( $this->getNamespace() == NS_CATEGORY
) {
4519 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4525 * Get the last touched timestamp
4527 * @param $db DatabaseBase: optional db
4528 * @return String last-touched timestamp
4530 public function getTouched( $db = null ) {
4531 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4532 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4537 * Get the timestamp when this page was updated since the user last saw it.
4540 * @return String|Null
4542 public function getNotificationTimestamp( $user = null ) {
4543 global $wgUser, $wgShowUpdatedMarker;
4544 // Assume current user if none given
4548 // Check cache first
4549 $uid = $user->getId();
4550 // avoid isset here, as it'll return false for null entries
4551 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4552 return $this->mNotificationTimestamp
[$uid];
4554 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4555 return $this->mNotificationTimestamp
[$uid] = false;
4557 // Don't cache too much!
4558 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4559 $this->mNotificationTimestamp
= array();
4561 $dbr = wfGetDB( DB_SLAVE
);
4562 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4563 'wl_notificationtimestamp',
4565 'wl_user' => $user->getId(),
4566 'wl_namespace' => $this->getNamespace(),
4567 'wl_title' => $this->getDBkey(),
4571 return $this->mNotificationTimestamp
[$uid];
4575 * Generate strings used for xml 'id' names in monobook tabs
4577 * @param $prepend string defaults to 'nstab-'
4578 * @return String XML 'id' name
4580 public function getNamespaceKey( $prepend = 'nstab-' ) {
4582 // Gets the subject namespace if this title
4583 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4584 // Checks if cononical namespace name exists for namespace
4585 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4586 // Uses canonical namespace name
4587 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4589 // Uses text of namespace
4590 $namespaceKey = $this->getSubjectNsText();
4592 // Makes namespace key lowercase
4593 $namespaceKey = $wgContLang->lc( $namespaceKey );
4595 if ( $namespaceKey == '' ) {
4596 $namespaceKey = 'main';
4598 // Changes file to image for backwards compatibility
4599 if ( $namespaceKey == 'file' ) {
4600 $namespaceKey = 'image';
4602 return $prepend . $namespaceKey;
4606 * Get all extant redirects to this Title
4608 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4609 * @return Array of Title redirects to this title
4611 public function getRedirectsHere( $ns = null ) {
4614 $dbr = wfGetDB( DB_SLAVE
);
4616 'rd_namespace' => $this->getNamespace(),
4617 'rd_title' => $this->getDBkey(),
4620 if ( $this->isExternal() ) {
4621 $where['rd_interwiki'] = $this->getInterwiki();
4623 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4625 if ( !is_null( $ns ) ) {
4626 $where['page_namespace'] = $ns;
4629 $res = $dbr->select(
4630 array( 'redirect', 'page' ),
4631 array( 'page_namespace', 'page_title' ),
4636 foreach ( $res as $row ) {
4637 $redirs[] = self
::newFromRow( $row );
4643 * Check if this Title is a valid redirect target
4647 public function isValidRedirectTarget() {
4648 global $wgInvalidRedirectTargets;
4650 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4651 if ( $this->isSpecial( 'Userlogout' ) ) {
4655 foreach ( $wgInvalidRedirectTargets as $target ) {
4656 if ( $this->isSpecial( $target ) ) {
4665 * Get a backlink cache object
4667 * @return BacklinkCache
4669 public function getBacklinkCache() {
4670 return BacklinkCache
::get( $this );
4674 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4678 public function canUseNoindex() {
4679 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4681 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4682 ?
$wgContentNamespaces
4683 : $wgExemptFromUserRobotsControl;
4685 return !in_array( $this->mNamespace
, $bannedNamespaces );
4690 * Returns the raw sort key to be used for categories, with the specified
4691 * prefix. This will be fed to Collation::getSortKey() to get a
4692 * binary sortkey that can be used for actual sorting.
4694 * @param $prefix string The prefix to be used, specified using
4695 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4699 public function getCategorySortkey( $prefix = '' ) {
4700 $unprefixed = $this->getText();
4702 // Anything that uses this hook should only depend
4703 // on the Title object passed in, and should probably
4704 // tell the users to run updateCollations.php --force
4705 // in order to re-sort existing category relations.
4706 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4707 if ( $prefix !== '' ) {
4708 # Separate with a line feed, so the unprefixed part is only used as
4709 # a tiebreaker when two pages have the exact same prefix.
4710 # In UCA, tab is the only character that can sort above LF
4711 # so we strip both of them from the original prefix.
4712 $prefix = strtr( $prefix, "\n\t", ' ' );
4713 return "$prefix\n$unprefixed";
4719 * Get the language in which the content of this page is written in
4720 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4721 * e.g. $wgLang (such as special pages, which are in the user language).
4726 public function getPageLanguage() {
4728 if ( $this->isSpecialPage() ) {
4729 // special pages are in the user language
4733 //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
4734 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4735 $contentHandler = ContentHandler
::getForTitle( $this );
4736 $pageLang = $contentHandler->getPageLanguage( $this );
4738 return wfGetLangObj( $pageLang );
4742 * Get the language in which the content of this page is written when
4743 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4744 * e.g. $wgLang (such as special pages, which are in the user language).
4749 public function getPageViewLanguage() {
4752 if ( $this->isSpecialPage() ) {
4753 // If the user chooses a variant, the content is actually
4754 // in a language whose code is the variant code.
4755 $variant = $wgLang->getPreferredVariant();
4756 if ( $wgLang->getCode() !== $variant ) {
4757 return Language
::factory( $variant );
4763 //NOTE: can't be cached persistently, depends on user settings
4764 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4765 $contentHandler = ContentHandler
::getForTitle( $this );
4766 $pageLang = $contentHandler->getPageViewLanguage( $this );
4771 * Get a list of rendered edit notices for this page.
4773 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4774 * they will already be wrapped in paragraphs.
4779 public function getEditNotices() {
4782 # Optional notices on a per-namespace and per-page basis
4783 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4784 $editnotice_ns_message = wfMessage( $editnotice_ns );
4785 if ( $editnotice_ns_message->exists() ) {
4786 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4788 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4789 $parts = explode( '/', $this->getDBkey() );
4790 $editnotice_base = $editnotice_ns;
4791 while ( count( $parts ) > 0 ) {
4792 $editnotice_base .= '-' . array_shift( $parts );
4793 $editnotice_base_msg = wfMessage( $editnotice_base );
4794 if ( $editnotice_base_msg->exists() ) {
4795 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4799 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4800 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4801 $editnoticeMsg = wfMessage( $editnoticeText );
4802 if ( $editnoticeMsg->exists() ) {
4803 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();