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
94 /*protected*/ function __construct() { }
97 * Create a new Title from a prefixed DB key
99 * @param string $key the database key, which has underscores
100 * instead of spaces, possibly including namespace and
102 * @return Title, or NULL on an error
104 public static function newFromDBkey( $key ) {
106 $t->mDbkeyform
= $key;
107 if ( $t->secureAndSplit() ) {
115 * Create a new Title from text, such as what one would find in a link. De-
116 * codes any HTML entities in the text.
118 * @param string $text the link text; spaces, prefixes, and an
119 * initial ':' indicating the main namespace are accepted.
120 * @param int $defaultNamespace the namespace to use if none is specified
121 * by a prefix. If you want to force a specific namespace even if
122 * $text might begin with a namespace prefix, use makeTitle() or
124 * @throws MWException
125 * @return Title|null - Title or null on an error.
127 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
128 if ( is_object( $text ) ) {
129 throw new MWException( 'Title::newFromText given an object' );
133 * Wiki pages often contain multiple links to the same page.
134 * Title normalization and parsing can become expensive on
135 * pages with many links, so we can save a little time by
138 * In theory these are value objects and won't get changed...
140 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
141 return Title
::$titleCache[$text];
144 # Convert things like é ā or 〗 into normalized (bug 14952) text
145 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
148 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
149 $t->mDefaultNamespace
= $defaultNamespace;
151 static $cachedcount = 0;
152 if ( $t->secureAndSplit() ) {
153 if ( $defaultNamespace == NS_MAIN
) {
154 if ( $cachedcount >= self
::CACHE_MAX
) {
155 # Avoid memory leaks on mass operations...
156 Title
::$titleCache = array();
160 Title
::$titleCache[$text] =& $t;
170 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
172 * Example of wrong and broken code:
173 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
175 * Example of right code:
176 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
178 * Create a new Title from URL-encoded text. Ensures that
179 * the given title's length does not exceed the maximum.
181 * @param string $url the title, as might be taken from a URL
182 * @return Title the new object, or NULL on an error
184 public static function newFromURL( $url ) {
187 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
188 # but some URLs used it as a space replacement and they still come
189 # from some external search tools.
190 if ( strpos( self
::legalChars(), '+' ) === false ) {
191 $url = str_replace( '+', ' ', $url );
194 $t->mDbkeyform
= str_replace( ' ', '_', $url );
195 if ( $t->secureAndSplit() ) {
203 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
204 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
208 protected static function getSelectFields() {
209 global $wgContentHandlerUseDB;
212 'page_namespace', 'page_title', 'page_id',
213 'page_len', 'page_is_redirect', 'page_latest',
216 if ( $wgContentHandlerUseDB ) {
217 $fields[] = 'page_content_model';
224 * Create a new Title from an article ID
226 * @param int $id the page_id corresponding to the Title to create
227 * @param int $flags use Title::GAID_FOR_UPDATE to use master
228 * @return Title the new object, or NULL on an error
230 public static function newFromID( $id, $flags = 0 ) {
231 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
232 $row = $db->selectRow(
234 self
::getSelectFields(),
235 array( 'page_id' => $id ),
238 if ( $row !== false ) {
239 $title = Title
::newFromRow( $row );
247 * Make an array of titles from an array of IDs
249 * @param array $ids of Int Array of IDs
250 * @return Array of Titles
252 public static function newFromIDs( $ids ) {
253 if ( !count( $ids ) ) {
256 $dbr = wfGetDB( DB_SLAVE
);
260 self
::getSelectFields(),
261 array( 'page_id' => $ids ),
266 foreach ( $res as $row ) {
267 $titles[] = Title
::newFromRow( $row );
273 * Make a Title object from a DB row
275 * @param $row Object database row (needs at least page_title,page_namespace)
276 * @return Title corresponding Title
278 public static function newFromRow( $row ) {
279 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
280 $t->loadFromRow( $row );
285 * Load Title object fields from a DB row.
286 * If false is given, the title will be treated as non-existing.
288 * @param $row Object|bool database row
290 public function loadFromRow( $row ) {
291 if ( $row ) { // page found
292 if ( isset( $row->page_id
) )
293 $this->mArticleID
= (int)$row->page_id
;
294 if ( isset( $row->page_len
) )
295 $this->mLength
= (int)$row->page_len
;
296 if ( isset( $row->page_is_redirect
) )
297 $this->mRedirect
= (bool)$row->page_is_redirect
;
298 if ( isset( $row->page_latest
) )
299 $this->mLatestID
= (int)$row->page_latest
;
300 if ( isset( $row->page_content_model
) )
301 $this->mContentModel
= strval( $row->page_content_model
);
303 $this->mContentModel
= false; # initialized lazily in getContentModel()
304 } else { // page not found
305 $this->mArticleID
= 0;
307 $this->mRedirect
= false;
308 $this->mLatestID
= 0;
309 $this->mContentModel
= false; # initialized lazily in getContentModel()
314 * Create a new Title from a namespace index and a DB key.
315 * It's assumed that $ns and $title are *valid*, for instance when
316 * they came directly from the database or a special page name.
317 * For convenience, spaces are converted to underscores so that
318 * eg user_text fields can be used directly.
320 * @param int $ns the namespace of the article
321 * @param string $title the unprefixed database key form
322 * @param string $fragment the link fragment (after the "#")
323 * @param string $interwiki the interwiki prefix
324 * @return Title the new object
326 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
328 $t->mInterwiki
= $interwiki;
329 $t->mFragment
= $fragment;
330 $t->mNamespace
= $ns = intval( $ns );
331 $t->mDbkeyform
= str_replace( ' ', '_', $title );
332 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
333 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
334 $t->mTextform
= str_replace( '_', ' ', $title );
335 $t->mContentModel
= false; # initialized lazily in getContentModel()
340 * Create a new Title from a namespace index and a DB key.
341 * The parameters will be checked for validity, which is a bit slower
342 * than makeTitle() but safer for user-provided data.
344 * @param int $ns the namespace of the article
345 * @param string $title database key form
346 * @param string $fragment the link fragment (after the "#")
347 * @param string $interwiki interwiki prefix
348 * @return Title the new object, or NULL on an error
350 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
351 if ( !MWNamespace
::exists( $ns ) ) {
356 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
357 if ( $t->secureAndSplit() ) {
365 * Create a new Title for the Main Page
367 * @return Title the new object
369 public static function newMainPage() {
370 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
371 // Don't give fatal errors if the message is broken
373 $title = Title
::newFromText( 'Main Page' );
379 * Extract a redirect destination from a string and return the
380 * Title, or null if the text doesn't contain a valid redirect
381 * This will only return the very next target, useful for
382 * the redirect table and other checks that don't need full recursion
384 * @param string $text Text with possible redirect
385 * @return Title: The corresponding Title
386 * @deprecated since 1.21, use Content::getRedirectTarget instead.
388 public static function newFromRedirect( $text ) {
389 ContentHandler
::deprecated( __METHOD__
, '1.21' );
391 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
392 return $content->getRedirectTarget();
396 * Extract a redirect destination from a string and return the
397 * Title, or null if the text doesn't contain a valid redirect
398 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
399 * in order to provide (hopefully) the Title of the final destination instead of another redirect
401 * @param string $text Text with possible redirect
403 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
405 public static function newFromRedirectRecurse( $text ) {
406 ContentHandler
::deprecated( __METHOD__
, '1.21' );
408 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
409 return $content->getUltimateRedirectTarget();
413 * Extract a redirect destination from a string and return an
414 * array of Titles, or null if the text doesn't contain a valid redirect
415 * The last element in the array is the final destination after all redirects
416 * have been resolved (up to $wgMaxRedirects times)
418 * @param string $text Text with possible redirect
419 * @return Array of Titles, with the destination last
420 * @deprecated since 1.21, use Content::getRedirectChain instead.
422 public static function newFromRedirectArray( $text ) {
423 ContentHandler
::deprecated( __METHOD__
, '1.21' );
425 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
426 return $content->getRedirectChain();
430 * Get the prefixed DB key associated with an ID
432 * @param int $id the page_id of the article
433 * @return Title an object representing the article, or NULL if no such article was found
435 public static function nameOf( $id ) {
436 $dbr = wfGetDB( DB_SLAVE
);
438 $s = $dbr->selectRow(
440 array( 'page_namespace', 'page_title' ),
441 array( 'page_id' => $id ),
444 if ( $s === false ) {
448 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
453 * Get a regex character class describing the legal characters in a link
455 * @return String the list of characters, not delimited
457 public static function legalChars() {
458 global $wgLegalTitleChars;
459 return $wgLegalTitleChars;
463 * Returns a simple regex that will match on characters and sequences invalid in titles.
464 * Note that this doesn't pick up many things that could be wrong with titles, but that
465 * replacing this regex with something valid will make many titles valid.
467 * @return String regex string
469 static function getTitleInvalidRegex() {
470 static $rxTc = false;
472 # Matching titles will be held as illegal.
474 # Any character not allowed is forbidden...
475 '[^' . self
::legalChars() . ']' .
476 # URL percent encoding sequences interfere with the ability
477 # to round-trip titles -- you can't link to them consistently.
479 # XML/HTML character references produce similar issues.
480 '|&[A-Za-z0-9\x80-\xff]+;' .
482 '|&#x[0-9A-Fa-f]+;' .
490 * Get a string representation of a title suitable for
491 * including in a search index
493 * @param int $ns a namespace index
494 * @param string $title text-form main part
495 * @return String a stripped-down title string ready for the search index
497 public static function indexTitle( $ns, $title ) {
500 $lc = SearchEngine
::legalSearchChars() . '&#;';
501 $t = $wgContLang->normalizeForSearch( $title );
502 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
503 $t = $wgContLang->lc( $t );
506 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
507 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
509 $t = preg_replace( "/\\s+/", ' ', $t );
511 if ( $ns == NS_FILE
) {
512 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
518 * Make a prefixed DB key from a DB key and a namespace index
520 * @param int $ns numerical representation of the namespace
521 * @param string $title the DB key form the title
522 * @param string $fragment The link fragment (after the "#")
523 * @param string $interwiki The interwiki prefix
524 * @return String the prefixed form of the title
526 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
529 $namespace = $wgContLang->getNsText( $ns );
530 $name = $namespace == '' ?
$title : "$namespace:$title";
531 if ( strval( $interwiki ) != '' ) {
532 $name = "$interwiki:$name";
534 if ( strval( $fragment ) != '' ) {
535 $name .= '#' . $fragment;
541 * Escape a text fragment, say from a link, for a URL
543 * @param string $fragment containing a URL or link fragment (after the "#")
544 * @return String: escaped string
546 static function escapeFragmentForURL( $fragment ) {
547 # Note that we don't urlencode the fragment. urlencoded Unicode
548 # fragments appear not to work in IE (at least up to 7) or in at least
549 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
550 # to care if they aren't encoded.
551 return Sanitizer
::escapeId( $fragment, 'noninitial' );
555 * Callback for usort() to do title sorts by (namespace, title)
560 * @return Integer: result of string comparison, or namespace comparison
562 public static function compare( $a, $b ) {
563 if ( $a->getNamespace() == $b->getNamespace() ) {
564 return strcmp( $a->getText(), $b->getText() );
566 return $a->getNamespace() - $b->getNamespace();
571 * Determine whether the object refers to a page within
574 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
576 public function isLocal() {
577 if ( $this->mInterwiki
!= '' ) {
578 $iw = Interwiki
::fetch( $this->mInterwiki
);
580 return $iw->isLocal();
587 * Is this Title interwiki?
591 public function isExternal() {
592 return ( $this->mInterwiki
!= '' );
596 * Get the interwiki prefix (or null string)
598 * @return String Interwiki prefix
600 public function getInterwiki() {
601 return $this->mInterwiki
;
605 * Determine whether the object refers to a page within
606 * this project and is transcludable.
608 * @return Bool TRUE if this is transcludable
610 public function isTrans() {
611 if ( $this->mInterwiki
== '' ) {
615 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
619 * Returns the DB name of the distant wiki which owns the object.
621 * @return String the DB name
623 public function getTransWikiID() {
624 if ( $this->mInterwiki
== '' ) {
628 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
632 * Get the text form (spaces not underscores) of the main part
634 * @return String Main part of the title
636 public function getText() {
637 return $this->mTextform
;
641 * Get the URL-encoded form of the main part
643 * @return String Main part of the title, URL-encoded
645 public function getPartialURL() {
646 return $this->mUrlform
;
650 * Get the main part with underscores
652 * @return String: Main part of the title, with underscores
654 public function getDBkey() {
655 return $this->mDbkeyform
;
659 * Get the DB key with the initial letter case as specified by the user
661 * @return String DB key
663 function getUserCaseDBKey() {
664 return $this->mUserCaseDBKey
;
668 * Get the namespace index, i.e. one of the NS_xxxx constants.
670 * @return Integer: Namespace index
672 public function getNamespace() {
673 return $this->mNamespace
;
677 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
679 * @throws MWException
680 * @return String: Content model id
682 public function getContentModel() {
683 if ( !$this->mContentModel
) {
684 $linkCache = LinkCache
::singleton();
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 string $name 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 int $ns 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 equivalence
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 * accidentally 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 functions 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 string $fragment 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 string $name 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 string $text 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
1300 * @deprecated since 1.19
1302 public function getEscapedText() {
1303 wfDeprecated( __METHOD__
, '1.19' );
1304 return htmlspecialchars( $this->getPrefixedText() );
1308 * Get a URL-encoded form of the subpage text
1310 * @return String URL-encoded subpage name
1312 public function getSubpageUrlForm() {
1313 $text = $this->getSubpageText();
1314 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1319 * Get a URL-encoded title (not an actual URL) including interwiki
1321 * @return String the URL-encoded form
1323 public function getPrefixedURL() {
1324 $s = $this->prefix( $this->mDbkeyform
);
1325 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1330 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1331 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1332 * second argument named variant. This was deprecated in favor
1333 * of passing an array of option with a "variant" key
1334 * Once $query2 is removed for good, this helper can be dropped
1335 * and the wfArrayToCgi moved to getLocalURL();
1337 * @since 1.19 (r105919)
1339 * @param $query2 bool
1342 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1343 if( $query2 !== false ) {
1344 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1345 "method called with a second parameter is deprecated. Add your " .
1346 "parameter to an array passed as the first parameter.", "1.19" );
1348 if ( is_array( $query ) ) {
1349 $query = wfArrayToCgi( $query );
1352 if ( is_string( $query2 ) ) {
1353 // $query2 is a string, we will consider this to be
1354 // a deprecated $variant argument and add it to the query
1355 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1357 $query2 = wfArrayToCgi( $query2 );
1359 // If we have $query content add a & to it first
1363 // Now append the queries together
1370 * Get a real URL referring to this title, with interwiki link and
1373 * See getLocalURL for the arguments.
1375 * @see self::getLocalURL
1378 * @param $query2 bool
1379 * @param $proto Protocol type to use in URL
1380 * @return String the URL
1382 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1383 $query = self
::fixUrlQueryArgs( $query, $query2 );
1385 # Hand off all the decisions on urls to getLocalURL
1386 $url = $this->getLocalURL( $query );
1388 # Expand the url to make it a full url. Note that getLocalURL has the
1389 # potential to output full urls for a variety of reasons, so we use
1390 # wfExpandUrl instead of simply prepending $wgServer
1391 $url = wfExpandUrl( $url, $proto );
1393 # Finally, add the fragment.
1394 $url .= $this->getFragmentForURL();
1396 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1401 * Get a URL with no fragment or server name. If this page is generated
1402 * with action=render, $wgServer is prepended.
1404 * @param string|array $query an optional query string,
1405 * not used for interwiki links. Can be specified as an associative array as well,
1406 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1407 * Some query patterns will trigger various shorturl path replacements.
1408 * @param $query2 Mixed: An optional secondary query array. This one MUST
1409 * be an array. If a string is passed it will be interpreted as a deprecated
1410 * variant argument and urlencoded into a variant= argument.
1411 * This second query argument will be added to the $query
1412 * The second parameter is deprecated since 1.19. Pass it as a key,value
1413 * pair in the first parameter array instead.
1415 * @return String the URL
1417 public function getLocalURL( $query = '', $query2 = false ) {
1418 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1420 $query = self
::fixUrlQueryArgs( $query, $query2 );
1422 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1424 $namespace = $this->getNsText();
1425 if ( $namespace != '' ) {
1426 # Can this actually happen? Interwikis shouldn't be parsed.
1427 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1430 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1431 $url = wfAppendQuery( $url, $query );
1433 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1434 if ( $query == '' ) {
1435 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1436 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1438 global $wgVariantArticlePath, $wgActionPaths;
1442 if ( !empty( $wgActionPaths ) &&
1443 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1445 $action = urldecode( $matches[2] );
1446 if ( isset( $wgActionPaths[$action] ) ) {
1447 $query = $matches[1];
1448 if ( isset( $matches[4] ) ) {
1449 $query .= $matches[4];
1451 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1452 if ( $query != '' ) {
1453 $url = wfAppendQuery( $url, $query );
1458 if ( $url === false &&
1459 $wgVariantArticlePath &&
1460 $this->getPageLanguage()->hasVariants() &&
1461 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1463 $variant = urldecode( $matches[1] );
1464 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1465 // Only do the variant replacement if the given variant is a valid
1466 // variant for the page's language.
1467 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1468 $url = str_replace( '$1', $dbkey, $url );
1472 if ( $url === false ) {
1473 if ( $query == '-' ) {
1476 $url = "{$wgScript}?title={$dbkey}&{$query}";
1480 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1482 // @todo FIXME: This causes breakage in various places when we
1483 // actually expected a local URL and end up with dupe prefixes.
1484 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1485 $url = $wgServer . $url;
1488 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1493 * Get a URL that's the simplest URL that will be valid to link, locally,
1494 * to the current Title. It includes the fragment, but does not include
1495 * the server unless action=render is used (or the link is external). If
1496 * there's a fragment but the prefixed text is empty, we just return a link
1499 * The result obviously should not be URL-escaped, but does need to be
1500 * HTML-escaped if it's being output in HTML.
1502 * See getLocalURL for the arguments.
1505 * @param $query2 bool
1506 * @param $proto Protocol to use; setting this will cause a full URL to be used
1507 * @see self::getLocalURL
1508 * @return String the URL
1510 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1511 wfProfileIn( __METHOD__
);
1512 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1513 $ret = $this->getFullURL( $query, $query2, $proto );
1514 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1515 $ret = $this->getFragmentForURL();
1517 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1519 wfProfileOut( __METHOD__
);
1524 * Get an HTML-escaped version of the URL form, suitable for
1525 * using in a link, without a server name or fragment
1527 * See getLocalURL for the arguments.
1529 * @see self::getLocalURL
1530 * @param $query string
1531 * @param $query2 bool|string
1532 * @return String the URL
1533 * @deprecated since 1.19
1535 public function escapeLocalURL( $query = '', $query2 = false ) {
1536 wfDeprecated( __METHOD__
, '1.19' );
1537 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1541 * Get an HTML-escaped version of the URL form, suitable for
1542 * using in a link, including the server name and fragment
1544 * See getLocalURL for the arguments.
1546 * @see self::getLocalURL
1547 * @return String the URL
1548 * @deprecated since 1.19
1550 public function escapeFullURL( $query = '', $query2 = false ) {
1551 wfDeprecated( __METHOD__
, '1.19' );
1552 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1556 * Get the URL form for an internal link.
1557 * - Used in various Squid-related code, in case we have a different
1558 * internal hostname for the server from the exposed one.
1560 * This uses $wgInternalServer to qualify the path, or $wgServer
1561 * if $wgInternalServer is not set. If the server variable used is
1562 * protocol-relative, the URL will be expanded to http://
1564 * See getLocalURL for the arguments.
1566 * @see self::getLocalURL
1567 * @return String the URL
1569 public function getInternalURL( $query = '', $query2 = false ) {
1570 global $wgInternalServer, $wgServer;
1571 $query = self
::fixUrlQueryArgs( $query, $query2 );
1572 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1573 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1574 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1579 * Get the URL for a canonical link, for use in things like IRC and
1580 * e-mail notifications. Uses $wgCanonicalServer and the
1581 * GetCanonicalURL hook.
1583 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1585 * See getLocalURL for the arguments.
1587 * @see self::getLocalURL
1588 * @return string The URL
1591 public function getCanonicalURL( $query = '', $query2 = false ) {
1592 $query = self
::fixUrlQueryArgs( $query, $query2 );
1593 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1594 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1599 * HTML-escaped version of getCanonicalURL()
1601 * See getLocalURL for the arguments.
1603 * @see self::getLocalURL
1606 * @deprecated since 1.19
1608 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1609 wfDeprecated( __METHOD__
, '1.19' );
1610 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1614 * Get the edit URL for this Title
1616 * @return String the URL, or a null string if this is an
1619 public function getEditURL() {
1620 if ( $this->mInterwiki
!= '' ) {
1623 $s = $this->getLocalURL( 'action=edit' );
1629 * Is $wgUser watching this page?
1631 * @deprecated in 1.20; use User::isWatched() instead.
1634 public function userIsWatching() {
1637 if ( is_null( $this->mWatched
) ) {
1638 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1639 $this->mWatched
= false;
1641 $this->mWatched
= $wgUser->isWatched( $this );
1644 return $this->mWatched
;
1648 * Can $wgUser read this page?
1650 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1652 * @todo fold these checks into userCan()
1654 public function userCanRead() {
1655 wfDeprecated( __METHOD__
, '1.19' );
1656 return $this->userCan( 'read' );
1660 * Can $user perform $action on this page?
1661 * This skips potentially expensive cascading permission checks
1662 * as well as avoids expensive error formatting
1664 * Suitable for use for nonessential UI controls in common cases, but
1665 * _not_ for functional access control.
1667 * May provide false positives, but should never provide a false negative.
1669 * @param string $action action that permission needs to be checked for
1670 * @param $user User to check (since 1.19); $wgUser will be used if not
1674 public function quickUserCan( $action, $user = null ) {
1675 return $this->userCan( $action, $user, false );
1679 * Can $user perform $action on this page?
1681 * @param string $action action that permission needs to be checked for
1682 * @param $user User to check (since 1.19); $wgUser will be used if not
1684 * @param bool $doExpensiveQueries Set this to false to avoid doing
1685 * unnecessary queries.
1688 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1689 if ( !$user instanceof User
) {
1693 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1697 * Can $user perform $action on this page?
1699 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1701 * @param string $action action that permission needs to be checked for
1702 * @param $user User to check
1703 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1704 * queries by skipping checks for cascading protections and user blocks.
1705 * @param array $ignoreErrors of Strings Set this to a list of message keys
1706 * whose corresponding errors may be ignored.
1707 * @return Array of arguments to wfMessage to explain permissions problems.
1709 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1710 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1712 // Remove the errors being ignored.
1713 foreach ( $errors as $index => $error ) {
1714 $error_key = is_array( $error ) ?
$error[0] : $error;
1716 if ( in_array( $error_key, $ignoreErrors ) ) {
1717 unset( $errors[$index] );
1725 * Permissions checks that fail most often, and which are easiest to test.
1727 * @param string $action the action to check
1728 * @param $user User user to check
1729 * @param array $errors list of current errors
1730 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1731 * @param $short Boolean short circuit on first error
1733 * @return Array list of errors
1735 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1736 if ( $action == 'create' ) {
1738 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1739 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1741 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1743 } elseif ( $action == 'move' ) {
1744 if ( !$user->isAllowed( 'move-rootuserpages' )
1745 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1746 // Show user page-specific message only if the user can move other pages
1747 $errors[] = array( 'cant-move-user-page' );
1750 // Check if user is allowed to move files if it's a file
1751 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1752 $errors[] = array( 'movenotallowedfile' );
1755 if ( !$user->isAllowed( 'move' ) ) {
1756 // User can't move anything
1757 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1758 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1759 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1760 // custom message if logged-in users without any special rights can move
1761 $errors[] = array( 'movenologintext' );
1763 $errors[] = array( 'movenotallowed' );
1766 } elseif ( $action == 'move-target' ) {
1767 if ( !$user->isAllowed( 'move' ) ) {
1768 // User can't move anything
1769 $errors[] = array( 'movenotallowed' );
1770 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1771 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1772 // Show user page-specific message only if the user can move other pages
1773 $errors[] = array( 'cant-move-to-user-page' );
1775 } elseif ( !$user->isAllowed( $action ) ) {
1776 $errors[] = $this->missingPermissionError( $action, $short );
1783 * Add the resulting error code to the errors array
1785 * @param array $errors list of current errors
1786 * @param $result Mixed result of errors
1788 * @return Array list of errors
1790 private function resultToError( $errors, $result ) {
1791 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1792 // A single array representing an error
1793 $errors[] = $result;
1794 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1795 // A nested array representing multiple errors
1796 $errors = array_merge( $errors, $result );
1797 } elseif ( $result !== '' && is_string( $result ) ) {
1798 // A string representing a message-id
1799 $errors[] = array( $result );
1800 } elseif ( $result === false ) {
1801 // a generic "We don't want them to do that"
1802 $errors[] = array( 'badaccess-group0' );
1808 * Check various permission hooks
1810 * @param string $action the action to check
1811 * @param $user User user to check
1812 * @param array $errors list of current errors
1813 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1814 * @param $short Boolean short circuit on first error
1816 * @return Array list of errors
1818 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1819 // Use getUserPermissionsErrors instead
1821 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1822 return $result ?
array() : array( array( 'badaccess-group0' ) );
1824 // Check getUserPermissionsErrors hook
1825 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1826 $errors = $this->resultToError( $errors, $result );
1828 // Check getUserPermissionsErrorsExpensive hook
1831 && !( $short && count( $errors ) > 0 )
1832 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
1834 $errors = $this->resultToError( $errors, $result );
1841 * Check permissions on special pages & namespaces
1843 * @param string $action the action to check
1844 * @param $user User user to check
1845 * @param array $errors list of current errors
1846 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1847 * @param $short Boolean short circuit on first error
1849 * @return Array list of errors
1851 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1852 # Only 'createaccount' can be performed on special pages,
1853 # which don't actually exist in the DB.
1854 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
1855 $errors[] = array( 'ns-specialprotected' );
1858 # Check $wgNamespaceProtection for restricted namespaces
1859 if ( $this->isNamespaceProtected( $user ) ) {
1860 $ns = $this->mNamespace
== NS_MAIN ?
1861 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1862 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1863 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1870 * Check CSS/JS sub-page permissions
1872 * @param string $action the action to check
1873 * @param $user User user to check
1874 * @param array $errors list of current errors
1875 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1876 * @param $short Boolean short circuit on first error
1878 * @return Array list of errors
1880 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1881 # Protect css/js subpages of user pages
1882 # XXX: this might be better using restrictions
1883 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1884 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1885 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1886 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1887 $errors[] = array( 'customcssprotected' );
1888 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1889 $errors[] = array( 'customjsprotected' );
1897 * Check against page_restrictions table requirements on this
1898 * page. The user must possess all required rights for this
1901 * @param string $action the action to check
1902 * @param $user User user to check
1903 * @param array $errors list of current errors
1904 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1905 * @param $short Boolean short circuit on first error
1907 * @return Array list of errors
1909 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1910 foreach ( $this->getRestrictions( $action ) as $right ) {
1911 // Backwards compatibility, rewrite sysop -> protect
1912 if ( $right == 'sysop' ) {
1915 if ( $right != '' && !$user->isAllowed( $right ) ) {
1916 // Users with 'editprotected' permission can edit protected pages
1917 // without cascading option turned on.
1918 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1919 ||
$this->mCascadeRestriction
)
1921 $errors[] = array( 'protectedpagetext', $right );
1930 * Check restrictions on cascading pages.
1932 * @param string $action the action to check
1933 * @param $user User to check
1934 * @param array $errors list of current errors
1935 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1936 * @param $short Boolean short circuit on first error
1938 * @return Array list of errors
1940 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1941 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1942 # We /could/ use the protection level on the source page, but it's
1943 # fairly ugly as we have to establish a precedence hierarchy for pages
1944 # included by multiple cascade-protected pages. So just restrict
1945 # it to people with 'protect' permission, as they could remove the
1946 # protection anyway.
1947 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1948 # Cascading protection depends on more than this page...
1949 # Several cascading protected pages may include this page...
1950 # Check each cascading level
1951 # This is only for protection restrictions, not for all actions
1952 if ( isset( $restrictions[$action] ) ) {
1953 foreach ( $restrictions[$action] as $right ) {
1954 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1955 if ( $right != '' && !$user->isAllowed( $right ) ) {
1957 foreach ( $cascadingSources as $page )
1958 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1959 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1969 * Check action permissions not already checked in checkQuickPermissions
1971 * @param string $action the action to check
1972 * @param $user User to check
1973 * @param array $errors list of current errors
1974 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1975 * @param $short Boolean short circuit on first error
1977 * @return Array list of errors
1979 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1980 global $wgDeleteRevisionsLimit, $wgLang;
1982 if ( $action == 'protect' ) {
1983 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1984 // If they can't edit, they shouldn't protect.
1985 $errors[] = array( 'protect-cantedit' );
1987 } elseif ( $action == 'create' ) {
1988 $title_protection = $this->getTitleProtection();
1989 if( $title_protection ) {
1990 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1991 $title_protection['pt_create_perm'] = 'protect'; // B/C
1993 if( $title_protection['pt_create_perm'] == '' ||
1994 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1996 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1999 } elseif ( $action == 'move' ) {
2000 // Check for immobile pages
2001 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2002 // Specific message for this case
2003 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2004 } elseif ( !$this->isMovable() ) {
2005 // Less specific message for rarer cases
2006 $errors[] = array( 'immobile-source-page' );
2008 } elseif ( $action == 'move-target' ) {
2009 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2010 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2011 } elseif ( !$this->isMovable() ) {
2012 $errors[] = array( 'immobile-target-page' );
2014 } elseif ( $action == 'delete' ) {
2015 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2016 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
2018 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2025 * Check that the user isn't blocked from editing.
2027 * @param string $action the action to check
2028 * @param $user User to check
2029 * @param array $errors list of current errors
2030 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2031 * @param $short Boolean short circuit on first error
2033 * @return Array list of errors
2035 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2036 // Account creation blocks handled at userlogin.
2037 // Unblocking handled in SpecialUnblock
2038 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2042 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
2044 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2045 $errors[] = array( 'confirmedittext' );
2048 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2049 // Don't block the user from editing their own talk page unless they've been
2050 // explicitly blocked from that too.
2051 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2052 // @todo FIXME: Pass the relevant context into this function.
2053 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2060 * Check that the user is allowed to read this page.
2062 * @param string $action the action to check
2063 * @param $user User to check
2064 * @param array $errors list of current errors
2065 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2066 * @param $short Boolean short circuit on first error
2068 * @return Array list of errors
2070 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2071 global $wgWhitelistRead, $wgWhitelistReadRegexp, $wgRevokePermissions;
2072 static $useShortcut = null;
2074 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2075 if ( is_null( $useShortcut ) ) {
2076 $useShortcut = true;
2077 if ( !User
::groupHasPermission( '*', 'read' ) ) {
2078 # Not a public wiki, so no shortcut
2079 $useShortcut = false;
2080 } elseif ( !empty( $wgRevokePermissions ) ) {
2082 * Iterate through each group with permissions being revoked (key not included since we don't care
2083 * what the group name is), then check if the read permission is being revoked. If it is, then
2084 * we don't use the shortcut below since the user might not be able to read, even though anon
2085 * reading is allowed.
2087 foreach ( $wgRevokePermissions as $perms ) {
2088 if ( !empty( $perms['read'] ) ) {
2089 # We might be removing the read right from the user, so no shortcut
2090 $useShortcut = false;
2097 $whitelisted = false;
2098 if ( $useShortcut ) {
2099 # Shortcut for public wikis, allows skipping quite a bit of code
2100 $whitelisted = true;
2101 } elseif ( $user->isAllowed( 'read' ) ) {
2102 # If the user is allowed to read pages, he is allowed to read all pages
2103 $whitelisted = true;
2104 } elseif ( $this->isSpecial( 'Userlogin' )
2105 ||
$this->isSpecial( 'ChangePassword' )
2106 ||
$this->isSpecial( 'PasswordReset' )
2108 # Always grant access to the login page.
2109 # Even anons need to be able to log in.
2110 $whitelisted = true;
2111 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2112 # Time to check the whitelist
2113 # Only do these checks is there's something to check against
2114 $name = $this->getPrefixedText();
2115 $dbName = $this->getPrefixedDBkey();
2117 // Check for explicit whitelisting with and without underscores
2118 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2119 $whitelisted = true;
2120 } elseif ( $this->getNamespace() == NS_MAIN
) {
2121 # Old settings might have the title prefixed with
2122 # a colon for main-namespace pages
2123 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2124 $whitelisted = true;
2126 } elseif ( $this->isSpecialPage() ) {
2127 # If it's a special page, ditch the subpage bit and check again
2128 $name = $this->getDBkey();
2129 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2131 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2132 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2133 $whitelisted = true;
2139 if( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2140 $name = $this->getPrefixedText();
2141 // Check for regex whitelisting
2142 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2143 if ( preg_match( $listItem, $name ) ) {
2144 $whitelisted = true;
2150 if ( !$whitelisted ) {
2151 # If the title is not whitelisted, give extensions a chance to do so...
2152 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2153 if ( !$whitelisted ) {
2154 $errors[] = $this->missingPermissionError( $action, $short );
2162 * Get a description array when the user doesn't have the right to perform
2163 * $action (i.e. when User::isAllowed() returns false)
2165 * @param string $action the action to check
2166 * @param $short Boolean short circuit on first error
2167 * @return Array list of errors
2169 private function missingPermissionError( $action, $short ) {
2170 // We avoid expensive display logic for quickUserCan's and such
2172 return array( 'badaccess-group0' );
2175 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2176 User
::getGroupsWithPermission( $action ) );
2178 if ( count( $groups ) ) {
2182 $wgLang->commaList( $groups ),
2186 return array( 'badaccess-group0' );
2191 * Can $user perform $action on this page? This is an internal function,
2192 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2193 * checks on wfReadOnly() and blocks)
2195 * @param string $action action that permission needs to be checked for
2196 * @param $user User to check
2197 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2198 * @param bool $short Set this to true to stop after the first permission error.
2199 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2201 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2202 wfProfileIn( __METHOD__
);
2204 # Read has special handling
2205 if ( $action == 'read' ) {
2207 'checkPermissionHooks',
2208 'checkReadPermissions',
2212 'checkQuickPermissions',
2213 'checkPermissionHooks',
2214 'checkSpecialsAndNSPermissions',
2215 'checkCSSandJSPermissions',
2216 'checkPageRestrictions',
2217 'checkCascadingSourcesRestrictions',
2218 'checkActionPermissions',
2224 while( count( $checks ) > 0 &&
2225 !( $short && count( $errors ) > 0 ) ) {
2226 $method = array_shift( $checks );
2227 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2230 wfProfileOut( __METHOD__
);
2235 * Protect css subpages of user pages: can $wgUser edit
2238 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2241 public function userCanEditCssSubpage() {
2243 wfDeprecated( __METHOD__
, '1.19' );
2244 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2245 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2249 * Protect js subpages of user pages: can $wgUser edit
2252 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2255 public function userCanEditJsSubpage() {
2257 wfDeprecated( __METHOD__
, '1.19' );
2259 ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2260 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
)
2265 * Get a filtered list of all restriction types supported by this wiki.
2266 * @param bool $exists True to get all restriction types that apply to
2267 * titles that do exist, False for all restriction types that apply to
2268 * titles that do not exist
2271 public static function getFilteredRestrictionTypes( $exists = true ) {
2272 global $wgRestrictionTypes;
2273 $types = $wgRestrictionTypes;
2275 # Remove the create restriction for existing titles
2276 $types = array_diff( $types, array( 'create' ) );
2278 # Only the create and upload restrictions apply to non-existing titles
2279 $types = array_intersect( $types, array( 'create', 'upload' ) );
2285 * Returns restriction types for the current Title
2287 * @return array applicable restriction types
2289 public function getRestrictionTypes() {
2290 if ( $this->isSpecialPage() ) {
2294 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2296 if ( $this->getNamespace() != NS_FILE
) {
2297 # Remove the upload restriction for non-file titles
2298 $types = array_diff( $types, array( 'upload' ) );
2301 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2303 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2304 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2310 * Is this title subject to title protection?
2311 * Title protection is the one applied against creation of such title.
2313 * @return Mixed An associative array representing any existent title
2314 * protection, or false if there's none.
2316 private function getTitleProtection() {
2317 // Can't protect pages in special namespaces
2318 if ( $this->getNamespace() < 0 ) {
2322 // Can't protect pages that exist.
2323 if ( $this->exists() ) {
2327 if ( !isset( $this->mTitleProtection
) ) {
2328 $dbr = wfGetDB( DB_SLAVE
);
2329 $res = $dbr->select(
2331 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2332 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2336 // fetchRow returns false if there are no rows.
2337 $this->mTitleProtection
= $dbr->fetchRow( $res );
2339 return $this->mTitleProtection
;
2343 * Update the title protection status
2345 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2346 * @param $create_perm String Permission required for creation
2347 * @param string $reason Reason for protection
2348 * @param string $expiry Expiry timestamp
2349 * @return boolean true
2351 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2352 wfDeprecated( __METHOD__
, '1.19' );
2356 $limit = array( 'create' => $create_perm );
2357 $expiry = array( 'create' => $expiry );
2359 $page = WikiPage
::factory( $this );
2361 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2363 return $status->isOK();
2367 * Remove any title protection due to page existing
2369 public function deleteTitleProtection() {
2370 $dbw = wfGetDB( DB_MASTER
);
2374 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2377 $this->mTitleProtection
= false;
2381 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2383 * @param string $action Action to check (default: edit)
2386 public function isSemiProtected( $action = 'edit' ) {
2387 if ( $this->exists() ) {
2388 $restrictions = $this->getRestrictions( $action );
2389 if ( count( $restrictions ) > 0 ) {
2390 foreach ( $restrictions as $restriction ) {
2391 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2401 # If it doesn't exist, it can't be protected
2407 * Does the title correspond to a protected article?
2409 * @param string $action the action the page is protected from,
2410 * by default checks all actions.
2413 public function isProtected( $action = '' ) {
2414 global $wgRestrictionLevels;
2416 $restrictionTypes = $this->getRestrictionTypes();
2418 # Special pages have inherent protection
2419 if( $this->isSpecialPage() ) {
2423 # Check regular protection levels
2424 foreach ( $restrictionTypes as $type ) {
2425 if ( $action == $type ||
$action == '' ) {
2426 $r = $this->getRestrictions( $type );
2427 foreach ( $wgRestrictionLevels as $level ) {
2428 if ( in_array( $level, $r ) && $level != '' ) {
2439 * Determines if $user is unable to edit this page because it has been protected
2440 * by $wgNamespaceProtection.
2442 * @param $user User object to check permissions
2445 public function isNamespaceProtected( User
$user ) {
2446 global $wgNamespaceProtection;
2448 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2449 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2450 if ( $right != '' && !$user->isAllowed( $right ) ) {
2459 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2461 * @return Bool If the page is subject to cascading restrictions.
2463 public function isCascadeProtected() {
2464 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2465 return ( $sources > 0 );
2469 * Cascading protection: Get the source of any cascading restrictions on this page.
2471 * @param bool $getPages Whether or not to retrieve the actual pages
2472 * that the restrictions have come from.
2473 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2474 * have come, false for none, or true if such restrictions exist, but $getPages
2475 * was not set. The restriction array is an array of each type, each of which
2476 * contains a array of unique groups.
2478 public function getCascadeProtectionSources( $getPages = true ) {
2480 $pagerestrictions = array();
2482 if ( isset( $this->mCascadeSources
) && $getPages ) {
2483 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2484 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2485 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2488 wfProfileIn( __METHOD__
);
2490 $dbr = wfGetDB( DB_SLAVE
);
2492 if ( $this->getNamespace() == NS_FILE
) {
2493 $tables = array( 'imagelinks', 'page_restrictions' );
2494 $where_clauses = array(
2495 'il_to' => $this->getDBkey(),
2500 $tables = array( 'templatelinks', 'page_restrictions' );
2501 $where_clauses = array(
2502 'tl_namespace' => $this->getNamespace(),
2503 'tl_title' => $this->getDBkey(),
2510 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2511 'pr_expiry', 'pr_type', 'pr_level' );
2512 $where_clauses[] = 'page_id=pr_page';
2515 $cols = array( 'pr_expiry' );
2518 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2520 $sources = $getPages ?
array() : false;
2521 $now = wfTimestampNow();
2522 $purgeExpired = false;
2524 foreach ( $res as $row ) {
2525 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2526 if ( $expiry > $now ) {
2528 $page_id = $row->pr_page
;
2529 $page_ns = $row->page_namespace
;
2530 $page_title = $row->page_title
;
2531 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2532 # Add groups needed for each restriction type if its not already there
2533 # Make sure this restriction type still exists
2535 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2536 $pagerestrictions[$row->pr_type
] = array();
2540 isset( $pagerestrictions[$row->pr_type
] )
2541 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2543 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2549 // Trigger lazy purge of expired restrictions from the db
2550 $purgeExpired = true;
2553 if ( $purgeExpired ) {
2554 Title
::purgeExpiredRestrictions();
2558 $this->mCascadeSources
= $sources;
2559 $this->mCascadingRestrictions
= $pagerestrictions;
2561 $this->mHasCascadingRestrictions
= $sources;
2564 wfProfileOut( __METHOD__
);
2565 return array( $sources, $pagerestrictions );
2569 * Accessor/initialisation for mRestrictions
2571 * @param string $action action that permission needs to be checked for
2572 * @return Array of Strings the array of groups allowed to edit this article
2574 public function getRestrictions( $action ) {
2575 if ( !$this->mRestrictionsLoaded
) {
2576 $this->loadRestrictions();
2578 return isset( $this->mRestrictions
[$action] )
2579 ?
$this->mRestrictions
[$action]
2584 * Get the expiry time for the restriction against a given action
2587 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2588 * or not protected at all, or false if the action is not recognised.
2590 public function getRestrictionExpiry( $action ) {
2591 if ( !$this->mRestrictionsLoaded
) {
2592 $this->loadRestrictions();
2594 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2598 * Returns cascading restrictions for the current article
2602 function areRestrictionsCascading() {
2603 if ( !$this->mRestrictionsLoaded
) {
2604 $this->loadRestrictions();
2607 return $this->mCascadeRestriction
;
2611 * Loads a string into mRestrictions array
2613 * @param $res Resource restrictions as an SQL result.
2614 * @param string $oldFashionedRestrictions comma-separated list of page
2615 * restrictions from page table (pre 1.10)
2617 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2620 foreach ( $res as $row ) {
2624 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2628 * Compiles list of active page restrictions from both page table (pre 1.10)
2629 * and page_restrictions table for this existing page.
2630 * Public for usage by LiquidThreads.
2632 * @param array $rows of db result objects
2633 * @param string $oldFashionedRestrictions comma-separated list of page
2634 * restrictions from page table (pre 1.10)
2636 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2638 $dbr = wfGetDB( DB_SLAVE
);
2640 $restrictionTypes = $this->getRestrictionTypes();
2642 foreach ( $restrictionTypes as $type ) {
2643 $this->mRestrictions
[$type] = array();
2644 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2647 $this->mCascadeRestriction
= false;
2649 # Backwards-compatibility: also load the restrictions from the page record (old format).
2651 if ( $oldFashionedRestrictions === null ) {
2652 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2653 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2656 if ( $oldFashionedRestrictions != '' ) {
2658 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2659 $temp = explode( '=', trim( $restrict ) );
2660 if ( count( $temp ) == 1 ) {
2661 // old old format should be treated as edit/move restriction
2662 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2663 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2665 $restriction = trim( $temp[1] );
2666 if( $restriction != '' ) { //some old entries are empty
2667 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2672 $this->mOldRestrictions
= true;
2676 if ( count( $rows ) ) {
2677 # Current system - load second to make them override.
2678 $now = wfTimestampNow();
2679 $purgeExpired = false;
2681 # Cycle through all the restrictions.
2682 foreach ( $rows as $row ) {
2684 // Don't take care of restrictions types that aren't allowed
2685 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2688 // This code should be refactored, now that it's being used more generally,
2689 // But I don't really see any harm in leaving it in Block for now -werdna
2690 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2692 // Only apply the restrictions if they haven't expired!
2693 if ( !$expiry ||
$expiry > $now ) {
2694 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2695 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2697 $this->mCascadeRestriction |
= $row->pr_cascade
;
2699 // Trigger a lazy purge of expired restrictions
2700 $purgeExpired = true;
2704 if ( $purgeExpired ) {
2705 Title
::purgeExpiredRestrictions();
2709 $this->mRestrictionsLoaded
= true;
2713 * Load restrictions from the page_restrictions table
2715 * @param string $oldFashionedRestrictions comma-separated list of page
2716 * restrictions from page table (pre 1.10)
2718 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2720 if ( !$this->mRestrictionsLoaded
) {
2721 if ( $this->exists() ) {
2722 $dbr = wfGetDB( DB_SLAVE
);
2724 $res = $dbr->select(
2725 'page_restrictions',
2726 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2727 array( 'pr_page' => $this->getArticleID() ),
2731 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2733 $title_protection = $this->getTitleProtection();
2735 if ( $title_protection ) {
2736 $now = wfTimestampNow();
2737 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2739 if ( !$expiry ||
$expiry > $now ) {
2740 // Apply the restrictions
2741 $this->mRestrictionsExpiry
['create'] = $expiry;
2742 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2743 } else { // Get rid of the old restrictions
2744 Title
::purgeExpiredRestrictions();
2745 $this->mTitleProtection
= false;
2748 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2750 $this->mRestrictionsLoaded
= true;
2756 * Flush the protection cache in this object and force reload from the database.
2757 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2759 public function flushRestrictions() {
2760 $this->mRestrictionsLoaded
= false;
2761 $this->mTitleProtection
= null;
2765 * Purge expired restrictions from the page_restrictions table
2767 static function purgeExpiredRestrictions() {
2768 if ( wfReadOnly() ) {
2772 $dbw = wfGetDB( DB_MASTER
);
2774 'page_restrictions',
2775 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2781 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2787 * Does this have subpages? (Warning, usually requires an extra DB query.)
2791 public function hasSubpages() {
2792 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2797 # We dynamically add a member variable for the purpose of this method
2798 # alone to cache the result. There's no point in having it hanging
2799 # around uninitialized in every Title object; therefore we only add it
2800 # if needed and don't declare it statically.
2801 if ( isset( $this->mHasSubpages
) ) {
2802 return $this->mHasSubpages
;
2805 $subpages = $this->getSubpages( 1 );
2806 if ( $subpages instanceof TitleArray
) {
2807 return $this->mHasSubpages
= (bool)$subpages->count();
2809 return $this->mHasSubpages
= false;
2813 * Get all subpages of this page.
2815 * @param int $limit maximum number of subpages to fetch; -1 for no limit
2816 * @return mixed TitleArray, or empty array if this page's namespace
2817 * doesn't allow subpages
2819 public function getSubpages( $limit = -1 ) {
2820 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2824 $dbr = wfGetDB( DB_SLAVE
);
2825 $conds['page_namespace'] = $this->getNamespace();
2826 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2828 if ( $limit > -1 ) {
2829 $options['LIMIT'] = $limit;
2831 return $this->mSubpages
= TitleArray
::newFromResult(
2832 $dbr->select( 'page',
2833 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2842 * Is there a version of this page in the deletion archive?
2844 * @return Int the number of archived revisions
2846 public function isDeleted() {
2847 if ( $this->getNamespace() < 0 ) {
2850 $dbr = wfGetDB( DB_SLAVE
);
2852 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2853 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2856 if ( $this->getNamespace() == NS_FILE
) {
2857 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2858 array( 'fa_name' => $this->getDBkey() ),
2867 * Is there a version of this page in the deletion archive?
2871 public function isDeletedQuick() {
2872 if ( $this->getNamespace() < 0 ) {
2875 $dbr = wfGetDB( DB_SLAVE
);
2876 $deleted = (bool)$dbr->selectField( 'archive', '1',
2877 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2880 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2881 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2882 array( 'fa_name' => $this->getDBkey() ),
2890 * Get the article ID for this Title from the link cache,
2891 * adding it if necessary
2893 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select
2895 * @return Int the ID
2897 public function getArticleID( $flags = 0 ) {
2898 if ( $this->getNamespace() < 0 ) {
2899 return $this->mArticleID
= 0;
2901 $linkCache = LinkCache
::singleton();
2902 if ( $flags & self
::GAID_FOR_UPDATE
) {
2903 $oldUpdate = $linkCache->forUpdate( true );
2904 $linkCache->clearLink( $this );
2905 $this->mArticleID
= $linkCache->addLinkObj( $this );
2906 $linkCache->forUpdate( $oldUpdate );
2908 if ( -1 == $this->mArticleID
) {
2909 $this->mArticleID
= $linkCache->addLinkObj( $this );
2912 return $this->mArticleID
;
2916 * Is this an article that is a redirect page?
2917 * Uses link cache, adding it if necessary
2919 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
2922 public function isRedirect( $flags = 0 ) {
2923 if ( !is_null( $this->mRedirect
) ) {
2924 return $this->mRedirect
;
2926 # Calling getArticleID() loads the field from cache as needed
2927 if ( !$this->getArticleID( $flags ) ) {
2928 return $this->mRedirect
= false;
2931 $linkCache = LinkCache
::singleton();
2932 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2933 if ( $cached === null ) {
2934 // TODO: check the assumption that the cache actually knows about this title
2935 // and handle this, such as get the title from the database.
2936 // See https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2937 wfDebug( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2938 wfDebug( wfBacktrace() );
2941 $this->mRedirect
= (bool)$cached;
2943 return $this->mRedirect
;
2947 * What is the length of this page?
2948 * Uses link cache, adding it if necessary
2950 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
2953 public function getLength( $flags = 0 ) {
2954 if ( $this->mLength
!= -1 ) {
2955 return $this->mLength
;
2957 # Calling getArticleID() loads the field from cache as needed
2958 if ( !$this->getArticleID( $flags ) ) {
2959 return $this->mLength
= 0;
2961 $linkCache = LinkCache
::singleton();
2962 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2963 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2964 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2965 # as a stop gap, perhaps log this, but don't throw an exception?
2966 wfDebug( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2967 wfDebug( wfBacktrace() );
2970 $this->mLength
= intval( $cached );
2972 return $this->mLength
;
2976 * What is the page_latest field for this page?
2978 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
2979 * @throws MWException
2980 * @return Int or 0 if the page doesn't exist
2982 public function getLatestRevID( $flags = 0 ) {
2983 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
2984 return intval( $this->mLatestID
);
2986 # Calling getArticleID() loads the field from cache as needed
2987 if ( !$this->getArticleID( $flags ) ) {
2988 return $this->mLatestID
= 0;
2990 $linkCache = LinkCache
::singleton();
2991 $linkCache->addLinkObj( $this );
2992 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2993 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2994 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2995 # as a stop gap, perhaps log this, but don't throw an exception?
2996 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2999 $this->mLatestID
= intval( $cached );
3001 return $this->mLatestID
;
3005 * This clears some fields in this object, and clears any associated
3006 * keys in the "bad links" section of the link cache.
3008 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3009 * loading of the new page_id. It's also called from
3010 * WikiPage::doDeleteArticleReal()
3012 * @param int $newid the new Article ID
3014 public function resetArticleID( $newid ) {
3015 $linkCache = LinkCache
::singleton();
3016 $linkCache->clearLink( $this );
3018 if ( $newid === false ) {
3019 $this->mArticleID
= -1;
3021 $this->mArticleID
= intval( $newid );
3023 $this->mRestrictionsLoaded
= false;
3024 $this->mRestrictions
= array();
3025 $this->mRedirect
= null;
3026 $this->mLength
= -1;
3027 $this->mLatestID
= false;
3028 $this->mContentModel
= false;
3029 $this->mEstimateRevisions
= null;
3033 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3035 * @param string $text containing title to capitalize
3036 * @param int $ns namespace index, defaults to NS_MAIN
3037 * @return String containing capitalized title
3039 public static function capitalize( $text, $ns = NS_MAIN
) {
3042 if ( MWNamespace
::isCapitalized( $ns ) ) {
3043 return $wgContLang->ucfirst( $text );
3050 * Secure and split - main initialisation function for this object
3052 * Assumes that mDbkeyform has been set, and is urldecoded
3053 * and uses underscores, but not otherwise munged. This function
3054 * removes illegal characters, splits off the interwiki and
3055 * namespace prefixes, sets the other forms, and canonicalizes
3058 * @return Bool true on success
3060 private function secureAndSplit() {
3061 global $wgContLang, $wgLocalInterwiki;
3064 $this->mInterwiki
= $this->mFragment
= '';
3065 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3067 $dbkey = $this->mDbkeyform
;
3069 # Strip Unicode bidi override characters.
3070 # Sometimes they slip into cut-n-pasted page titles, where the
3071 # override chars get included in list displays.
3072 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
3074 # Clean up whitespace
3075 # Note: use of the /u option on preg_replace here will cause
3076 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3077 # conveniently disabling them.
3078 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3079 $dbkey = trim( $dbkey, '_' );
3081 if ( $dbkey == '' ) {
3085 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3086 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3090 $this->mDbkeyform
= $dbkey;
3092 # Initial colon indicates main namespace rather than specified default
3093 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3094 if ( ':' == $dbkey[0] ) {
3095 $this->mNamespace
= NS_MAIN
;
3096 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3097 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3100 # Namespace or interwiki prefix
3102 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3105 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3107 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3108 # Ordinary namespace
3110 $this->mNamespace
= $ns;
3111 # For Talk:X pages, check if X has a "namespace" prefix
3112 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3113 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3114 # Disallow Talk:File:x type titles...
3116 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3117 # Disallow Talk:Interwiki:x type titles...
3121 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3122 if ( !$firstPass ) {
3123 # Can't make a local interwiki link to an interwiki link.
3124 # That's just crazy!
3130 $this->mInterwiki
= $wgContLang->lc( $p );
3132 # Redundant interwiki prefix to the local wiki
3133 if ( $wgLocalInterwiki !== false
3134 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3136 if ( $dbkey == '' ) {
3137 # Can't have an empty self-link
3140 $this->mInterwiki
= '';
3142 # Do another namespace split...
3146 # If there's an initial colon after the interwiki, that also
3147 # resets the default namespace
3148 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3149 $this->mNamespace
= NS_MAIN
;
3150 $dbkey = substr( $dbkey, 1 );
3153 # If there's no recognized interwiki or namespace,
3154 # then let the colon expression be part of the title.
3159 # We already know that some pages won't be in the database!
3160 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3161 $this->mArticleID
= 0;
3163 $fragment = strstr( $dbkey, '#' );
3164 if ( false !== $fragment ) {
3165 $this->setFragment( $fragment );
3166 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3167 # remove whitespace again: prevents "Foo_bar_#"
3168 # becoming "Foo_bar_"
3169 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3172 # Reject illegal characters.
3173 $rxTc = self
::getTitleInvalidRegex();
3174 if ( preg_match( $rxTc, $dbkey ) ) {
3178 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3179 # reachable due to the way web browsers deal with 'relative' URLs.
3180 # Also, they conflict with subpage syntax. Forbid them explicitly.
3182 strpos( $dbkey, '.' ) !== false &&
3184 $dbkey === '.' ||
$dbkey === '..' ||
3185 strpos( $dbkey, './' ) === 0 ||
3186 strpos( $dbkey, '../' ) === 0 ||
3187 strpos( $dbkey, '/./' ) !== false ||
3188 strpos( $dbkey, '/../' ) !== false ||
3189 substr( $dbkey, -2 ) == '/.' ||
3190 substr( $dbkey, -3 ) == '/..'
3196 # Magic tilde sequences? Nu-uh!
3197 if ( strpos( $dbkey, '~~~' ) !== false ) {
3201 # Limit the size of titles to 255 bytes. This is typically the size of the
3202 # underlying database field. We make an exception for special pages, which
3203 # don't need to be stored in the database, and may edge over 255 bytes due
3204 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3206 ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 )
3207 ||
strlen( $dbkey ) > 512
3212 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3213 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3214 # other site might be case-sensitive.
3215 $this->mUserCaseDBKey
= $dbkey;
3216 if ( $this->mInterwiki
== '' ) {
3217 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3220 # Can't make a link to a namespace alone... "empty" local links can only be
3221 # self-links with a fragment identifier.
3222 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3226 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3227 // IP names are not allowed for accounts, and can only be referring to
3228 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3229 // there are numerous ways to present the same IP. Having sp:contribs scan
3230 // them all is silly and having some show the edits and others not is
3231 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3232 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3233 ? IP
::sanitizeIP( $dbkey )
3236 // Any remaining initial :s are illegal.
3237 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3242 $this->mDbkeyform
= $dbkey;
3243 $this->mUrlform
= wfUrlencode( $dbkey );
3245 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3251 * Get an array of Title objects linking to this Title
3252 * Also stores the IDs in the link cache.
3254 * WARNING: do not use this function on arbitrary user-supplied titles!
3255 * On heavily-used templates it will max out the memory.
3257 * @param array $options may be FOR UPDATE
3258 * @param string $table table name
3259 * @param string $prefix fields prefix
3260 * @return Array of Title objects linking here
3262 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3263 if ( count( $options ) > 0 ) {
3264 $db = wfGetDB( DB_MASTER
);
3266 $db = wfGetDB( DB_SLAVE
);
3270 array( 'page', $table ),
3271 self
::getSelectFields(),
3273 "{$prefix}_from=page_id",
3274 "{$prefix}_namespace" => $this->getNamespace(),
3275 "{$prefix}_title" => $this->getDBkey() ),
3281 if ( $res->numRows() ) {
3282 $linkCache = LinkCache
::singleton();
3283 foreach ( $res as $row ) {
3284 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3286 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3287 $retVal[] = $titleObj;
3295 * Get an array of Title objects using this Title as a template
3296 * Also stores the IDs in the link cache.
3298 * WARNING: do not use this function on arbitrary user-supplied titles!
3299 * On heavily-used templates it will max out the memory.
3301 * @param array $options may be FOR UPDATE
3302 * @return Array of Title the Title objects linking here
3304 public function getTemplateLinksTo( $options = array() ) {
3305 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3309 * Get an array of Title objects linked from this Title
3310 * Also stores the IDs in the link cache.
3312 * WARNING: do not use this function on arbitrary user-supplied titles!
3313 * On heavily-used templates it will max out the memory.
3315 * @param array $options may be FOR UPDATE
3316 * @param string $table table name
3317 * @param string $prefix fields prefix
3318 * @return Array of Title objects linking here
3320 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3321 global $wgContentHandlerUseDB;
3323 $id = $this->getArticleID();
3325 # If the page doesn't exist; there can't be any link from this page
3330 if ( count( $options ) > 0 ) {
3331 $db = wfGetDB( DB_MASTER
);
3333 $db = wfGetDB( DB_SLAVE
);
3336 $namespaceFiled = "{$prefix}_namespace";
3337 $titleField = "{$prefix}_title";
3339 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3340 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3343 array( $table, 'page' ),
3345 array( "{$prefix}_from" => $id ),
3348 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3352 if ( $res->numRows() ) {
3353 $linkCache = LinkCache
::singleton();
3354 foreach ( $res as $row ) {
3355 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3357 if ( $row->page_id
) {
3358 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3360 $linkCache->addBadLinkObj( $titleObj );
3362 $retVal[] = $titleObj;
3370 * Get an array of Title objects used on this Title as a template
3371 * Also stores the IDs in the link cache.
3373 * WARNING: do not use this function on arbitrary user-supplied titles!
3374 * On heavily-used templates it will max out the memory.
3376 * @param array $options may be FOR UPDATE
3377 * @return Array of Title the Title objects used here
3379 public function getTemplateLinksFrom( $options = array() ) {
3380 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3384 * Get an array of Title objects referring to non-existent articles linked from this page
3386 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3387 * @return Array of Title the Title objects
3389 public function getBrokenLinksFrom() {
3390 if ( $this->getArticleID() == 0 ) {
3391 # All links from article ID 0 are false positives
3395 $dbr = wfGetDB( DB_SLAVE
);
3396 $res = $dbr->select(
3397 array( 'page', 'pagelinks' ),
3398 array( 'pl_namespace', 'pl_title' ),
3400 'pl_from' => $this->getArticleID(),
3401 'page_namespace IS NULL'
3403 __METHOD__
, array(),
3407 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3413 foreach ( $res as $row ) {
3414 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3420 * Get a list of URLs to purge from the Squid cache when this
3423 * @return Array of String the URLs
3425 public function getSquidURLs() {
3427 $this->getInternalURL(),
3428 $this->getInternalURL( 'action=history' )
3431 $pageLang = $this->getPageLanguage();
3432 if ( $pageLang->hasVariants() ) {
3433 $variants = $pageLang->getVariants();
3434 foreach ( $variants as $vCode ) {
3435 $urls[] = $this->getInternalURL( '', $vCode );
3443 * Purge all applicable Squid URLs
3445 public function purgeSquid() {
3447 if ( $wgUseSquid ) {
3448 $urls = $this->getSquidURLs();
3449 $u = new SquidUpdate( $urls );
3455 * Move this page without authentication
3457 * @param $nt Title the new page Title
3458 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3460 public function moveNoAuth( &$nt ) {
3461 return $this->moveTo( $nt, false );
3465 * Check whether a given move operation would be valid.
3466 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3468 * @param $nt Title the new title
3469 * @param bool $auth indicates whether $wgUser's permissions
3471 * @param string $reason is the log summary of the move, used for spam checking
3472 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3474 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3475 global $wgUser, $wgContentHandlerUseDB;
3479 // Normally we'd add this to $errors, but we'll get
3480 // lots of syntax errors if $nt is not an object
3481 return array( array( 'badtitletext' ) );
3483 if ( $this->equals( $nt ) ) {
3484 $errors[] = array( 'selfmove' );
3486 if ( !$this->isMovable() ) {
3487 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3489 if ( $nt->getInterwiki() != '' ) {
3490 $errors[] = array( 'immobile-target-namespace-iw' );
3492 if ( !$nt->isMovable() ) {
3493 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3496 $oldid = $this->getArticleID();
3497 $newid = $nt->getArticleID();
3499 if ( strlen( $nt->getDBkey() ) < 1 ) {
3500 $errors[] = array( 'articleexists' );
3503 ( $this->getDBkey() == '' ) ||
3505 ( $nt->getDBkey() == '' )
3507 $errors[] = array( 'badarticleerror' );
3510 // Content model checks
3511 if ( !$wgContentHandlerUseDB &&
3512 $this->getContentModel() !== $nt->getContentModel() ) {
3513 // can't move a page if that would change the page's content model
3516 ContentHandler
::getLocalizedName( $this->getContentModel() ),
3517 ContentHandler
::getLocalizedName( $nt->getContentModel() )
3521 // Image-specific checks
3522 if ( $this->getNamespace() == NS_FILE
) {
3523 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3526 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3527 $errors[] = array( 'nonfile-cannot-move-to-file' );
3531 $errors = wfMergeErrorArrays( $errors,
3532 $this->getUserPermissionsErrors( 'move', $wgUser ),
3533 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3534 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3535 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3538 $match = EditPage
::matchSummarySpamRegex( $reason );
3539 if ( $match !== false ) {
3540 // This is kind of lame, won't display nice
3541 $errors[] = array( 'spamprotectiontext' );
3545 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3546 $errors[] = array( 'hookaborted', $err );
3549 # The move is allowed only if (1) the target doesn't exist, or
3550 # (2) the target is a redirect to the source, and has no history
3551 # (so we can undo bad moves right after they're done).
3553 if ( 0 != $newid ) { # Target exists; check for validity
3554 if ( !$this->isValidMoveTarget( $nt ) ) {
3555 $errors[] = array( 'articleexists' );
3558 $tp = $nt->getTitleProtection();
3559 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3560 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3561 $errors[] = array( 'cantmove-titleprotected' );
3564 if ( empty( $errors ) ) {
3571 * Check if the requested move target is a valid file move target
3572 * @param Title $nt Target title
3573 * @return array List of errors
3575 protected function validateFileMoveOperation( $nt ) {
3580 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3582 $file = wfLocalFile( $this );
3583 if ( $file->exists() ) {
3584 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3585 $errors[] = array( 'imageinvalidfilename' );
3587 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3588 $errors[] = array( 'imagetypemismatch' );
3592 if ( $nt->getNamespace() != NS_FILE
) {
3593 $errors[] = array( 'imagenocrossnamespace' );
3594 // From here we want to do checks on a file object, so if we can't
3595 // create one, we must return.
3599 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3601 $destFile = wfLocalFile( $nt );
3602 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3603 $errors[] = array( 'file-exists-sharedrepo' );
3610 * Move a title to a new location
3612 * @param $nt Title the new title
3613 * @param bool $auth indicates whether $wgUser's permissions
3615 * @param string $reason the reason for the move
3616 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3617 * Ignored if the user doesn't have the suppressredirect right.
3618 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3620 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3622 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3623 if ( is_array( $err ) ) {
3624 // Auto-block user's IP if the account was "hard" blocked
3625 $wgUser->spreadAnyEditBlock();
3628 // Check suppressredirect permission
3629 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3630 $createRedirect = true;
3633 // If it is a file, move it first.
3634 // It is done before all other moving stuff is done because it's hard to revert.
3635 $dbw = wfGetDB( DB_MASTER
);
3636 if ( $this->getNamespace() == NS_FILE
) {
3637 $file = wfLocalFile( $this );
3638 if ( $file->exists() ) {
3639 $status = $file->move( $nt );
3640 if ( !$status->isOk() ) {
3641 return $status->getErrorsArray();
3644 // Clear RepoGroup process cache
3645 RepoGroup
::singleton()->clearCache( $this );
3646 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3649 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3650 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3651 $protected = $this->isProtected();
3653 // Do the actual move
3654 $this->moveToInternal( $nt, $reason, $createRedirect );
3656 // Refresh the sortkey for this row. Be careful to avoid resetting
3657 // cl_timestamp, which may disturb time-based lists on some sites.
3658 $prefixes = $dbw->select(
3660 array( 'cl_sortkey_prefix', 'cl_to' ),
3661 array( 'cl_from' => $pageid ),
3664 foreach ( $prefixes as $prefixRow ) {
3665 $prefix = $prefixRow->cl_sortkey_prefix
;
3666 $catTo = $prefixRow->cl_to
;
3667 $dbw->update( 'categorylinks',
3669 'cl_sortkey' => Collation
::singleton()->getSortKey(
3670 $nt->getCategorySortkey( $prefix ) ),
3671 'cl_timestamp=cl_timestamp' ),
3673 'cl_from' => $pageid,
3674 'cl_to' => $catTo ),
3679 $redirid = $this->getArticleID();
3682 # Protect the redirect title as the title used to be...
3683 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3685 'pr_page' => $redirid,
3686 'pr_type' => 'pr_type',
3687 'pr_level' => 'pr_level',
3688 'pr_cascade' => 'pr_cascade',
3689 'pr_user' => 'pr_user',
3690 'pr_expiry' => 'pr_expiry'
3692 array( 'pr_page' => $pageid ),
3696 # Update the protection log
3697 $log = new LogPage( 'protect' );
3698 $comment = wfMessage(
3700 $this->getPrefixedText(),
3701 $nt->getPrefixedText()
3702 )->inContentLanguage()->text();
3704 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3706 // @todo FIXME: $params?
3707 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3711 $oldnamespace = MWNamespace
::getSubject( $this->getNamespace() );
3712 $newnamespace = MWNamespace
::getSubject( $nt->getNamespace() );
3713 $oldtitle = $this->getDBkey();
3714 $newtitle = $nt->getDBkey();
3716 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3717 WatchedItem
::duplicateEntries( $this, $nt );
3720 $dbw->commit( __METHOD__
);
3722 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3727 * Move page to a title which is either a redirect to the
3728 * source page or nonexistent
3730 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3731 * @param string $reason The reason for the move
3732 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3733 * if the user has the suppressredirect right
3734 * @throws MWException
3736 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3737 global $wgUser, $wgContLang;
3739 if ( $nt->exists() ) {
3740 $moveOverRedirect = true;
3741 $logType = 'move_redir';
3743 $moveOverRedirect = false;
3747 if ( $createRedirect ) {
3748 $contentHandler = ContentHandler
::getForTitle( $this );
3749 $redirectContent = $contentHandler->makeRedirectContent( $nt );
3751 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3753 $redirectContent = null;
3756 $logEntry = new ManualLogEntry( 'move', $logType );
3757 $logEntry->setPerformer( $wgUser );
3758 $logEntry->setTarget( $this );
3759 $logEntry->setComment( $reason );
3760 $logEntry->setParameters( array(
3761 '4::target' => $nt->getPrefixedText(),
3762 '5::noredir' => $redirectContent ?
'0': '1',
3765 $formatter = LogFormatter
::newFromEntry( $logEntry );
3766 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3767 $comment = $formatter->getPlainActionText();
3769 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3771 # Truncate for whole multibyte characters.
3772 $comment = $wgContLang->truncate( $comment, 255 );
3774 $oldid = $this->getArticleID();
3776 $dbw = wfGetDB( DB_MASTER
);
3778 $newpage = WikiPage
::factory( $nt );
3780 if ( $moveOverRedirect ) {
3781 $newid = $nt->getArticleID();
3783 # Delete the old redirect. We don't save it to history since
3784 # by definition if we've got here it's rather uninteresting.
3785 # We have to remove it so that the next step doesn't trigger
3786 # a conflict on the unique namespace+title index...
3787 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3789 $newpage->doDeleteUpdates( $newid );
3792 # Save a null revision in the page's history notifying of the move
3793 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3794 if ( !is_object( $nullRevision ) ) {
3795 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3798 $nullRevision->insertOn( $dbw );
3800 # Change the name of the target page:
3801 $dbw->update( 'page',
3803 'page_namespace' => $nt->getNamespace(),
3804 'page_title' => $nt->getDBkey(),
3806 /* WHERE */ array( 'page_id' => $oldid ),
3810 $this->resetArticleID( 0 );
3811 $nt->resetArticleID( $oldid );
3812 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // bug 46397
3814 $newpage->updateRevisionOn( $dbw, $nullRevision );
3816 wfRunHooks( 'NewRevisionFromEditComplete',
3817 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3819 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3821 if ( !$moveOverRedirect ) {
3822 WikiPage
::onArticleCreate( $nt );
3825 # Recreate the redirect, this time in the other direction.
3826 if ( !$redirectContent ) {
3827 WikiPage
::onArticleDelete( $this );
3829 $redirectArticle = WikiPage
::factory( $this );
3830 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // bug 46397
3831 $newid = $redirectArticle->insertOn( $dbw );
3832 if ( $newid ) { // sanity
3833 $redirectRevision = new Revision( array(
3834 'title' => $this, // for determining the default content model
3836 'comment' => $comment,
3837 'content' => $redirectContent ) );
3838 $redirectRevision->insertOn( $dbw );
3839 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3841 wfRunHooks( 'NewRevisionFromEditComplete',
3842 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3844 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3849 $logid = $logEntry->insert();
3850 $logEntry->publish( $logid );
3854 * Move this page's subpages to be subpages of $nt
3856 * @param $nt Title Move target
3857 * @param bool $auth Whether $wgUser's permissions should be checked
3858 * @param string $reason The reason for the move
3859 * @param bool $createRedirect Whether to create redirects from the old subpages to
3860 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3861 * @return mixed array with old page titles as keys, and strings (new page titles) or
3862 * arrays (errors) as values, or an error array with numeric indices if no pages
3865 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3866 global $wgMaximumMovedPages;
3867 // Check permissions
3868 if ( !$this->userCan( 'move-subpages' ) ) {
3869 return array( 'cant-move-subpages' );
3871 // Do the source and target namespaces support subpages?
3872 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3873 return array( 'namespace-nosubpages',
3874 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3876 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3877 return array( 'namespace-nosubpages',
3878 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3881 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3884 foreach ( $subpages as $oldSubpage ) {
3886 if ( $count > $wgMaximumMovedPages ) {
3887 $retval[$oldSubpage->getPrefixedTitle()] =
3888 array( 'movepage-max-pages',
3889 $wgMaximumMovedPages );
3893 // We don't know whether this function was called before
3894 // or after moving the root page, so check both
3896 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3897 $oldSubpage->getArticleID() == $nt->getArticleID() )
3899 // When moving a page to a subpage of itself,
3900 // don't move it twice
3903 $newPageName = preg_replace(
3904 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3905 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3906 $oldSubpage->getDBkey() );
3907 if ( $oldSubpage->isTalkPage() ) {
3908 $newNs = $nt->getTalkPage()->getNamespace();
3910 $newNs = $nt->getSubjectPage()->getNamespace();
3912 # Bug 14385: we need makeTitleSafe because the new page names may
3913 # be longer than 255 characters.
3914 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3916 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3917 if ( $success === true ) {
3918 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3920 $retval[$oldSubpage->getPrefixedText()] = $success;
3927 * Checks if this page is just a one-rev redirect.
3928 * Adds lock, so don't use just for light purposes.
3932 public function isSingleRevRedirect() {
3933 global $wgContentHandlerUseDB;
3935 $dbw = wfGetDB( DB_MASTER
);
3938 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3939 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3941 $row = $dbw->selectRow( 'page',
3945 array( 'FOR UPDATE' )
3947 # Cache some fields we may want
3948 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3949 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3950 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3951 $this->mContentModel
= $row && isset( $row->page_content_model
) ?
strval( $row->page_content_model
) : false;
3952 if ( !$this->mRedirect
) {
3955 # Does the article have a history?
3956 $row = $dbw->selectField( array( 'page', 'revision' ),
3958 array( 'page_namespace' => $this->getNamespace(),
3959 'page_title' => $this->getDBkey(),
3961 'page_latest != rev_id'
3964 array( 'FOR UPDATE' )
3966 # Return true if there was no history
3967 return ( $row === false );
3971 * Checks if $this can be moved to a given Title
3972 * - Selects for update, so don't call it unless you mean business
3974 * @param $nt Title the new title to check
3977 public function isValidMoveTarget( $nt ) {
3978 # Is it an existing file?
3979 if ( $nt->getNamespace() == NS_FILE
) {
3980 $file = wfLocalFile( $nt );
3981 if ( $file->exists() ) {
3982 wfDebug( __METHOD__
. ": file exists\n" );
3986 # Is it a redirect with no history?
3987 if ( !$nt->isSingleRevRedirect() ) {
3988 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3991 # Get the article text
3992 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3993 if( !is_object( $rev ) ) {
3996 $content = $rev->getContent();
3997 # Does the redirect point to the source?
3998 # Or is it a broken self-redirect, usually caused by namespace collisions?
3999 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4001 if ( $redirTitle ) {
4002 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4003 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4004 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4010 # Fail safe (not a redirect after all. strange.)
4011 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4012 " is a redirect, but it doesn't contain a valid redirect.\n" );
4018 * Get categories to which this Title belongs and return an array of
4019 * categories' names.
4021 * @return Array of parents in the form:
4022 * $parent => $currentarticle
4024 public function getParentCategories() {
4029 $titleKey = $this->getArticleID();
4031 if ( $titleKey === 0 ) {
4035 $dbr = wfGetDB( DB_SLAVE
);
4037 $res = $dbr->select(
4040 array( 'cl_from' => $titleKey ),
4044 if ( $res->numRows() > 0 ) {
4045 foreach ( $res as $row ) {
4046 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4047 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4054 * Get a tree of parent categories
4056 * @param array $children with the children in the keys, to check for circular refs
4057 * @return Array Tree of parent categories
4059 public function getParentCategoryTree( $children = array() ) {
4061 $parents = $this->getParentCategories();
4064 foreach ( $parents as $parent => $current ) {
4065 if ( array_key_exists( $parent, $children ) ) {
4066 # Circular reference
4067 $stack[$parent] = array();
4069 $nt = Title
::newFromText( $parent );
4071 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
4081 * Get an associative array for selecting this title from
4084 * @return Array suitable for the $where parameter of DB::select()
4086 public function pageCond() {
4087 if ( $this->mArticleID
> 0 ) {
4088 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4089 return array( 'page_id' => $this->mArticleID
);
4091 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4096 * Get the revision ID of the previous revision
4098 * @param int $revId Revision ID. Get the revision that was before this one.
4099 * @param int $flags Title::GAID_FOR_UPDATE
4100 * @return Int|Bool Old revision ID, or FALSE if none exists
4102 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4103 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4104 $revId = $db->selectField( 'revision', 'rev_id',
4106 'rev_page' => $this->getArticleID( $flags ),
4107 'rev_id < ' . intval( $revId )
4110 array( 'ORDER BY' => 'rev_id DESC' )
4113 if ( $revId === false ) {
4116 return intval( $revId );
4121 * Get the revision ID of the next revision
4123 * @param int $revId Revision ID. Get the revision that was after this one.
4124 * @param int $flags Title::GAID_FOR_UPDATE
4125 * @return Int|Bool Next revision ID, or FALSE if none exists
4127 public function getNextRevisionID( $revId, $flags = 0 ) {
4128 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4129 $revId = $db->selectField( 'revision', 'rev_id',
4131 'rev_page' => $this->getArticleID( $flags ),
4132 'rev_id > ' . intval( $revId )
4135 array( 'ORDER BY' => 'rev_id' )
4138 if ( $revId === false ) {
4141 return intval( $revId );
4146 * Get the first revision of the page
4148 * @param int $flags Title::GAID_FOR_UPDATE
4149 * @return Revision|Null if page doesn't exist
4151 public function getFirstRevision( $flags = 0 ) {
4152 $pageId = $this->getArticleID( $flags );
4154 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4155 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4156 array( 'rev_page' => $pageId ),
4158 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4161 return new Revision( $row );
4168 * Get the oldest revision timestamp of this page
4170 * @param int $flags Title::GAID_FOR_UPDATE
4171 * @return String: MW timestamp
4173 public function getEarliestRevTime( $flags = 0 ) {
4174 $rev = $this->getFirstRevision( $flags );
4175 return $rev ?
$rev->getTimestamp() : null;
4179 * Check if this is a new page
4183 public function isNewPage() {
4184 $dbr = wfGetDB( DB_SLAVE
);
4185 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4189 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4193 public function isBigDeletion() {
4194 global $wgDeleteRevisionsLimit;
4196 if ( !$wgDeleteRevisionsLimit ) {
4200 $revCount = $this->estimateRevisionCount();
4201 return $revCount > $wgDeleteRevisionsLimit;
4205 * Get the approximate revision count of this page.
4209 public function estimateRevisionCount() {
4210 if ( !$this->exists() ) {
4214 if ( $this->mEstimateRevisions
=== null ) {
4215 $dbr = wfGetDB( DB_SLAVE
);
4216 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4217 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4220 return $this->mEstimateRevisions
;
4224 * Get the number of revisions between the given revision.
4225 * Used for diffs and other things that really need it.
4227 * @param int|Revision $old Old revision or rev ID (first before range)
4228 * @param int|Revision $new New revision or rev ID (first after range)
4229 * @return Int Number of revisions between these revisions.
4231 public function countRevisionsBetween( $old, $new ) {
4232 if ( !( $old instanceof Revision
) ) {
4233 $old = Revision
::newFromTitle( $this, (int)$old );
4235 if ( !( $new instanceof Revision
) ) {
4236 $new = Revision
::newFromTitle( $this, (int)$new );
4238 if ( !$old ||
!$new ) {
4239 return 0; // nothing to compare
4241 $dbr = wfGetDB( DB_SLAVE
);
4242 return (int)$dbr->selectField( 'revision', 'count(*)',
4244 'rev_page' => $this->getArticleID(),
4245 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4246 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4253 * Get the number of authors between the given revisions or revision IDs.
4254 * Used for diffs and other things that really need it.
4256 * @param int|Revision $old Old revision or rev ID (first before range by default)
4257 * @param int|Revision $new New revision or rev ID (first after range by default)
4258 * @param int $limit Maximum number of authors
4259 * @param string|array $options (Optional): Single option, or an array of options:
4260 * 'include_old' Include $old in the range; $new is excluded.
4261 * 'include_new' Include $new in the range; $old is excluded.
4262 * 'include_both' Include both $old and $new in the range.
4263 * Unknown option values are ignored.
4264 * @return int Number of revision authors in the range; zero if not both revisions exist
4266 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4267 if ( !( $old instanceof Revision
) ) {
4268 $old = Revision
::newFromTitle( $this, (int)$old );
4270 if ( !( $new instanceof Revision
) ) {
4271 $new = Revision
::newFromTitle( $this, (int)$new );
4273 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4274 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4275 // in the sanity check below?
4276 if ( !$old ||
!$new ) {
4277 return 0; // nothing to compare
4281 $options = (array)$options;
4282 if ( in_array( 'include_old', $options ) ) {
4285 if ( in_array( 'include_new', $options ) ) {
4288 if ( in_array( 'include_both', $options ) ) {
4292 // No DB query needed if $old and $new are the same or successive revisions:
4293 if ( $old->getId() === $new->getId() ) {
4294 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4295 } else if ( $old->getId() === $new->getParentId() ) {
4296 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4297 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4299 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4301 $dbr = wfGetDB( DB_SLAVE
);
4302 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4304 'rev_page' => $this->getArticleID(),
4305 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4306 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4308 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4310 return (int)$dbr->numRows( $res );
4314 * Compare with another title.
4316 * @param $title Title
4319 public function equals( Title
$title ) {
4320 // Note: === is necessary for proper matching of number-like titles.
4321 return $this->getInterwiki() === $title->getInterwiki()
4322 && $this->getNamespace() == $title->getNamespace()
4323 && $this->getDBkey() === $title->getDBkey();
4327 * Check if this title is a subpage of another title
4329 * @param $title Title
4332 public function isSubpageOf( Title
$title ) {
4333 return $this->getInterwiki() === $title->getInterwiki()
4334 && $this->getNamespace() == $title->getNamespace()
4335 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4339 * Check if page exists. For historical reasons, this function simply
4340 * checks for the existence of the title in the page table, and will
4341 * thus return false for interwiki links, special pages and the like.
4342 * If you want to know if a title can be meaningfully viewed, you should
4343 * probably call the isKnown() method instead.
4347 public function exists() {
4348 return $this->getArticleID() != 0;
4352 * Should links to this title be shown as potentially viewable (i.e. as
4353 * "bluelinks"), even if there's no record by this title in the page
4356 * This function is semi-deprecated for public use, as well as somewhat
4357 * misleadingly named. You probably just want to call isKnown(), which
4358 * calls this function internally.
4360 * (ISSUE: Most of these checks are cheap, but the file existence check
4361 * can potentially be quite expensive. Including it here fixes a lot of
4362 * existing code, but we might want to add an optional parameter to skip
4363 * it and any other expensive checks.)
4367 public function isAlwaysKnown() {
4371 * Allows overriding default behavior for determining if a page exists.
4372 * If $isKnown is kept as null, regular checks happen. If it's
4373 * a boolean, this value is returned by the isKnown method.
4377 * @param Title $title
4378 * @param boolean|null $isKnown
4380 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4382 if ( !is_null( $isKnown ) ) {
4386 if ( $this->mInterwiki
!= '' ) {
4387 return true; // any interwiki link might be viewable, for all we know
4390 switch( $this->mNamespace
) {
4393 // file exists, possibly in a foreign repo
4394 return (bool)wfFindFile( $this );
4396 // valid special page
4397 return SpecialPageFactory
::exists( $this->getDBkey() );
4399 // selflink, possibly with fragment
4400 return $this->mDbkeyform
== '';
4402 // known system message
4403 return $this->hasSourceText() !== false;
4410 * Does this title refer to a page that can (or might) be meaningfully
4411 * viewed? In particular, this function may be used to determine if
4412 * links to the title should be rendered as "bluelinks" (as opposed to
4413 * "redlinks" to non-existent pages).
4414 * Adding something else to this function will cause inconsistency
4415 * since LinkHolderArray calls isAlwaysKnown() and does its own
4416 * page existence check.
4420 public function isKnown() {
4421 return $this->isAlwaysKnown() ||
$this->exists();
4425 * Does this page have source text?
4429 public function hasSourceText() {
4430 if ( $this->exists() ) {
4434 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4435 // If the page doesn't exist but is a known system message, default
4436 // message content will be displayed, same for language subpages-
4437 // Use always content language to avoid loading hundreds of languages
4438 // to get the link color.
4440 list( $name, ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4441 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4442 return $message->exists();
4449 * Get the default message text or false if the message doesn't exist
4451 * @return String or false
4453 public function getDefaultMessageText() {
4456 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4460 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4461 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4463 if ( $message->exists() ) {
4464 return $message->plain();
4471 * Updates page_touched for this page; called from LinksUpdate.php
4473 * @return Bool true if the update succeeded
4475 public function invalidateCache() {
4478 if ( wfReadOnly() ) {
4482 $dbw = wfGetDB( DB_MASTER
);
4483 $conds = $this->pageCond();
4484 $dbw->onTransactionIdle( function() use ( $dbw, $conds ) {
4487 array( 'page_touched' => $dbw->timestamp() ),
4492 HTMLFileCache
::clearFileCache( $this );
4495 $revision = WikiPage
::factory( $this )->getRevision();
4496 if ( $revision !== null ) {
4497 $memcKey = wfMemcKey( 'infoaction', $this->getPrefixedText(), $revision->getId() );
4498 $success = $wgMemc->delete( $memcKey );
4507 * Update page_touched timestamps and send squid purge messages for
4508 * pages linking to this title. May be sent to the job queue depending
4509 * on the number of links. Typically called on create and delete.
4511 public function touchLinks() {
4512 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4515 if ( $this->getNamespace() == NS_CATEGORY
) {
4516 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4522 * Get the last touched timestamp
4524 * @param $db DatabaseBase: optional db
4525 * @return String last-touched timestamp
4527 public function getTouched( $db = null ) {
4528 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4529 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4534 * Get the timestamp when this page was updated since the user last saw it.
4537 * @return String|Null
4539 public function getNotificationTimestamp( $user = null ) {
4540 global $wgUser, $wgShowUpdatedMarker;
4541 // Assume current user if none given
4545 // Check cache first
4546 $uid = $user->getId();
4547 // avoid isset here, as it'll return false for null entries
4548 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4549 return $this->mNotificationTimestamp
[$uid];
4551 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4552 return $this->mNotificationTimestamp
[$uid] = false;
4554 // Don't cache too much!
4555 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4556 $this->mNotificationTimestamp
= array();
4558 $dbr = wfGetDB( DB_SLAVE
);
4559 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4560 'wl_notificationtimestamp',
4562 'wl_user' => $user->getId(),
4563 'wl_namespace' => $this->getNamespace(),
4564 'wl_title' => $this->getDBkey(),
4568 return $this->mNotificationTimestamp
[$uid];
4572 * Generate strings used for xml 'id' names in monobook tabs
4574 * @param string $prepend defaults to 'nstab-'
4575 * @return String XML 'id' name
4577 public function getNamespaceKey( $prepend = 'nstab-' ) {
4579 // Gets the subject namespace if this title
4580 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4581 // Checks if canonical namespace name exists for namespace
4582 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4583 // Uses canonical namespace name
4584 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4586 // Uses text of namespace
4587 $namespaceKey = $this->getSubjectNsText();
4589 // Makes namespace key lowercase
4590 $namespaceKey = $wgContLang->lc( $namespaceKey );
4592 if ( $namespaceKey == '' ) {
4593 $namespaceKey = 'main';
4595 // Changes file to image for backwards compatibility
4596 if ( $namespaceKey == 'file' ) {
4597 $namespaceKey = 'image';
4599 return $prepend . $namespaceKey;
4603 * Get all extant redirects to this Title
4605 * @param int|Null $ns Single namespace to consider; NULL to consider all namespaces
4606 * @return Array of Title redirects to this title
4608 public function getRedirectsHere( $ns = null ) {
4611 $dbr = wfGetDB( DB_SLAVE
);
4613 'rd_namespace' => $this->getNamespace(),
4614 'rd_title' => $this->getDBkey(),
4617 if ( $this->isExternal() ) {
4618 $where['rd_interwiki'] = $this->getInterwiki();
4620 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4622 if ( !is_null( $ns ) ) {
4623 $where['page_namespace'] = $ns;
4626 $res = $dbr->select(
4627 array( 'redirect', 'page' ),
4628 array( 'page_namespace', 'page_title' ),
4633 foreach ( $res as $row ) {
4634 $redirs[] = self
::newFromRow( $row );
4640 * Check if this Title is a valid redirect target
4644 public function isValidRedirectTarget() {
4645 global $wgInvalidRedirectTargets;
4647 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4648 if ( $this->isSpecial( 'Userlogout' ) ) {
4652 foreach ( $wgInvalidRedirectTargets as $target ) {
4653 if ( $this->isSpecial( $target ) ) {
4662 * Get a backlink cache object
4664 * @return BacklinkCache
4666 public function getBacklinkCache() {
4667 return BacklinkCache
::get( $this );
4671 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4675 public function canUseNoindex() {
4676 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4678 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4679 ?
$wgContentNamespaces
4680 : $wgExemptFromUserRobotsControl;
4682 return !in_array( $this->mNamespace
, $bannedNamespaces );
4687 * Returns the raw sort key to be used for categories, with the specified
4688 * prefix. This will be fed to Collation::getSortKey() to get a
4689 * binary sortkey that can be used for actual sorting.
4691 * @param string $prefix The prefix to be used, specified using
4692 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4696 public function getCategorySortkey( $prefix = '' ) {
4697 $unprefixed = $this->getText();
4699 // Anything that uses this hook should only depend
4700 // on the Title object passed in, and should probably
4701 // tell the users to run updateCollations.php --force
4702 // in order to re-sort existing category relations.
4703 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4704 if ( $prefix !== '' ) {
4705 # Separate with a line feed, so the unprefixed part is only used as
4706 # a tiebreaker when two pages have the exact same prefix.
4707 # In UCA, tab is the only character that can sort above LF
4708 # so we strip both of them from the original prefix.
4709 $prefix = strtr( $prefix, "\n\t", ' ' );
4710 return "$prefix\n$unprefixed";
4716 * Get the language in which the content of this page is written in
4717 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4718 * e.g. $wgLang (such as special pages, which are in the user language).
4723 public function getPageLanguage() {
4725 if ( $this->isSpecialPage() ) {
4726 // special pages are in the user language
4730 //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
4731 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4732 $contentHandler = ContentHandler
::getForTitle( $this );
4733 $pageLang = $contentHandler->getPageLanguage( $this );
4735 return wfGetLangObj( $pageLang );
4739 * Get the language in which the content of this page is written when
4740 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4741 * e.g. $wgLang (such as special pages, which are in the user language).
4746 public function getPageViewLanguage() {
4749 if ( $this->isSpecialPage() ) {
4750 // If the user chooses a variant, the content is actually
4751 // in a language whose code is the variant code.
4752 $variant = $wgLang->getPreferredVariant();
4753 if ( $wgLang->getCode() !== $variant ) {
4754 return Language
::factory( $variant );
4760 //NOTE: can't be cached persistently, depends on user settings
4761 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4762 $contentHandler = ContentHandler
::getForTitle( $this );
4763 $pageLang = $contentHandler->getPageViewLanguage( $this );
4768 * Get a list of rendered edit notices for this page.
4770 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4771 * they will already be wrapped in paragraphs.
4776 public function getEditNotices() {
4779 # Optional notices on a per-namespace and per-page basis
4780 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4781 $editnotice_ns_message = wfMessage( $editnotice_ns );
4782 if ( $editnotice_ns_message->exists() ) {
4783 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4785 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4786 $parts = explode( '/', $this->getDBkey() );
4787 $editnotice_base = $editnotice_ns;
4788 while ( count( $parts ) > 0 ) {
4789 $editnotice_base .= '-' . array_shift( $parts );
4790 $editnotice_base_msg = wfMessage( $editnotice_base );
4791 if ( $editnotice_base_msg->exists() ) {
4792 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4796 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4797 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4798 $editnoticeMsg = wfMessage( $editnoticeText );
4799 if ( $editnoticeMsg->exists() ) {
4800 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();