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 $mBacklinkCache = null; // /< Cache of links to this title
89 var $mHasSubpage; // /< Whether a page has any subpages
96 /*protected*/ function __construct() { }
99 * Create a new Title from a prefixed DB key
101 * @param $key String the database key, which has underscores
102 * instead of spaces, possibly including namespace and
104 * @return Title, or NULL on an error
106 public static function newFromDBkey( $key ) {
108 $t->mDbkeyform
= $key;
109 if ( $t->secureAndSplit() ) {
117 * Create a new Title from text, such as what one would find in a link. De-
118 * codes any HTML entities in the text.
120 * @param $text String the link text; spaces, prefixes, and an
121 * initial ':' indicating the main namespace are accepted.
122 * @param $defaultNamespace Int the namespace to use if none is speci-
123 * fied by a prefix. If you want to force a specific namespace even if
124 * $text might begin with a namespace prefix, use makeTitle() or
126 * @throws MWException
127 * @return Title|null - Title or null on an error.
129 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
130 if ( is_object( $text ) ) {
131 throw new MWException( 'Title::newFromText given an object' );
135 * Wiki pages often contain multiple links to the same page.
136 * Title normalization and parsing can become expensive on
137 * pages with many links, so we can save a little time by
140 * In theory these are value objects and won't get changed...
142 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
143 return Title
::$titleCache[$text];
146 # Convert things like é ā or 〗 into normalized (bug 14952) text
147 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
150 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
151 $t->mDefaultNamespace
= $defaultNamespace;
153 static $cachedcount = 0 ;
154 if ( $t->secureAndSplit() ) {
155 if ( $defaultNamespace == NS_MAIN
) {
156 if ( $cachedcount >= self
::CACHE_MAX
) {
157 # Avoid memory leaks on mass operations...
158 Title
::$titleCache = array();
162 Title
::$titleCache[$text] =& $t;
172 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
174 * Example of wrong and broken code:
175 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
177 * Example of right code:
178 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
180 * Create a new Title from URL-encoded text. Ensures that
181 * the given title's length does not exceed the maximum.
183 * @param $url String the title, as might be taken from a URL
184 * @return Title the new object, or NULL on an error
186 public static function newFromURL( $url ) {
189 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
190 # but some URLs used it as a space replacement and they still come
191 # from some external search tools.
192 if ( strpos( self
::legalChars(), '+' ) === false ) {
193 $url = str_replace( '+', ' ', $url );
196 $t->mDbkeyform
= str_replace( ' ', '_', $url );
197 if ( $t->secureAndSplit() ) {
205 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
206 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
210 protected static function getSelectFields() {
211 global $wgContentHandlerUseDB;
214 'page_namespace', 'page_title', 'page_id',
215 'page_len', 'page_is_redirect', 'page_latest',
218 if ( $wgContentHandlerUseDB ) {
219 $fields[] = 'page_content_model';
226 * Create a new Title from an article ID
228 * @param $id Int the page_id corresponding to the Title to create
229 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
230 * @return Title the new object, or NULL on an error
232 public static function newFromID( $id, $flags = 0 ) {
233 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
234 $row = $db->selectRow(
236 self
::getSelectFields(),
237 array( 'page_id' => $id ),
240 if ( $row !== false ) {
241 $title = Title
::newFromRow( $row );
249 * Make an array of titles from an array of IDs
251 * @param $ids Array of Int Array of IDs
252 * @return Array of Titles
254 public static function newFromIDs( $ids ) {
255 if ( !count( $ids ) ) {
258 $dbr = wfGetDB( DB_SLAVE
);
262 self
::getSelectFields(),
263 array( 'page_id' => $ids ),
268 foreach ( $res as $row ) {
269 $titles[] = Title
::newFromRow( $row );
275 * Make a Title object from a DB row
277 * @param $row Object database row (needs at least page_title,page_namespace)
278 * @return Title corresponding Title
280 public static function newFromRow( $row ) {
281 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
282 $t->loadFromRow( $row );
287 * Load Title object fields from a DB row.
288 * If false is given, the title will be treated as non-existing.
290 * @param $row Object|bool database row
292 public function loadFromRow( $row ) {
293 if ( $row ) { // page found
294 if ( isset( $row->page_id
) )
295 $this->mArticleID
= (int)$row->page_id
;
296 if ( isset( $row->page_len
) )
297 $this->mLength
= (int)$row->page_len
;
298 if ( isset( $row->page_is_redirect
) )
299 $this->mRedirect
= (bool)$row->page_is_redirect
;
300 if ( isset( $row->page_latest
) )
301 $this->mLatestID
= (int)$row->page_latest
;
302 if ( isset( $row->page_content_model
) )
303 $this->mContentModel
= strval( $row->page_content_model
);
305 $this->mContentModel
= false; # initialized lazily in getContentModel()
306 } else { // page not found
307 $this->mArticleID
= 0;
309 $this->mRedirect
= false;
310 $this->mLatestID
= 0;
311 $this->mContentModel
= false; # initialized lazily in getContentModel()
316 * Create a new Title from a namespace index and a DB key.
317 * It's assumed that $ns and $title are *valid*, for instance when
318 * they came directly from the database or a special page name.
319 * For convenience, spaces are converted to underscores so that
320 * eg user_text fields can be used directly.
322 * @param $ns Int the namespace of the article
323 * @param $title String the unprefixed database key form
324 * @param $fragment String the link fragment (after the "#")
325 * @param $interwiki String the interwiki prefix
326 * @return Title the new object
328 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
330 $t->mInterwiki
= $interwiki;
331 $t->mFragment
= $fragment;
332 $t->mNamespace
= $ns = intval( $ns );
333 $t->mDbkeyform
= str_replace( ' ', '_', $title );
334 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
335 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
336 $t->mTextform
= str_replace( '_', ' ', $title );
337 $t->mContentModel
= false; # initialized lazily in getContentModel()
342 * Create a new Title from a namespace index and a DB key.
343 * The parameters will be checked for validity, which is a bit slower
344 * than makeTitle() but safer for user-provided data.
346 * @param $ns Int the namespace of the article
347 * @param $title String database key form
348 * @param $fragment String the link fragment (after the "#")
349 * @param $interwiki String interwiki prefix
350 * @return Title the new object, or NULL on an error
352 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
353 if ( !MWNamespace
::exists( $ns ) ) {
358 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
359 if ( $t->secureAndSplit() ) {
367 * Create a new Title for the Main Page
369 * @return Title the new object
371 public static function newMainPage() {
372 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
373 // Don't give fatal errors if the message is broken
375 $title = Title
::newFromText( 'Main Page' );
381 * Extract a redirect destination from a string and return the
382 * Title, or null if the text doesn't contain a valid redirect
383 * This will only return the very next target, useful for
384 * the redirect table and other checks that don't need full recursion
386 * @param $text String: Text with possible redirect
387 * @return Title: The corresponding Title
388 * @deprecated since 1.WD, use Content::getRedirectTarget instead.
390 public static function newFromRedirect( $text ) {
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 $text String Text with possible redirect
403 * @deprecated since 1.WD, use Content::getUltimateRedirectTarget instead.
405 public static function newFromRedirectRecurse( $text ) {
406 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
407 return $content->getUltimateRedirectTarget();
411 * Extract a redirect destination from a string and return an
412 * array of Titles, or null if the text doesn't contain a valid redirect
413 * The last element in the array is the final destination after all redirects
414 * have been resolved (up to $wgMaxRedirects times)
416 * @param $text String Text with possible redirect
417 * @return Array of Titles, with the destination last
418 * @deprecated since 1.WD, use Content::getRedirectChain instead.
420 public static function newFromRedirectArray( $text ) {
421 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
422 return $content->getRedirectChain();
426 * Get the prefixed DB key associated with an ID
428 * @param $id Int the page_id of the article
429 * @return Title an object representing the article, or NULL if no such article was found
431 public static function nameOf( $id ) {
432 $dbr = wfGetDB( DB_SLAVE
);
434 $s = $dbr->selectRow(
436 array( 'page_namespace', 'page_title' ),
437 array( 'page_id' => $id ),
440 if ( $s === false ) {
444 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
449 * Get a regex character class describing the legal characters in a link
451 * @return String the list of characters, not delimited
453 public static function legalChars() {
454 global $wgLegalTitleChars;
455 return $wgLegalTitleChars;
459 * Returns a simple regex that will match on characters and sequences invalid in titles.
460 * Note that this doesn't pick up many things that could be wrong with titles, but that
461 * replacing this regex with something valid will make many titles valid.
463 * @return String regex string
465 static function getTitleInvalidRegex() {
466 static $rxTc = false;
468 # Matching titles will be held as illegal.
470 # Any character not allowed is forbidden...
471 '[^' . self
::legalChars() . ']' .
472 # URL percent encoding sequences interfere with the ability
473 # to round-trip titles -- you can't link to them consistently.
475 # XML/HTML character references produce similar issues.
476 '|&[A-Za-z0-9\x80-\xff]+;' .
478 '|&#x[0-9A-Fa-f]+;' .
486 * Get a string representation of a title suitable for
487 * including in a search index
489 * @param $ns Int a namespace index
490 * @param $title String text-form main part
491 * @return String a stripped-down title string ready for the search index
493 public static function indexTitle( $ns, $title ) {
496 $lc = SearchEngine
::legalSearchChars() . '&#;';
497 $t = $wgContLang->normalizeForSearch( $title );
498 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
499 $t = $wgContLang->lc( $t );
502 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
503 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
505 $t = preg_replace( "/\\s+/", ' ', $t );
507 if ( $ns == NS_FILE
) {
508 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
514 * Make a prefixed DB key from a DB key and a namespace index
516 * @param $ns Int numerical representation of the namespace
517 * @param $title String the DB key form the title
518 * @param $fragment String The link fragment (after the "#")
519 * @param $interwiki String The interwiki prefix
520 * @return String the prefixed form of the title
522 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
525 $namespace = $wgContLang->getNsText( $ns );
526 $name = $namespace == '' ?
$title : "$namespace:$title";
527 if ( strval( $interwiki ) != '' ) {
528 $name = "$interwiki:$name";
530 if ( strval( $fragment ) != '' ) {
531 $name .= '#' . $fragment;
537 * Escape a text fragment, say from a link, for a URL
539 * @param $fragment string containing a URL or link fragment (after the "#")
540 * @return String: escaped string
542 static function escapeFragmentForURL( $fragment ) {
543 # Note that we don't urlencode the fragment. urlencoded Unicode
544 # fragments appear not to work in IE (at least up to 7) or in at least
545 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
546 # to care if they aren't encoded.
547 return Sanitizer
::escapeId( $fragment, 'noninitial' );
551 * Callback for usort() to do title sorts by (namespace, title)
556 * @return Integer: result of string comparison, or namespace comparison
558 public static function compare( $a, $b ) {
559 if ( $a->getNamespace() == $b->getNamespace() ) {
560 return strcmp( $a->getText(), $b->getText() );
562 return $a->getNamespace() - $b->getNamespace();
567 * Determine whether the object refers to a page within
570 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
572 public function isLocal() {
573 if ( $this->mInterwiki
!= '' ) {
574 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
581 * Is this Title interwiki?
585 public function isExternal() {
586 return ( $this->mInterwiki
!= '' );
590 * Get the interwiki prefix (or null string)
592 * @return String Interwiki prefix
594 public function getInterwiki() {
595 return $this->mInterwiki
;
599 * Determine whether the object refers to a page within
600 * this project and is transcludable.
602 * @return Bool TRUE if this is transcludable
604 public function isTrans() {
605 if ( $this->mInterwiki
== '' ) {
609 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
613 * Returns the DB name of the distant wiki which owns the object.
615 * @return String the DB name
617 public function getTransWikiID() {
618 if ( $this->mInterwiki
== '' ) {
622 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
626 * Get the text form (spaces not underscores) of the main part
628 * @return String Main part of the title
630 public function getText() {
631 return $this->mTextform
;
635 * Get the URL-encoded form of the main part
637 * @return String Main part of the title, URL-encoded
639 public function getPartialURL() {
640 return $this->mUrlform
;
644 * Get the main part with underscores
646 * @return String: Main part of the title, with underscores
648 public function getDBkey() {
649 return $this->mDbkeyform
;
653 * Get the DB key with the initial letter case as specified by the user
655 * @return String DB key
657 function getUserCaseDBKey() {
658 return $this->mUserCaseDBKey
;
662 * Get the namespace index, i.e. one of the NS_xxxx constants.
664 * @return Integer: Namespace index
666 public function getNamespace() {
667 return $this->mNamespace
;
671 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
673 * @return String: Content model id
675 public function getContentModel() {
676 if ( !$this->mContentModel
) {
677 $linkCache = LinkCache
::singleton();
678 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
681 if ( !$this->mContentModel
) {
682 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
685 if( !$this->mContentModel
) {
686 throw new MWException( "failed to determin content model!" );
689 return $this->mContentModel
;
693 * Convenience method for checking a title's content model name
696 * @return Boolean true if $this->getContentModel() == $id
698 public function hasContentModel( $id ) {
699 return $this->getContentModel() == $id;
703 * Get the namespace text
705 * @return String: Namespace text
707 public function getNsText() {
710 if ( $this->mInterwiki
!= '' ) {
711 // This probably shouldn't even happen. ohh man, oh yuck.
712 // But for interwiki transclusion it sometimes does.
713 // Shit. Shit shit shit.
715 // Use the canonical namespaces if possible to try to
716 // resolve a foreign namespace.
717 if ( MWNamespace
::exists( $this->mNamespace
) ) {
718 return MWNamespace
::getCanonicalName( $this->mNamespace
);
722 if ( $wgContLang->needsGenderDistinction() &&
723 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
724 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
725 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
728 return $wgContLang->getNsText( $this->mNamespace
);
732 * Get the namespace text of the subject (rather than talk) page
734 * @return String Namespace text
736 public function getSubjectNsText() {
738 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
742 * Get the namespace text of the talk page
744 * @return String Namespace text
746 public function getTalkNsText() {
748 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
752 * Could this title have a corresponding talk page?
754 * @return Bool TRUE or FALSE
756 public function canTalk() {
757 return( MWNamespace
::canTalk( $this->mNamespace
) );
761 * Is this in a namespace that allows actual pages?
764 * @internal note -- uses hardcoded namespace index instead of constants
766 public function canExist() {
767 return $this->mNamespace
>= NS_MAIN
;
771 * Can this title be added to a user's watchlist?
773 * @return Bool TRUE or FALSE
775 public function isWatchable() {
776 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
780 * Returns true if this is a special page.
784 public function isSpecialPage() {
785 return $this->getNamespace() == NS_SPECIAL
;
789 * Returns true if this title resolves to the named special page
791 * @param $name String The special page name
794 public function isSpecial( $name ) {
795 if ( $this->isSpecialPage() ) {
796 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
797 if ( $name == $thisName ) {
805 * If the Title refers to a special page alias which is not the local default, resolve
806 * the alias, and localise the name as necessary. Otherwise, return $this
810 public function fixSpecialName() {
811 if ( $this->isSpecialPage() ) {
812 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
813 if ( $canonicalName ) {
814 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
815 if ( $localName != $this->mDbkeyform
) {
816 return Title
::makeTitle( NS_SPECIAL
, $localName );
824 * Returns true if the title is inside the specified namespace.
826 * Please make use of this instead of comparing to getNamespace()
827 * This function is much more resistant to changes we may make
828 * to namespaces than code that makes direct comparisons.
829 * @param $ns int The namespace
833 public function inNamespace( $ns ) {
834 return MWNamespace
::equals( $this->getNamespace(), $ns );
838 * Returns true if the title is inside one of the specified namespaces.
840 * @param ...$namespaces The namespaces to check for
844 public function inNamespaces( /* ... */ ) {
845 $namespaces = func_get_args();
846 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
847 $namespaces = $namespaces[0];
850 foreach ( $namespaces as $ns ) {
851 if ( $this->inNamespace( $ns ) ) {
860 * Returns true if the title has the same subject namespace as the
861 * namespace specified.
862 * For example this method will take NS_USER and return true if namespace
863 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
864 * as their subject namespace.
866 * This is MUCH simpler than individually testing for equivilance
867 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
872 public function hasSubjectNamespace( $ns ) {
873 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
877 * Is this Title in a namespace which contains content?
878 * In other words, is this a content page, for the purposes of calculating
883 public function isContentPage() {
884 return MWNamespace
::isContent( $this->getNamespace() );
888 * Would anybody with sufficient privileges be able to move this page?
889 * Some pages just aren't movable.
891 * @return Bool TRUE or FALSE
893 public function isMovable() {
894 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
895 // Interwiki title or immovable namespace. Hooks don't get to override here
900 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
905 * Is this the mainpage?
906 * @note Title::newFromText seams to be sufficiently optimized by the title
907 * cache that we don't need to over-optimize by doing direct comparisons and
908 * acidentally creating new bugs where $title->equals( Title::newFromText() )
909 * ends up reporting something differently than $title->isMainPage();
914 public function isMainPage() {
915 return $this->equals( Title
::newMainPage() );
923 public function isSubpage() {
924 return MWNamespace
::hasSubpages( $this->mNamespace
)
925 ?
strpos( $this->getText(), '/' ) !== false
930 * Is this a conversion table for the LanguageConverter?
934 public function isConversionTable() {
935 return $this->getNamespace() == NS_MEDIAWIKI
&&
936 strpos( $this->getText(), 'Conversiontable/' ) === 0;
940 * Does that page contain wikitext, or it is JS, CSS or whatever?
944 public function isWikitextPage() {
945 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
949 * Could this page contain custom CSS or JavaScript for the global UI.
950 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
951 * or CONTENT_MODEL_JAVASCRIPT.
953 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
955 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
959 public function isCssOrJsPage() {
960 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
961 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
962 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
964 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
965 # hook funktions can force this method to return true even outside the mediawiki namespace.
967 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
969 return $isCssOrJsPage;
973 * Is this a .css or .js subpage of a user page?
976 public function isCssJsSubpage() {
977 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
978 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
979 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
983 * Trim down a .css or .js subpage title to get the corresponding skin name
985 * @return string containing skin name from .css or .js subpage title
987 public function getSkinFromCssJsSubpage() {
988 $subpage = explode( '/', $this->mTextform
);
989 $subpage = $subpage[ count( $subpage ) - 1 ];
990 $lastdot = strrpos( $subpage, '.' );
991 if ( $lastdot === false )
992 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
993 return substr( $subpage, 0, $lastdot );
997 * Is this a .css subpage of a user page?
1001 public function isCssSubpage() {
1002 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1003 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1007 * Is this a .js subpage of a user page?
1011 public function isJsSubpage() {
1012 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1013 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1017 * Is this a talk page of some sort?
1021 public function isTalkPage() {
1022 return MWNamespace
::isTalk( $this->getNamespace() );
1026 * Get a Title object associated with the talk page of this article
1028 * @return Title the object for the talk page
1030 public function getTalkPage() {
1031 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1035 * Get a title object associated with the subject page of this
1038 * @return Title the object for the subject page
1040 public function getSubjectPage() {
1041 // Is this the same title?
1042 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1043 if ( $this->getNamespace() == $subjectNS ) {
1046 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1050 * Get the default namespace index, for when there is no namespace
1052 * @return Int Default namespace index
1054 public function getDefaultNamespace() {
1055 return $this->mDefaultNamespace
;
1059 * Get title for search index
1061 * @return String a stripped-down title string ready for the
1064 public function getIndexTitle() {
1065 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1069 * Get the Title fragment (i.e.\ the bit after the #) in text form
1071 * @return String Title fragment
1073 public function getFragment() {
1074 return $this->mFragment
;
1078 * Get the fragment in URL form, including the "#" character if there is one
1079 * @return String Fragment in URL form
1081 public function getFragmentForURL() {
1082 if ( $this->mFragment
== '' ) {
1085 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1090 * Set the fragment for this title. Removes the first character from the
1091 * specified fragment before setting, so it assumes you're passing it with
1094 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1095 * Still in active use privately.
1097 * @param $fragment String text
1099 public function setFragment( $fragment ) {
1100 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1104 * Prefix some arbitrary text with the namespace or interwiki prefix
1107 * @param $name String the text
1108 * @return String the prefixed text
1111 private function prefix( $name ) {
1113 if ( $this->mInterwiki
!= '' ) {
1114 $p = $this->mInterwiki
. ':';
1117 if ( 0 != $this->mNamespace
) {
1118 $p .= $this->getNsText() . ':';
1124 * Get the prefixed database key form
1126 * @return String the prefixed title, with underscores and
1127 * any interwiki and namespace prefixes
1129 public function getPrefixedDBkey() {
1130 $s = $this->prefix( $this->mDbkeyform
);
1131 $s = str_replace( ' ', '_', $s );
1136 * Get the prefixed title with spaces.
1137 * This is the form usually used for display
1139 * @return String the prefixed title, with spaces
1141 public function getPrefixedText() {
1142 // @todo FIXME: Bad usage of empty() ?
1143 if ( empty( $this->mPrefixedText
) ) {
1144 $s = $this->prefix( $this->mTextform
);
1145 $s = str_replace( '_', ' ', $s );
1146 $this->mPrefixedText
= $s;
1148 return $this->mPrefixedText
;
1152 * Return a string representation of this title
1154 * @return String representation of this title
1156 public function __toString() {
1157 return $this->getPrefixedText();
1161 * Get the prefixed title with spaces, plus any fragment
1162 * (part beginning with '#')
1164 * @return String the prefixed title, with spaces and the fragment, including '#'
1166 public function getFullText() {
1167 $text = $this->getPrefixedText();
1168 if ( $this->mFragment
!= '' ) {
1169 $text .= '#' . $this->mFragment
;
1175 * Get the base page name, i.e. the leftmost part before any slashes
1177 * @return String Base name
1179 public function getBaseText() {
1180 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1181 return $this->getText();
1184 $parts = explode( '/', $this->getText() );
1185 # Don't discard the real title if there's no subpage involved
1186 if ( count( $parts ) > 1 ) {
1187 unset( $parts[count( $parts ) - 1] );
1189 return implode( '/', $parts );
1193 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1195 * @return String Subpage name
1197 public function getSubpageText() {
1198 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1199 return( $this->mTextform
);
1201 $parts = explode( '/', $this->mTextform
);
1202 return( $parts[count( $parts ) - 1] );
1206 * Get the HTML-escaped displayable text form.
1207 * Used for the title field in <a> tags.
1209 * @return String the text, including any prefixes
1211 public function getEscapedText() {
1212 wfDeprecated( __METHOD__
, '1.19' );
1213 return htmlspecialchars( $this->getPrefixedText() );
1217 * Get a URL-encoded form of the subpage text
1219 * @return String URL-encoded subpage name
1221 public function getSubpageUrlForm() {
1222 $text = $this->getSubpageText();
1223 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1228 * Get a URL-encoded title (not an actual URL) including interwiki
1230 * @return String the URL-encoded form
1232 public function getPrefixedURL() {
1233 $s = $this->prefix( $this->mDbkeyform
);
1234 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1239 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1240 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1241 * second argument named variant. This was deprecated in favor
1242 * of passing an array of option with a "variant" key
1243 * Once $query2 is removed for good, this helper can be dropped
1244 * andthe wfArrayToCGI moved to getLocalURL();
1246 * @since 1.19 (r105919)
1248 * @param $query2 bool
1251 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1252 if( $query2 !== false ) {
1253 wfDeprecated( "Title::get{Canonical,Full,Link,Local} method called with a second parameter is deprecated. Add your parameter to an array passed as the first parameter.", "1.19" );
1255 if ( is_array( $query ) ) {
1256 $query = wfArrayToCGI( $query );
1259 if ( is_string( $query2 ) ) {
1260 // $query2 is a string, we will consider this to be
1261 // a deprecated $variant argument and add it to the query
1262 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1264 $query2 = wfArrayToCGI( $query2 );
1266 // If we have $query content add a & to it first
1270 // Now append the queries together
1277 * Get a real URL referring to this title, with interwiki link and
1280 * See getLocalURL for the arguments.
1282 * @see self::getLocalURL
1284 * @param $proto Protocol type to use in URL
1285 * @return String the URL
1287 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1288 $query = self
::fixUrlQueryArgs( $query, $query2 );
1290 # Hand off all the decisions on urls to getLocalURL
1291 $url = $this->getLocalURL( $query );
1293 # Expand the url to make it a full url. Note that getLocalURL has the
1294 # potential to output full urls for a variety of reasons, so we use
1295 # wfExpandUrl instead of simply prepending $wgServer
1296 $url = wfExpandUrl( $url, $proto );
1298 # Finally, add the fragment.
1299 $url .= $this->getFragmentForURL();
1301 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1306 * Get a URL with no fragment or server name. If this page is generated
1307 * with action=render, $wgServer is prepended.
1310 * @param $query string|array an optional query string,
1311 * not used for interwiki links. Can be specified as an associative array as well,
1312 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1313 * Some query patterns will trigger various shorturl path replacements.
1314 * @param $query2 Mixed: An optional secondary query array. This one MUST
1315 * be an array. If a string is passed it will be interpreted as a deprecated
1316 * variant argument and urlencoded into a variant= argument.
1317 * This second query argument will be added to the $query
1318 * The second parameter is deprecated since 1.19. Pass it as a key,value
1319 * pair in the first parameter array instead.
1321 * @return String the URL
1323 public function getLocalURL( $query = '', $query2 = false ) {
1324 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1326 $query = self
::fixUrlQueryArgs( $query, $query2 );
1328 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1330 $namespace = $this->getNsText();
1331 if ( $namespace != '' ) {
1332 # Can this actually happen? Interwikis shouldn't be parsed.
1333 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1336 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1337 $url = wfAppendQuery( $url, $query );
1339 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1340 if ( $query == '' ) {
1341 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1342 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1344 global $wgVariantArticlePath, $wgActionPaths;
1348 if ( !empty( $wgActionPaths ) &&
1349 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1351 $action = urldecode( $matches[2] );
1352 if ( isset( $wgActionPaths[$action] ) ) {
1353 $query = $matches[1];
1354 if ( isset( $matches[4] ) ) {
1355 $query .= $matches[4];
1357 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1358 if ( $query != '' ) {
1359 $url = wfAppendQuery( $url, $query );
1364 if ( $url === false &&
1365 $wgVariantArticlePath &&
1366 $this->getPageLanguage()->hasVariants() &&
1367 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1369 $variant = urldecode( $matches[1] );
1370 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1371 // Only do the variant replacement if the given variant is a valid
1372 // variant for the page's language.
1373 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1374 $url = str_replace( '$1', $dbkey, $url );
1378 if ( $url === false ) {
1379 if ( $query == '-' ) {
1382 $url = "{$wgScript}?title={$dbkey}&{$query}";
1386 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1388 // @todo FIXME: This causes breakage in various places when we
1389 // actually expected a local URL and end up with dupe prefixes.
1390 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1391 $url = $wgServer . $url;
1394 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1399 * Get a URL that's the simplest URL that will be valid to link, locally,
1400 * to the current Title. It includes the fragment, but does not include
1401 * the server unless action=render is used (or the link is external). If
1402 * there's a fragment but the prefixed text is empty, we just return a link
1405 * The result obviously should not be URL-escaped, but does need to be
1406 * HTML-escaped if it's being output in HTML.
1408 * See getLocalURL for the arguments.
1410 * @see self::getLocalURL
1411 * @return String the URL
1413 public function getLinkURL( $query = '', $query2 = false ) {
1414 wfProfileIn( __METHOD__
);
1415 if ( $this->isExternal() ) {
1416 $ret = $this->getFullURL( $query, $query2 );
1417 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1418 $ret = $this->getFragmentForURL();
1420 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1422 wfProfileOut( __METHOD__
);
1427 * Get an HTML-escaped version of the URL form, suitable for
1428 * using in a link, without a server name or fragment
1430 * See getLocalURL for the arguments.
1432 * @see self::getLocalURL
1433 * @param $query string
1434 * @param $query2 bool|string
1435 * @return String the URL
1437 public function escapeLocalURL( $query = '', $query2 = false ) {
1438 wfDeprecated( __METHOD__
, '1.19' );
1439 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1443 * Get an HTML-escaped version of the URL form, suitable for
1444 * using in a link, including the server name and fragment
1446 * See getLocalURL for the arguments.
1448 * @see self::getLocalURL
1449 * @return String the URL
1451 public function escapeFullURL( $query = '', $query2 = false ) {
1452 wfDeprecated( __METHOD__
, '1.19' );
1453 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1457 * Get the URL form for an internal link.
1458 * - Used in various Squid-related code, in case we have a different
1459 * internal hostname for the server from the exposed one.
1461 * This uses $wgInternalServer to qualify the path, or $wgServer
1462 * if $wgInternalServer is not set. If the server variable used is
1463 * protocol-relative, the URL will be expanded to http://
1465 * See getLocalURL for the arguments.
1467 * @see self::getLocalURL
1468 * @return String the URL
1470 public function getInternalURL( $query = '', $query2 = false ) {
1471 global $wgInternalServer, $wgServer;
1472 $query = self
::fixUrlQueryArgs( $query, $query2 );
1473 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1474 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1475 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1480 * Get the URL for a canonical link, for use in things like IRC and
1481 * e-mail notifications. Uses $wgCanonicalServer and the
1482 * GetCanonicalURL hook.
1484 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1486 * See getLocalURL for the arguments.
1488 * @see self::getLocalURL
1489 * @return string The URL
1492 public function getCanonicalURL( $query = '', $query2 = false ) {
1493 $query = self
::fixUrlQueryArgs( $query, $query2 );
1494 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1495 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1500 * HTML-escaped version of getCanonicalURL()
1502 * See getLocalURL for the arguments.
1504 * @see self::getLocalURL
1508 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1509 wfDeprecated( __METHOD__
, '1.19' );
1510 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1514 * Get the edit URL for this Title
1516 * @return String the URL, or a null string if this is an
1519 public function getEditURL() {
1520 if ( $this->mInterwiki
!= '' ) {
1523 $s = $this->getLocalURL( 'action=edit' );
1529 * Is $wgUser watching this page?
1531 * @deprecated in 1.20; use User::isWatched() instead.
1534 public function userIsWatching() {
1537 if ( is_null( $this->mWatched
) ) {
1538 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1539 $this->mWatched
= false;
1541 $this->mWatched
= $wgUser->isWatched( $this );
1544 return $this->mWatched
;
1548 * Can $wgUser read this page?
1550 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1552 * @todo fold these checks into userCan()
1554 public function userCanRead() {
1555 wfDeprecated( __METHOD__
, '1.19' );
1556 return $this->userCan( 'read' );
1560 * Can $user perform $action on this page?
1561 * This skips potentially expensive cascading permission checks
1562 * as well as avoids expensive error formatting
1564 * Suitable for use for nonessential UI controls in common cases, but
1565 * _not_ for functional access control.
1567 * May provide false positives, but should never provide a false negative.
1569 * @param $action String action that permission needs to be checked for
1570 * @param $user User to check (since 1.19); $wgUser will be used if not
1574 public function quickUserCan( $action, $user = null ) {
1575 return $this->userCan( $action, $user, false );
1579 * Can $user perform $action on this page?
1581 * @param $action String action that permission needs to be checked for
1582 * @param $user User to check (since 1.19); $wgUser will be used if not
1584 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1585 * unnecessary queries.
1588 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1589 if ( !$user instanceof User
) {
1593 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1597 * Can $user perform $action on this page?
1599 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1601 * @param $action String action that permission needs to be checked for
1602 * @param $user User to check
1603 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1604 * queries by skipping checks for cascading protections and user blocks.
1605 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1606 * whose corresponding errors may be ignored.
1607 * @return Array of arguments to wfMessage to explain permissions problems.
1609 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1610 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1612 // Remove the errors being ignored.
1613 foreach ( $errors as $index => $error ) {
1614 $error_key = is_array( $error ) ?
$error[0] : $error;
1616 if ( in_array( $error_key, $ignoreErrors ) ) {
1617 unset( $errors[$index] );
1625 * Permissions checks that fail most often, and which are easiest to test.
1627 * @param $action String the action to check
1628 * @param $user User user to check
1629 * @param $errors Array list of current errors
1630 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1631 * @param $short Boolean short circuit on first error
1633 * @return Array list of errors
1635 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1636 if ( $action == 'create' ) {
1637 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1638 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1639 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1641 } elseif ( $action == 'move' ) {
1642 if ( !$user->isAllowed( 'move-rootuserpages' )
1643 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1644 // Show user page-specific message only if the user can move other pages
1645 $errors[] = array( 'cant-move-user-page' );
1648 // Check if user is allowed to move files if it's a file
1649 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1650 $errors[] = array( 'movenotallowedfile' );
1653 if ( !$user->isAllowed( 'move' ) ) {
1654 // User can't move anything
1655 global $wgGroupPermissions;
1656 $userCanMove = false;
1657 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1658 $userCanMove = $wgGroupPermissions['user']['move'];
1660 $autoconfirmedCanMove = false;
1661 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1662 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1664 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1665 // custom message if logged-in users without any special rights can move
1666 $errors[] = array( 'movenologintext' );
1668 $errors[] = array( 'movenotallowed' );
1671 } elseif ( $action == 'move-target' ) {
1672 if ( !$user->isAllowed( 'move' ) ) {
1673 // User can't move anything
1674 $errors[] = array( 'movenotallowed' );
1675 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1676 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1677 // Show user page-specific message only if the user can move other pages
1678 $errors[] = array( 'cant-move-to-user-page' );
1680 } elseif ( !$user->isAllowed( $action ) ) {
1681 $errors[] = $this->missingPermissionError( $action, $short );
1688 * Add the resulting error code to the errors array
1690 * @param $errors Array list of current errors
1691 * @param $result Mixed result of errors
1693 * @return Array list of errors
1695 private function resultToError( $errors, $result ) {
1696 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1697 // A single array representing an error
1698 $errors[] = $result;
1699 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1700 // A nested array representing multiple errors
1701 $errors = array_merge( $errors, $result );
1702 } elseif ( $result !== '' && is_string( $result ) ) {
1703 // A string representing a message-id
1704 $errors[] = array( $result );
1705 } elseif ( $result === false ) {
1706 // a generic "We don't want them to do that"
1707 $errors[] = array( 'badaccess-group0' );
1713 * Check various permission hooks
1715 * @param $action String the action to check
1716 * @param $user User user to check
1717 * @param $errors Array list of current errors
1718 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1719 * @param $short Boolean short circuit on first error
1721 * @return Array list of errors
1723 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1724 // Use getUserPermissionsErrors instead
1726 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1727 return $result ?
array() : array( array( 'badaccess-group0' ) );
1729 // Check getUserPermissionsErrors hook
1730 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1731 $errors = $this->resultToError( $errors, $result );
1733 // Check getUserPermissionsErrorsExpensive hook
1734 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1735 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1736 $errors = $this->resultToError( $errors, $result );
1743 * Check permissions on special pages & namespaces
1745 * @param $action String the action to check
1746 * @param $user User user to check
1747 * @param $errors Array list of current errors
1748 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1749 * @param $short Boolean short circuit on first error
1751 * @return Array list of errors
1753 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1754 # Only 'createaccount' and 'execute' can be performed on
1755 # special pages, which don't actually exist in the DB.
1756 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1757 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1758 $errors[] = array( 'ns-specialprotected' );
1761 # Check $wgNamespaceProtection for restricted namespaces
1762 if ( $this->isNamespaceProtected( $user ) ) {
1763 $ns = $this->mNamespace
== NS_MAIN ?
1764 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1765 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1766 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1773 * Check CSS/JS sub-page permissions
1775 * @param $action String the action to check
1776 * @param $user User user to check
1777 * @param $errors Array list of current errors
1778 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1779 * @param $short Boolean short circuit on first error
1781 * @return Array list of errors
1783 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1784 # Protect css/js subpages of user pages
1785 # XXX: this might be better using restrictions
1786 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1787 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1788 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1789 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1790 $errors[] = array( 'customcssprotected' );
1791 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1792 $errors[] = array( 'customjsprotected' );
1800 * Check against page_restrictions table requirements on this
1801 * page. The user must possess all required rights for this
1804 * @param $action String the action to check
1805 * @param $user User user to check
1806 * @param $errors Array list of current errors
1807 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1808 * @param $short Boolean short circuit on first error
1810 * @return Array list of errors
1812 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1813 foreach ( $this->getRestrictions( $action ) as $right ) {
1814 // Backwards compatibility, rewrite sysop -> protect
1815 if ( $right == 'sysop' ) {
1818 if ( $right != '' && !$user->isAllowed( $right ) ) {
1819 // Users with 'editprotected' permission can edit protected pages
1820 // without cascading option turned on.
1821 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1822 ||
$this->mCascadeRestriction
)
1824 $errors[] = array( 'protectedpagetext', $right );
1833 * Check restrictions on cascading pages.
1835 * @param $action String the action to check
1836 * @param $user User to check
1837 * @param $errors Array list of current errors
1838 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1839 * @param $short Boolean short circuit on first error
1841 * @return Array list of errors
1843 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1844 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1845 # We /could/ use the protection level on the source page, but it's
1846 # fairly ugly as we have to establish a precedence hierarchy for pages
1847 # included by multiple cascade-protected pages. So just restrict
1848 # it to people with 'protect' permission, as they could remove the
1849 # protection anyway.
1850 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1851 # Cascading protection depends on more than this page...
1852 # Several cascading protected pages may include this page...
1853 # Check each cascading level
1854 # This is only for protection restrictions, not for all actions
1855 if ( isset( $restrictions[$action] ) ) {
1856 foreach ( $restrictions[$action] as $right ) {
1857 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1858 if ( $right != '' && !$user->isAllowed( $right ) ) {
1860 foreach ( $cascadingSources as $page )
1861 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1862 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1872 * Check action permissions not already checked in checkQuickPermissions
1874 * @param $action String the action to check
1875 * @param $user User to check
1876 * @param $errors Array list of current errors
1877 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1878 * @param $short Boolean short circuit on first error
1880 * @return Array list of errors
1882 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1883 global $wgDeleteRevisionsLimit, $wgLang;
1885 if ( $action == 'protect' ) {
1886 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1887 // If they can't edit, they shouldn't protect.
1888 $errors[] = array( 'protect-cantedit' );
1890 } elseif ( $action == 'create' ) {
1891 $title_protection = $this->getTitleProtection();
1892 if( $title_protection ) {
1893 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1894 $title_protection['pt_create_perm'] = 'protect'; // B/C
1896 if( $title_protection['pt_create_perm'] == '' ||
1897 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1899 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1902 } elseif ( $action == 'move' ) {
1903 // Check for immobile pages
1904 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1905 // Specific message for this case
1906 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1907 } elseif ( !$this->isMovable() ) {
1908 // Less specific message for rarer cases
1909 $errors[] = array( 'immobile-source-page' );
1911 } elseif ( $action == 'move-target' ) {
1912 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1913 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1914 } elseif ( !$this->isMovable() ) {
1915 $errors[] = array( 'immobile-target-page' );
1917 } elseif ( $action == 'delete' ) {
1918 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1919 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1921 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1928 * Check that the user isn't blocked from editting.
1930 * @param $action String the action to check
1931 * @param $user User to check
1932 * @param $errors Array list of current errors
1933 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1934 * @param $short Boolean short circuit on first error
1936 * @return Array list of errors
1938 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1939 // Account creation blocks handled at userlogin.
1940 // Unblocking handled in SpecialUnblock
1941 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1945 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1947 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1948 $errors[] = array( 'confirmedittext' );
1951 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1952 // Don't block the user from editing their own talk page unless they've been
1953 // explicitly blocked from that too.
1954 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1955 $block = $user->getBlock();
1957 // This is from OutputPage::blockedPage
1958 // Copied at r23888 by werdna
1960 $id = $user->blockedBy();
1961 $reason = $user->blockedFor();
1962 if ( $reason == '' ) {
1963 $reason = wfMessage( 'blockednoreason' )->text();
1965 $ip = $user->getRequest()->getIP();
1967 if ( is_numeric( $id ) ) {
1968 $name = User
::whoIs( $id );
1973 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1974 $blockid = $block->getId();
1975 $blockExpiry = $block->getExpiry();
1976 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1977 if ( $blockExpiry == 'infinity' ) {
1978 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1980 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1983 $intended = strval( $block->getTarget() );
1985 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1986 $blockid, $blockExpiry, $intended, $blockTimestamp );
1993 * Check that the user is allowed to read this page.
1995 * @param $action String the action to check
1996 * @param $user User to check
1997 * @param $errors Array list of current errors
1998 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1999 * @param $short Boolean short circuit on first error
2001 * @return Array list of errors
2003 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2004 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2005 static $useShortcut = null;
2007 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2008 if ( is_null( $useShortcut ) ) {
2009 $useShortcut = true;
2010 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2011 # Not a public wiki, so no shortcut
2012 $useShortcut = false;
2013 } elseif ( !empty( $wgRevokePermissions ) ) {
2015 * Iterate through each group with permissions being revoked (key not included since we don't care
2016 * what the group name is), then check if the read permission is being revoked. If it is, then
2017 * we don't use the shortcut below since the user might not be able to read, even though anon
2018 * reading is allowed.
2020 foreach ( $wgRevokePermissions as $perms ) {
2021 if ( !empty( $perms['read'] ) ) {
2022 # We might be removing the read right from the user, so no shortcut
2023 $useShortcut = false;
2030 $whitelisted = false;
2031 if ( $useShortcut ) {
2032 # Shortcut for public wikis, allows skipping quite a bit of code
2033 $whitelisted = true;
2034 } elseif ( $user->isAllowed( 'read' ) ) {
2035 # If the user is allowed to read pages, he is allowed to read all pages
2036 $whitelisted = true;
2037 } elseif ( $this->isSpecial( 'Userlogin' )
2038 ||
$this->isSpecial( 'ChangePassword' )
2039 ||
$this->isSpecial( 'PasswordReset' )
2041 # Always grant access to the login page.
2042 # Even anons need to be able to log in.
2043 $whitelisted = true;
2044 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2045 # Time to check the whitelist
2046 # Only do these checks is there's something to check against
2047 $name = $this->getPrefixedText();
2048 $dbName = $this->getPrefixedDBKey();
2050 // Check for explicit whitelisting with and without underscores
2051 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2052 $whitelisted = true;
2053 } elseif ( $this->getNamespace() == NS_MAIN
) {
2054 # Old settings might have the title prefixed with
2055 # a colon for main-namespace pages
2056 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2057 $whitelisted = true;
2059 } elseif ( $this->isSpecialPage() ) {
2060 # If it's a special page, ditch the subpage bit and check again
2061 $name = $this->getDBkey();
2062 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2063 if ( $name !== false ) {
2064 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2065 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2066 $whitelisted = true;
2072 if ( !$whitelisted ) {
2073 # If the title is not whitelisted, give extensions a chance to do so...
2074 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2075 if ( !$whitelisted ) {
2076 $errors[] = $this->missingPermissionError( $action, $short );
2084 * Get a description array when the user doesn't have the right to perform
2085 * $action (i.e. when User::isAllowed() returns false)
2087 * @param $action String the action to check
2088 * @param $short Boolean short circuit on first error
2089 * @return Array list of errors
2091 private function missingPermissionError( $action, $short ) {
2092 // We avoid expensive display logic for quickUserCan's and such
2094 return array( 'badaccess-group0' );
2097 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2098 User
::getGroupsWithPermission( $action ) );
2100 if ( count( $groups ) ) {
2104 $wgLang->commaList( $groups ),
2108 return array( 'badaccess-group0' );
2113 * Can $user perform $action on this page? This is an internal function,
2114 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2115 * checks on wfReadOnly() and blocks)
2117 * @param $action String action that permission needs to be checked for
2118 * @param $user User to check
2119 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2120 * @param $short Bool Set this to true to stop after the first permission error.
2121 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2123 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2124 wfProfileIn( __METHOD__
);
2126 # Read has special handling
2127 if ( $action == 'read' ) {
2129 'checkPermissionHooks',
2130 'checkReadPermissions',
2134 'checkQuickPermissions',
2135 'checkPermissionHooks',
2136 'checkSpecialsAndNSPermissions',
2137 'checkCSSandJSPermissions',
2138 'checkPageRestrictions',
2139 'checkCascadingSourcesRestrictions',
2140 'checkActionPermissions',
2146 while( count( $checks ) > 0 &&
2147 !( $short && count( $errors ) > 0 ) ) {
2148 $method = array_shift( $checks );
2149 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2152 wfProfileOut( __METHOD__
);
2157 * Protect css subpages of user pages: can $wgUser edit
2160 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2163 public function userCanEditCssSubpage() {
2165 wfDeprecated( __METHOD__
, '1.19' );
2166 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2167 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2171 * Protect js subpages of user pages: can $wgUser edit
2174 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2177 public function userCanEditJsSubpage() {
2179 wfDeprecated( __METHOD__
, '1.19' );
2180 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2181 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2185 * Get a filtered list of all restriction types supported by this wiki.
2186 * @param bool $exists True to get all restriction types that apply to
2187 * titles that do exist, False for all restriction types that apply to
2188 * titles that do not exist
2191 public static function getFilteredRestrictionTypes( $exists = true ) {
2192 global $wgRestrictionTypes;
2193 $types = $wgRestrictionTypes;
2195 # Remove the create restriction for existing titles
2196 $types = array_diff( $types, array( 'create' ) );
2198 # Only the create and upload restrictions apply to non-existing titles
2199 $types = array_intersect( $types, array( 'create', 'upload' ) );
2205 * Returns restriction types for the current Title
2207 * @return array applicable restriction types
2209 public function getRestrictionTypes() {
2210 if ( $this->isSpecialPage() ) {
2214 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2216 if ( $this->getNamespace() != NS_FILE
) {
2217 # Remove the upload restriction for non-file titles
2218 $types = array_diff( $types, array( 'upload' ) );
2221 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2223 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2224 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2230 * Is this title subject to title protection?
2231 * Title protection is the one applied against creation of such title.
2233 * @return Mixed An associative array representing any existent title
2234 * protection, or false if there's none.
2236 private function getTitleProtection() {
2237 // Can't protect pages in special namespaces
2238 if ( $this->getNamespace() < 0 ) {
2242 // Can't protect pages that exist.
2243 if ( $this->exists() ) {
2247 if ( !isset( $this->mTitleProtection
) ) {
2248 $dbr = wfGetDB( DB_SLAVE
);
2249 $res = $dbr->select( 'protected_titles', '*',
2250 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2253 // fetchRow returns false if there are no rows.
2254 $this->mTitleProtection
= $dbr->fetchRow( $res );
2256 return $this->mTitleProtection
;
2260 * Update the title protection status
2262 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2263 * @param $create_perm String Permission required for creation
2264 * @param $reason String Reason for protection
2265 * @param $expiry String Expiry timestamp
2266 * @return boolean true
2268 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2269 wfDeprecated( __METHOD__
, '1.19' );
2273 $limit = array( 'create' => $create_perm );
2274 $expiry = array( 'create' => $expiry );
2276 $page = WikiPage
::factory( $this );
2277 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2279 return $status->isOK();
2283 * Remove any title protection due to page existing
2285 public function deleteTitleProtection() {
2286 $dbw = wfGetDB( DB_MASTER
);
2290 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2293 $this->mTitleProtection
= false;
2297 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2299 * @param $action String Action to check (default: edit)
2302 public function isSemiProtected( $action = 'edit' ) {
2303 if ( $this->exists() ) {
2304 $restrictions = $this->getRestrictions( $action );
2305 if ( count( $restrictions ) > 0 ) {
2306 foreach ( $restrictions as $restriction ) {
2307 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2317 # If it doesn't exist, it can't be protected
2323 * Does the title correspond to a protected article?
2325 * @param $action String the action the page is protected from,
2326 * by default checks all actions.
2329 public function isProtected( $action = '' ) {
2330 global $wgRestrictionLevels;
2332 $restrictionTypes = $this->getRestrictionTypes();
2334 # Special pages have inherent protection
2335 if( $this->isSpecialPage() ) {
2339 # Check regular protection levels
2340 foreach ( $restrictionTypes as $type ) {
2341 if ( $action == $type ||
$action == '' ) {
2342 $r = $this->getRestrictions( $type );
2343 foreach ( $wgRestrictionLevels as $level ) {
2344 if ( in_array( $level, $r ) && $level != '' ) {
2355 * Determines if $user is unable to edit this page because it has been protected
2356 * by $wgNamespaceProtection.
2358 * @param $user User object to check permissions
2361 public function isNamespaceProtected( User
$user ) {
2362 global $wgNamespaceProtection;
2364 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2365 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2366 if ( $right != '' && !$user->isAllowed( $right ) ) {
2375 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2377 * @return Bool If the page is subject to cascading restrictions.
2379 public function isCascadeProtected() {
2380 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2381 return ( $sources > 0 );
2385 * Cascading protection: Get the source of any cascading restrictions on this page.
2387 * @param $getPages Bool Whether or not to retrieve the actual pages
2388 * that the restrictions have come from.
2389 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2390 * have come, false for none, or true if such restrictions exist, but $getPages
2391 * was not set. The restriction array is an array of each type, each of which
2392 * contains a array of unique groups.
2394 public function getCascadeProtectionSources( $getPages = true ) {
2396 $pagerestrictions = array();
2398 if ( isset( $this->mCascadeSources
) && $getPages ) {
2399 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2400 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2401 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2404 wfProfileIn( __METHOD__
);
2406 $dbr = wfGetDB( DB_SLAVE
);
2408 if ( $this->getNamespace() == NS_FILE
) {
2409 $tables = array( 'imagelinks', 'page_restrictions' );
2410 $where_clauses = array(
2411 'il_to' => $this->getDBkey(),
2416 $tables = array( 'templatelinks', 'page_restrictions' );
2417 $where_clauses = array(
2418 'tl_namespace' => $this->getNamespace(),
2419 'tl_title' => $this->getDBkey(),
2426 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2427 'pr_expiry', 'pr_type', 'pr_level' );
2428 $where_clauses[] = 'page_id=pr_page';
2431 $cols = array( 'pr_expiry' );
2434 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2436 $sources = $getPages ?
array() : false;
2437 $now = wfTimestampNow();
2438 $purgeExpired = false;
2440 foreach ( $res as $row ) {
2441 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2442 if ( $expiry > $now ) {
2444 $page_id = $row->pr_page
;
2445 $page_ns = $row->page_namespace
;
2446 $page_title = $row->page_title
;
2447 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2448 # Add groups needed for each restriction type if its not already there
2449 # Make sure this restriction type still exists
2451 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2452 $pagerestrictions[$row->pr_type
] = array();
2455 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2456 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2457 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2463 // Trigger lazy purge of expired restrictions from the db
2464 $purgeExpired = true;
2467 if ( $purgeExpired ) {
2468 Title
::purgeExpiredRestrictions();
2472 $this->mCascadeSources
= $sources;
2473 $this->mCascadingRestrictions
= $pagerestrictions;
2475 $this->mHasCascadingRestrictions
= $sources;
2478 wfProfileOut( __METHOD__
);
2479 return array( $sources, $pagerestrictions );
2483 * Accessor/initialisation for mRestrictions
2485 * @param $action String action that permission needs to be checked for
2486 * @return Array of Strings the array of groups allowed to edit this article
2488 public function getRestrictions( $action ) {
2489 if ( !$this->mRestrictionsLoaded
) {
2490 $this->loadRestrictions();
2492 return isset( $this->mRestrictions
[$action] )
2493 ?
$this->mRestrictions
[$action]
2498 * Get the expiry time for the restriction against a given action
2501 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2502 * or not protected at all, or false if the action is not recognised.
2504 public function getRestrictionExpiry( $action ) {
2505 if ( !$this->mRestrictionsLoaded
) {
2506 $this->loadRestrictions();
2508 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2512 * Returns cascading restrictions for the current article
2516 function areRestrictionsCascading() {
2517 if ( !$this->mRestrictionsLoaded
) {
2518 $this->loadRestrictions();
2521 return $this->mCascadeRestriction
;
2525 * Loads a string into mRestrictions array
2527 * @param $res Resource restrictions as an SQL result.
2528 * @param $oldFashionedRestrictions String comma-separated list of page
2529 * restrictions from page table (pre 1.10)
2531 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2534 foreach ( $res as $row ) {
2538 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2542 * Compiles list of active page restrictions from both page table (pre 1.10)
2543 * and page_restrictions table for this existing page.
2544 * Public for usage by LiquidThreads.
2546 * @param $rows array of db result objects
2547 * @param $oldFashionedRestrictions string comma-separated list of page
2548 * restrictions from page table (pre 1.10)
2550 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2552 $dbr = wfGetDB( DB_SLAVE
);
2554 $restrictionTypes = $this->getRestrictionTypes();
2556 foreach ( $restrictionTypes as $type ) {
2557 $this->mRestrictions
[$type] = array();
2558 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2561 $this->mCascadeRestriction
= false;
2563 # Backwards-compatibility: also load the restrictions from the page record (old format).
2565 if ( $oldFashionedRestrictions === null ) {
2566 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2567 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2570 if ( $oldFashionedRestrictions != '' ) {
2572 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2573 $temp = explode( '=', trim( $restrict ) );
2574 if ( count( $temp ) == 1 ) {
2575 // old old format should be treated as edit/move restriction
2576 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2577 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2579 $restriction = trim( $temp[1] );
2580 if( $restriction != '' ) { //some old entries are empty
2581 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2586 $this->mOldRestrictions
= true;
2590 if ( count( $rows ) ) {
2591 # Current system - load second to make them override.
2592 $now = wfTimestampNow();
2593 $purgeExpired = false;
2595 # Cycle through all the restrictions.
2596 foreach ( $rows as $row ) {
2598 // Don't take care of restrictions types that aren't allowed
2599 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2602 // This code should be refactored, now that it's being used more generally,
2603 // But I don't really see any harm in leaving it in Block for now -werdna
2604 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2606 // Only apply the restrictions if they haven't expired!
2607 if ( !$expiry ||
$expiry > $now ) {
2608 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2609 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2611 $this->mCascadeRestriction |
= $row->pr_cascade
;
2613 // Trigger a lazy purge of expired restrictions
2614 $purgeExpired = true;
2618 if ( $purgeExpired ) {
2619 Title
::purgeExpiredRestrictions();
2623 $this->mRestrictionsLoaded
= true;
2627 * Load restrictions from the page_restrictions table
2629 * @param $oldFashionedRestrictions String comma-separated list of page
2630 * restrictions from page table (pre 1.10)
2632 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2634 if ( !$this->mRestrictionsLoaded
) {
2635 if ( $this->exists() ) {
2636 $dbr = wfGetDB( DB_SLAVE
);
2638 $res = $dbr->select(
2639 'page_restrictions',
2641 array( 'pr_page' => $this->getArticleID() ),
2645 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2647 $title_protection = $this->getTitleProtection();
2649 if ( $title_protection ) {
2650 $now = wfTimestampNow();
2651 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2653 if ( !$expiry ||
$expiry > $now ) {
2654 // Apply the restrictions
2655 $this->mRestrictionsExpiry
['create'] = $expiry;
2656 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2657 } else { // Get rid of the old restrictions
2658 Title
::purgeExpiredRestrictions();
2659 $this->mTitleProtection
= false;
2662 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2664 $this->mRestrictionsLoaded
= true;
2670 * Flush the protection cache in this object and force reload from the database.
2671 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2673 public function flushRestrictions() {
2674 $this->mRestrictionsLoaded
= false;
2675 $this->mTitleProtection
= null;
2679 * Purge expired restrictions from the page_restrictions table
2681 static function purgeExpiredRestrictions() {
2682 $dbw = wfGetDB( DB_MASTER
);
2684 'page_restrictions',
2685 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2691 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2697 * Does this have subpages? (Warning, usually requires an extra DB query.)
2701 public function hasSubpages() {
2702 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2707 # We dynamically add a member variable for the purpose of this method
2708 # alone to cache the result. There's no point in having it hanging
2709 # around uninitialized in every Title object; therefore we only add it
2710 # if needed and don't declare it statically.
2711 if ( isset( $this->mHasSubpages
) ) {
2712 return $this->mHasSubpages
;
2715 $subpages = $this->getSubpages( 1 );
2716 if ( $subpages instanceof TitleArray
) {
2717 return $this->mHasSubpages
= (bool)$subpages->count();
2719 return $this->mHasSubpages
= false;
2723 * Get all subpages of this page.
2725 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2726 * @return mixed TitleArray, or empty array if this page's namespace
2727 * doesn't allow subpages
2729 public function getSubpages( $limit = -1 ) {
2730 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2734 $dbr = wfGetDB( DB_SLAVE
);
2735 $conds['page_namespace'] = $this->getNamespace();
2736 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2738 if ( $limit > -1 ) {
2739 $options['LIMIT'] = $limit;
2741 return $this->mSubpages
= TitleArray
::newFromResult(
2742 $dbr->select( 'page',
2743 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2752 * Is there a version of this page in the deletion archive?
2754 * @return Int the number of archived revisions
2756 public function isDeleted() {
2757 if ( $this->getNamespace() < 0 ) {
2760 $dbr = wfGetDB( DB_SLAVE
);
2762 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2763 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2766 if ( $this->getNamespace() == NS_FILE
) {
2767 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2768 array( 'fa_name' => $this->getDBkey() ),
2777 * Is there a version of this page in the deletion archive?
2781 public function isDeletedQuick() {
2782 if ( $this->getNamespace() < 0 ) {
2785 $dbr = wfGetDB( DB_SLAVE
);
2786 $deleted = (bool)$dbr->selectField( 'archive', '1',
2787 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2790 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2791 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2792 array( 'fa_name' => $this->getDBkey() ),
2800 * Get the article ID for this Title from the link cache,
2801 * adding it if necessary
2803 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2805 * @return Int the ID
2807 public function getArticleID( $flags = 0 ) {
2808 if ( $this->getNamespace() < 0 ) {
2809 return $this->mArticleID
= 0;
2811 $linkCache = LinkCache
::singleton();
2812 if ( $flags & self
::GAID_FOR_UPDATE
) {
2813 $oldUpdate = $linkCache->forUpdate( true );
2814 $linkCache->clearLink( $this );
2815 $this->mArticleID
= $linkCache->addLinkObj( $this );
2816 $linkCache->forUpdate( $oldUpdate );
2818 if ( -1 == $this->mArticleID
) {
2819 $this->mArticleID
= $linkCache->addLinkObj( $this );
2822 return $this->mArticleID
;
2826 * Is this an article that is a redirect page?
2827 * Uses link cache, adding it if necessary
2829 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2832 public function isRedirect( $flags = 0 ) {
2833 if ( !is_null( $this->mRedirect
) ) {
2834 return $this->mRedirect
;
2836 # Calling getArticleID() loads the field from cache as needed
2837 if ( !$this->getArticleID( $flags ) ) {
2838 return $this->mRedirect
= false;
2841 $linkCache = LinkCache
::singleton();
2842 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2843 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2844 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2845 # as a stop gap, perhaps log this, but don't throw an exception?
2846 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2849 $this->mRedirect
= (bool)$cached;
2851 return $this->mRedirect
;
2855 * What is the length of this page?
2856 * Uses link cache, adding it if necessary
2858 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2861 public function getLength( $flags = 0 ) {
2862 if ( $this->mLength
!= -1 ) {
2863 return $this->mLength
;
2865 # Calling getArticleID() loads the field from cache as needed
2866 if ( !$this->getArticleID( $flags ) ) {
2867 return $this->mLength
= 0;
2869 $linkCache = LinkCache
::singleton();
2870 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2871 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2872 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2873 # as a stop gap, perhaps log this, but don't throw an exception?
2874 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2877 $this->mLength
= intval( $cached );
2879 return $this->mLength
;
2883 * What is the page_latest field for this page?
2885 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2886 * @return Int or 0 if the page doesn't exist
2888 public function getLatestRevID( $flags = 0 ) {
2889 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
2890 return intval( $this->mLatestID
);
2892 # Calling getArticleID() loads the field from cache as needed
2893 if ( !$this->getArticleID( $flags ) ) {
2894 return $this->mLatestID
= 0;
2896 $linkCache = LinkCache
::singleton();
2897 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2898 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
2899 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2900 # as a stop gap, perhaps log this, but don't throw an exception?
2901 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2904 $this->mLatestID
= intval( $cached );
2906 return $this->mLatestID
;
2910 * This clears some fields in this object, and clears any associated
2911 * keys in the "bad links" section of the link cache.
2913 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2914 * loading of the new page_id. It's also called from
2915 * WikiPage::doDeleteArticleReal()
2917 * @param $newid Int the new Article ID
2919 public function resetArticleID( $newid ) {
2920 $linkCache = LinkCache
::singleton();
2921 $linkCache->clearLink( $this );
2923 if ( $newid === false ) {
2924 $this->mArticleID
= -1;
2926 $this->mArticleID
= intval( $newid );
2928 $this->mRestrictionsLoaded
= false;
2929 $this->mRestrictions
= array();
2930 $this->mRedirect
= null;
2931 $this->mLength
= -1;
2932 $this->mLatestID
= false;
2933 $this->mContentModel
= false;
2934 $this->mEstimateRevisions
= null;
2938 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2940 * @param $text String containing title to capitalize
2941 * @param $ns int namespace index, defaults to NS_MAIN
2942 * @return String containing capitalized title
2944 public static function capitalize( $text, $ns = NS_MAIN
) {
2947 if ( MWNamespace
::isCapitalized( $ns ) ) {
2948 return $wgContLang->ucfirst( $text );
2955 * Secure and split - main initialisation function for this object
2957 * Assumes that mDbkeyform has been set, and is urldecoded
2958 * and uses underscores, but not otherwise munged. This function
2959 * removes illegal characters, splits off the interwiki and
2960 * namespace prefixes, sets the other forms, and canonicalizes
2963 * @return Bool true on success
2965 private function secureAndSplit() {
2966 global $wgContLang, $wgLocalInterwiki;
2969 $this->mInterwiki
= $this->mFragment
= '';
2970 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2972 $dbkey = $this->mDbkeyform
;
2974 # Strip Unicode bidi override characters.
2975 # Sometimes they slip into cut-n-pasted page titles, where the
2976 # override chars get included in list displays.
2977 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2979 # Clean up whitespace
2980 # Note: use of the /u option on preg_replace here will cause
2981 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2982 # conveniently disabling them.
2983 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2984 $dbkey = trim( $dbkey, '_' );
2986 if ( $dbkey == '' ) {
2990 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2991 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2995 $this->mDbkeyform
= $dbkey;
2997 # Initial colon indicates main namespace rather than specified default
2998 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2999 if ( ':' == $dbkey[0] ) {
3000 $this->mNamespace
= NS_MAIN
;
3001 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3002 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3005 # Namespace or interwiki prefix
3007 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3010 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3012 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3013 # Ordinary namespace
3015 $this->mNamespace
= $ns;
3016 # For Talk:X pages, check if X has a "namespace" prefix
3017 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3018 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3019 # Disallow Talk:File:x type titles...
3021 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3022 # Disallow Talk:Interwiki:x type titles...
3026 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3027 if ( !$firstPass ) {
3028 # Can't make a local interwiki link to an interwiki link.
3029 # That's just crazy!
3035 $this->mInterwiki
= $wgContLang->lc( $p );
3037 # Redundant interwiki prefix to the local wiki
3038 if ( $wgLocalInterwiki !== false
3039 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3041 if ( $dbkey == '' ) {
3042 # Can't have an empty self-link
3045 $this->mInterwiki
= '';
3047 # Do another namespace split...
3051 # If there's an initial colon after the interwiki, that also
3052 # resets the default namespace
3053 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3054 $this->mNamespace
= NS_MAIN
;
3055 $dbkey = substr( $dbkey, 1 );
3058 # If there's no recognized interwiki or namespace,
3059 # then let the colon expression be part of the title.
3064 # We already know that some pages won't be in the database!
3065 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3066 $this->mArticleID
= 0;
3068 $fragment = strstr( $dbkey, '#' );
3069 if ( false !== $fragment ) {
3070 $this->setFragment( $fragment );
3071 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3072 # remove whitespace again: prevents "Foo_bar_#"
3073 # becoming "Foo_bar_"
3074 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3077 # Reject illegal characters.
3078 $rxTc = self
::getTitleInvalidRegex();
3079 if ( preg_match( $rxTc, $dbkey ) ) {
3083 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3084 # reachable due to the way web browsers deal with 'relative' URLs.
3085 # Also, they conflict with subpage syntax. Forbid them explicitly.
3086 if ( strpos( $dbkey, '.' ) !== false &&
3087 ( $dbkey === '.' ||
$dbkey === '..' ||
3088 strpos( $dbkey, './' ) === 0 ||
3089 strpos( $dbkey, '../' ) === 0 ||
3090 strpos( $dbkey, '/./' ) !== false ||
3091 strpos( $dbkey, '/../' ) !== false ||
3092 substr( $dbkey, -2 ) == '/.' ||
3093 substr( $dbkey, -3 ) == '/..' ) )
3098 # Magic tilde sequences? Nu-uh!
3099 if ( strpos( $dbkey, '~~~' ) !== false ) {
3103 # Limit the size of titles to 255 bytes. This is typically the size of the
3104 # underlying database field. We make an exception for special pages, which
3105 # don't need to be stored in the database, and may edge over 255 bytes due
3106 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3107 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3108 strlen( $dbkey ) > 512 )
3113 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3114 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3115 # other site might be case-sensitive.
3116 $this->mUserCaseDBKey
= $dbkey;
3117 if ( $this->mInterwiki
== '' ) {
3118 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3121 # Can't make a link to a namespace alone... "empty" local links can only be
3122 # self-links with a fragment identifier.
3123 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3127 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3128 // IP names are not allowed for accounts, and can only be referring to
3129 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3130 // there are numerous ways to present the same IP. Having sp:contribs scan
3131 // them all is silly and having some show the edits and others not is
3132 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3133 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3134 ? IP
::sanitizeIP( $dbkey )
3137 // Any remaining initial :s are illegal.
3138 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3143 $this->mDbkeyform
= $dbkey;
3144 $this->mUrlform
= wfUrlencode( $dbkey );
3146 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3152 * Get an array of Title objects linking to this Title
3153 * Also stores the IDs in the link cache.
3155 * WARNING: do not use this function on arbitrary user-supplied titles!
3156 * On heavily-used templates it will max out the memory.
3158 * @param $options Array: may be FOR UPDATE
3159 * @param $table String: table name
3160 * @param $prefix String: fields prefix
3161 * @return Array of Title objects linking here
3163 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3164 if ( count( $options ) > 0 ) {
3165 $db = wfGetDB( DB_MASTER
);
3167 $db = wfGetDB( DB_SLAVE
);
3171 array( 'page', $table ),
3172 self
::getSelectFields(),
3174 "{$prefix}_from=page_id",
3175 "{$prefix}_namespace" => $this->getNamespace(),
3176 "{$prefix}_title" => $this->getDBkey() ),
3182 if ( $res->numRows() ) {
3183 $linkCache = LinkCache
::singleton();
3184 foreach ( $res as $row ) {
3185 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3187 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3188 $retVal[] = $titleObj;
3196 * Get an array of Title objects using this Title as a template
3197 * Also stores the IDs in the link cache.
3199 * WARNING: do not use this function on arbitrary user-supplied titles!
3200 * On heavily-used templates it will max out the memory.
3202 * @param $options Array: may be FOR UPDATE
3203 * @return Array of Title the Title objects linking here
3205 public function getTemplateLinksTo( $options = array() ) {
3206 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3210 * Get an array of Title objects linked from this Title
3211 * Also stores the IDs in the link cache.
3213 * WARNING: do not use this function on arbitrary user-supplied titles!
3214 * On heavily-used templates it will max out the memory.
3216 * @param $options Array: may be FOR UPDATE
3217 * @param $table String: table name
3218 * @param $prefix String: fields prefix
3219 * @return Array of Title objects linking here
3221 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3222 global $wgContentHandlerUseDB;
3224 $id = $this->getArticleID();
3226 # If the page doesn't exist; there can't be any link from this page
3231 if ( count( $options ) > 0 ) {
3232 $db = wfGetDB( DB_MASTER
);
3234 $db = wfGetDB( DB_SLAVE
);
3237 $namespaceFiled = "{$prefix}_namespace";
3238 $titleField = "{$prefix}_title";
3240 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3241 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3244 array( $table, 'page' ),
3246 array( "{$prefix}_from" => $id ),
3249 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3253 if ( $res->numRows() ) {
3254 $linkCache = LinkCache
::singleton();
3255 foreach ( $res as $row ) {
3256 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3258 if ( $row->page_id
) {
3259 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3261 $linkCache->addBadLinkObj( $titleObj );
3263 $retVal[] = $titleObj;
3271 * Get an array of Title objects used on this Title as a template
3272 * Also stores the IDs in the link cache.
3274 * WARNING: do not use this function on arbitrary user-supplied titles!
3275 * On heavily-used templates it will max out the memory.
3277 * @param $options Array: may be FOR UPDATE
3278 * @return Array of Title the Title objects used here
3280 public function getTemplateLinksFrom( $options = array() ) {
3281 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3285 * Get an array of Title objects referring to non-existent articles linked from this page
3287 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3288 * @return Array of Title the Title objects
3290 public function getBrokenLinksFrom() {
3291 if ( $this->getArticleID() == 0 ) {
3292 # All links from article ID 0 are false positives
3296 $dbr = wfGetDB( DB_SLAVE
);
3297 $res = $dbr->select(
3298 array( 'page', 'pagelinks' ),
3299 array( 'pl_namespace', 'pl_title' ),
3301 'pl_from' => $this->getArticleID(),
3302 'page_namespace IS NULL'
3304 __METHOD__
, array(),
3308 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3314 foreach ( $res as $row ) {
3315 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3322 * Get a list of URLs to purge from the Squid cache when this
3325 * @return Array of String the URLs
3327 public function getSquidURLs() {
3329 $this->getInternalURL(),
3330 $this->getInternalURL( 'action=history' )
3333 $pageLang = $this->getPageLanguage();
3334 if ( $pageLang->hasVariants() ) {
3335 $variants = $pageLang->getVariants();
3336 foreach ( $variants as $vCode ) {
3337 $urls[] = $this->getInternalURL( '', $vCode );
3345 * Purge all applicable Squid URLs
3347 public function purgeSquid() {
3349 if ( $wgUseSquid ) {
3350 $urls = $this->getSquidURLs();
3351 $u = new SquidUpdate( $urls );
3357 * Move this page without authentication
3359 * @param $nt Title the new page Title
3360 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3362 public function moveNoAuth( &$nt ) {
3363 return $this->moveTo( $nt, false );
3367 * Check whether a given move operation would be valid.
3368 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3370 * @param $nt Title the new title
3371 * @param $auth Bool indicates whether $wgUser's permissions
3373 * @param $reason String is the log summary of the move, used for spam checking
3374 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3376 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3381 // Normally we'd add this to $errors, but we'll get
3382 // lots of syntax errors if $nt is not an object
3383 return array( array( 'badtitletext' ) );
3385 if ( $this->equals( $nt ) ) {
3386 $errors[] = array( 'selfmove' );
3388 if ( !$this->isMovable() ) {
3389 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3391 if ( $nt->getInterwiki() != '' ) {
3392 $errors[] = array( 'immobile-target-namespace-iw' );
3394 if ( !$nt->isMovable() ) {
3395 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3398 $oldid = $this->getArticleID();
3399 $newid = $nt->getArticleID();
3401 if ( strlen( $nt->getDBkey() ) < 1 ) {
3402 $errors[] = array( 'articleexists' );
3404 if ( ( $this->getDBkey() == '' ) ||
3406 ( $nt->getDBkey() == '' ) ) {
3407 $errors[] = array( 'badarticleerror' );
3410 // Image-specific checks
3411 if ( $this->getNamespace() == NS_FILE
) {
3412 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3415 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3416 $errors[] = array( 'nonfile-cannot-move-to-file' );
3420 $errors = wfMergeErrorArrays( $errors,
3421 $this->getUserPermissionsErrors( 'move', $wgUser ),
3422 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3423 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3424 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3427 $match = EditPage
::matchSummarySpamRegex( $reason );
3428 if ( $match !== false ) {
3429 // This is kind of lame, won't display nice
3430 $errors[] = array( 'spamprotectiontext' );
3434 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3435 $errors[] = array( 'hookaborted', $err );
3438 # The move is allowed only if (1) the target doesn't exist, or
3439 # (2) the target is a redirect to the source, and has no history
3440 # (so we can undo bad moves right after they're done).
3442 if ( 0 != $newid ) { # Target exists; check for validity
3443 if ( !$this->isValidMoveTarget( $nt ) ) {
3444 $errors[] = array( 'articleexists' );
3447 $tp = $nt->getTitleProtection();
3448 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3449 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3450 $errors[] = array( 'cantmove-titleprotected' );
3453 if ( empty( $errors ) ) {
3460 * Check if the requested move target is a valid file move target
3461 * @param Title $nt Target title
3462 * @return array List of errors
3464 protected function validateFileMoveOperation( $nt ) {
3469 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3471 $file = wfLocalFile( $this );
3472 if ( $file->exists() ) {
3473 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3474 $errors[] = array( 'imageinvalidfilename' );
3476 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3477 $errors[] = array( 'imagetypemismatch' );
3481 if ( $nt->getNamespace() != NS_FILE
) {
3482 $errors[] = array( 'imagenocrossnamespace' );
3483 // From here we want to do checks on a file object, so if we can't
3484 // create one, we must return.
3488 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3490 $destFile = wfLocalFile( $nt );
3491 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3492 $errors[] = array( 'file-exists-sharedrepo' );
3499 * Move a title to a new location
3501 * @param $nt Title the new title
3502 * @param $auth Bool indicates whether $wgUser's permissions
3504 * @param $reason String the reason for the move
3505 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3506 * Ignored if the user doesn't have the suppressredirect right.
3507 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3509 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3511 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3512 if ( is_array( $err ) ) {
3513 // Auto-block user's IP if the account was "hard" blocked
3514 $wgUser->spreadAnyEditBlock();
3517 // Check suppressredirect permission
3518 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3519 $createRedirect = true;
3522 // If it is a file, move it first.
3523 // It is done before all other moving stuff is done because it's hard to revert.
3524 $dbw = wfGetDB( DB_MASTER
);
3525 if ( $this->getNamespace() == NS_FILE
) {
3526 $file = wfLocalFile( $this );
3527 if ( $file->exists() ) {
3528 $status = $file->move( $nt );
3529 if ( !$status->isOk() ) {
3530 return $status->getErrorsArray();
3533 // Clear RepoGroup process cache
3534 RepoGroup
::singleton()->clearCache( $this );
3535 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3538 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3539 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3540 $protected = $this->isProtected();
3542 // Do the actual move
3543 $this->moveToInternal( $nt, $reason, $createRedirect );
3545 // Refresh the sortkey for this row. Be careful to avoid resetting
3546 // cl_timestamp, which may disturb time-based lists on some sites.
3547 $prefixes = $dbw->select(
3549 array( 'cl_sortkey_prefix', 'cl_to' ),
3550 array( 'cl_from' => $pageid ),
3553 foreach ( $prefixes as $prefixRow ) {
3554 $prefix = $prefixRow->cl_sortkey_prefix
;
3555 $catTo = $prefixRow->cl_to
;
3556 $dbw->update( 'categorylinks',
3558 'cl_sortkey' => Collation
::singleton()->getSortKey(
3559 $nt->getCategorySortkey( $prefix ) ),
3560 'cl_timestamp=cl_timestamp' ),
3562 'cl_from' => $pageid,
3563 'cl_to' => $catTo ),
3568 $redirid = $this->getArticleID();
3571 # Protect the redirect title as the title used to be...
3572 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3574 'pr_page' => $redirid,
3575 'pr_type' => 'pr_type',
3576 'pr_level' => 'pr_level',
3577 'pr_cascade' => 'pr_cascade',
3578 'pr_user' => 'pr_user',
3579 'pr_expiry' => 'pr_expiry'
3581 array( 'pr_page' => $pageid ),
3585 # Update the protection log
3586 $log = new LogPage( 'protect' );
3587 $comment = wfMessage(
3589 $this->getPrefixedText(),
3590 $nt->getPrefixedText()
3591 )->inContentLanguage()->text();
3593 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3595 // @todo FIXME: $params?
3596 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3600 $oldnamespace = $this->getNamespace() & ~
1;
3601 $newnamespace = $nt->getNamespace() & ~
1;
3602 $oldtitle = $this->getDBkey();
3603 $newtitle = $nt->getDBkey();
3605 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3606 WatchedItem
::duplicateEntries( $this, $nt );
3609 $dbw->commit( __METHOD__
);
3611 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3616 * Move page to a title which is either a redirect to the
3617 * source page or nonexistent
3619 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3620 * @param $reason String The reason for the move
3621 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3622 * if the user has the suppressredirect right
3623 * @throws MWException
3625 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3626 global $wgUser, $wgContLang;
3628 if ( $nt->exists() ) {
3629 $moveOverRedirect = true;
3630 $logType = 'move_redir';
3632 $moveOverRedirect = false;
3636 $redirectSuppressed = !$createRedirect;
3638 $logEntry = new ManualLogEntry( 'move', $logType );
3639 $logEntry->setPerformer( $wgUser );
3640 $logEntry->setTarget( $this );
3641 $logEntry->setComment( $reason );
3642 $logEntry->setParameters( array(
3643 '4::target' => $nt->getPrefixedText(),
3644 '5::noredir' => $redirectSuppressed ?
'1': '0',
3647 $formatter = LogFormatter
::newFromEntry( $logEntry );
3648 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3649 $comment = $formatter->getPlainActionText();
3651 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3653 # Truncate for whole multibyte characters.
3654 $comment = $wgContLang->truncate( $comment, 255 );
3656 $oldid = $this->getArticleID();
3658 $dbw = wfGetDB( DB_MASTER
);
3660 $newpage = WikiPage
::factory( $nt );
3662 if ( $moveOverRedirect ) {
3663 $newid = $nt->getArticleID();
3665 # Delete the old redirect. We don't save it to history since
3666 # by definition if we've got here it's rather uninteresting.
3667 # We have to remove it so that the next step doesn't trigger
3668 # a conflict on the unique namespace+title index...
3669 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3671 $newpage->doDeleteUpdates( $newid );
3674 # Save a null revision in the page's history notifying of the move
3675 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3676 if ( !is_object( $nullRevision ) ) {
3677 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3679 $nullRevId = $nullRevision->insertOn( $dbw );
3681 # Change the name of the target page:
3682 $dbw->update( 'page',
3684 'page_namespace' => $nt->getNamespace(),
3685 'page_title' => $nt->getDBkey(),
3687 /* WHERE */ array( 'page_id' => $oldid ),
3691 $this->resetArticleID( 0 );
3692 $nt->resetArticleID( $oldid );
3694 $newpage->updateRevisionOn( $dbw, $nullRevision );
3696 wfRunHooks( 'NewRevisionFromEditComplete',
3697 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3699 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3701 if ( !$moveOverRedirect ) {
3702 WikiPage
::onArticleCreate( $nt );
3705 # Recreate the redirect, this time in the other direction.
3706 if ( $redirectSuppressed ) {
3707 WikiPage
::onArticleDelete( $this );
3709 $mwRedir = MagicWord
::get( 'redirect' );
3710 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3711 $redirectArticle = WikiPage
::factory( $this );
3712 $newid = $redirectArticle->insertOn( $dbw );
3713 if ( $newid ) { // sanity
3714 $redirectRevision = new Revision( array(
3716 'comment' => $comment,
3717 'text' => $redirectText ) );
3718 $redirectRevision->insertOn( $dbw );
3719 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3721 wfRunHooks( 'NewRevisionFromEditComplete',
3722 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3724 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3729 $logid = $logEntry->insert();
3730 $logEntry->publish( $logid );
3734 * Move this page's subpages to be subpages of $nt
3736 * @param $nt Title Move target
3737 * @param $auth bool Whether $wgUser's permissions should be checked
3738 * @param $reason string The reason for the move
3739 * @param $createRedirect bool Whether to create redirects from the old subpages to
3740 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3741 * @return mixed array with old page titles as keys, and strings (new page titles) or
3742 * arrays (errors) as values, or an error array with numeric indices if no pages
3745 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3746 global $wgMaximumMovedPages;
3747 // Check permissions
3748 if ( !$this->userCan( 'move-subpages' ) ) {
3749 return array( 'cant-move-subpages' );
3751 // Do the source and target namespaces support subpages?
3752 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3753 return array( 'namespace-nosubpages',
3754 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3756 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3757 return array( 'namespace-nosubpages',
3758 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3761 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3764 foreach ( $subpages as $oldSubpage ) {
3766 if ( $count > $wgMaximumMovedPages ) {
3767 $retval[$oldSubpage->getPrefixedTitle()] =
3768 array( 'movepage-max-pages',
3769 $wgMaximumMovedPages );
3773 // We don't know whether this function was called before
3774 // or after moving the root page, so check both
3776 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3777 $oldSubpage->getArticleID() == $nt->getArticleID() )
3779 // When moving a page to a subpage of itself,
3780 // don't move it twice
3783 $newPageName = preg_replace(
3784 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3785 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3786 $oldSubpage->getDBkey() );
3787 if ( $oldSubpage->isTalkPage() ) {
3788 $newNs = $nt->getTalkPage()->getNamespace();
3790 $newNs = $nt->getSubjectPage()->getNamespace();
3792 # Bug 14385: we need makeTitleSafe because the new page names may
3793 # be longer than 255 characters.
3794 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3796 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3797 if ( $success === true ) {
3798 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3800 $retval[$oldSubpage->getPrefixedText()] = $success;
3807 * Checks if this page is just a one-rev redirect.
3808 * Adds lock, so don't use just for light purposes.
3812 public function isSingleRevRedirect() {
3813 global $wgContentHandlerUseDB;
3815 $dbw = wfGetDB( DB_MASTER
);
3818 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3819 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3821 $row = $dbw->selectRow( 'page',
3825 array( 'FOR UPDATE' )
3827 # Cache some fields we may want
3828 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3829 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3830 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3831 $this->mContentModel
= $row && isset( $row->page_content_model
) ?
strval( $row->page_content_model
) : false;
3832 if ( !$this->mRedirect
) {
3835 # Does the article have a history?
3836 $row = $dbw->selectField( array( 'page', 'revision' ),
3838 array( 'page_namespace' => $this->getNamespace(),
3839 'page_title' => $this->getDBkey(),
3841 'page_latest != rev_id'
3844 array( 'FOR UPDATE' )
3846 # Return true if there was no history
3847 return ( $row === false );
3851 * Checks if $this can be moved to a given Title
3852 * - Selects for update, so don't call it unless you mean business
3854 * @param $nt Title the new title to check
3857 public function isValidMoveTarget( $nt ) {
3858 # Is it an existing file?
3859 if ( $nt->getNamespace() == NS_FILE
) {
3860 $file = wfLocalFile( $nt );
3861 if ( $file->exists() ) {
3862 wfDebug( __METHOD__
. ": file exists\n" );
3866 # Is it a redirect with no history?
3867 if ( !$nt->isSingleRevRedirect() ) {
3868 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3871 # Get the article text
3872 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3873 if( !is_object( $rev ) ){
3876 $content = $rev->getContent();
3877 # Does the redirect point to the source?
3878 # Or is it a broken self-redirect, usually caused by namespace collisions?
3879 $redirTitle = $content->getRedirectTarget();
3881 if ( $redirTitle ) {
3882 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3883 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3884 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3890 # Fail safe (not a redirect after all. strange.)
3891 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3892 " is a redirect, but it doesn't contain a valid redirect.\n" );
3898 * Get categories to which this Title belongs and return an array of
3899 * categories' names.
3901 * @return Array of parents in the form:
3902 * $parent => $currentarticle
3904 public function getParentCategories() {
3909 $titleKey = $this->getArticleID();
3911 if ( $titleKey === 0 ) {
3915 $dbr = wfGetDB( DB_SLAVE
);
3917 $res = $dbr->select( 'categorylinks', '*',
3919 'cl_from' => $titleKey,
3925 if ( $dbr->numRows( $res ) > 0 ) {
3926 foreach ( $res as $row ) {
3927 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3928 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3935 * Get a tree of parent categories
3937 * @param $children Array with the children in the keys, to check for circular refs
3938 * @return Array Tree of parent categories
3940 public function getParentCategoryTree( $children = array() ) {
3942 $parents = $this->getParentCategories();
3945 foreach ( $parents as $parent => $current ) {
3946 if ( array_key_exists( $parent, $children ) ) {
3947 # Circular reference
3948 $stack[$parent] = array();
3950 $nt = Title
::newFromText( $parent );
3952 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3962 * Get an associative array for selecting this title from
3965 * @return Array suitable for the $where parameter of DB::select()
3967 public function pageCond() {
3968 if ( $this->mArticleID
> 0 ) {
3969 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3970 return array( 'page_id' => $this->mArticleID
);
3972 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3977 * Get the revision ID of the previous revision
3979 * @param $revId Int Revision ID. Get the revision that was before this one.
3980 * @param $flags Int Title::GAID_FOR_UPDATE
3981 * @return Int|Bool Old revision ID, or FALSE if none exists
3983 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3984 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3985 $revId = $db->selectField( 'revision', 'rev_id',
3987 'rev_page' => $this->getArticleID( $flags ),
3988 'rev_id < ' . intval( $revId )
3991 array( 'ORDER BY' => 'rev_id DESC' )
3994 if ( $revId === false ) {
3997 return intval( $revId );
4002 * Get the revision ID of the next revision
4004 * @param $revId Int Revision ID. Get the revision that was after this one.
4005 * @param $flags Int Title::GAID_FOR_UPDATE
4006 * @return Int|Bool Next revision ID, or FALSE if none exists
4008 public function getNextRevisionID( $revId, $flags = 0 ) {
4009 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4010 $revId = $db->selectField( 'revision', 'rev_id',
4012 'rev_page' => $this->getArticleID( $flags ),
4013 'rev_id > ' . intval( $revId )
4016 array( 'ORDER BY' => 'rev_id' )
4019 if ( $revId === false ) {
4022 return intval( $revId );
4027 * Get the first revision of the page
4029 * @param $flags Int Title::GAID_FOR_UPDATE
4030 * @return Revision|Null if page doesn't exist
4032 public function getFirstRevision( $flags = 0 ) {
4033 $pageId = $this->getArticleID( $flags );
4035 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4036 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4037 array( 'rev_page' => $pageId ),
4039 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4042 return new Revision( $row );
4049 * Get the oldest revision timestamp of this page
4051 * @param $flags Int Title::GAID_FOR_UPDATE
4052 * @return String: MW timestamp
4054 public function getEarliestRevTime( $flags = 0 ) {
4055 $rev = $this->getFirstRevision( $flags );
4056 return $rev ?
$rev->getTimestamp() : null;
4060 * Check if this is a new page
4064 public function isNewPage() {
4065 $dbr = wfGetDB( DB_SLAVE
);
4066 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4070 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4074 public function isBigDeletion() {
4075 global $wgDeleteRevisionsLimit;
4077 if ( !$wgDeleteRevisionsLimit ) {
4081 $revCount = $this->estimateRevisionCount();
4082 return $revCount > $wgDeleteRevisionsLimit;
4086 * Get the approximate revision count of this page.
4090 public function estimateRevisionCount() {
4091 if ( !$this->exists() ) {
4095 if ( $this->mEstimateRevisions
=== null ) {
4096 $dbr = wfGetDB( DB_SLAVE
);
4097 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4098 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4101 return $this->mEstimateRevisions
;
4105 * Get the number of revisions between the given revision.
4106 * Used for diffs and other things that really need it.
4108 * @param $old int|Revision Old revision or rev ID (first before range)
4109 * @param $new int|Revision New revision or rev ID (first after range)
4110 * @return Int Number of revisions between these revisions.
4112 public function countRevisionsBetween( $old, $new ) {
4113 if ( !( $old instanceof Revision
) ) {
4114 $old = Revision
::newFromTitle( $this, (int)$old );
4116 if ( !( $new instanceof Revision
) ) {
4117 $new = Revision
::newFromTitle( $this, (int)$new );
4119 if ( !$old ||
!$new ) {
4120 return 0; // nothing to compare
4122 $dbr = wfGetDB( DB_SLAVE
);
4123 return (int)$dbr->selectField( 'revision', 'count(*)',
4125 'rev_page' => $this->getArticleID(),
4126 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4127 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4134 * Get the number of authors between the given revisions or revision IDs.
4135 * Used for diffs and other things that really need it.
4137 * @param $old int|Revision Old revision or rev ID (first before range by default)
4138 * @param $new int|Revision New revision or rev ID (first after range by default)
4139 * @param $limit int Maximum number of authors
4140 * @param $options string|array (Optional): Single option, or an array of options:
4141 * 'include_old' Include $old in the range; $new is excluded.
4142 * 'include_new' Include $new in the range; $old is excluded.
4143 * 'include_both' Include both $old and $new in the range.
4144 * Unknown option values are ignored.
4145 * @return int Number of revision authors in the range; zero if not both revisions exist
4147 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4148 if ( !( $old instanceof Revision
) ) {
4149 $old = Revision
::newFromTitle( $this, (int)$old );
4151 if ( !( $new instanceof Revision
) ) {
4152 $new = Revision
::newFromTitle( $this, (int)$new );
4154 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4155 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4156 // in the sanity check below?
4157 if ( !$old ||
!$new ) {
4158 return 0; // nothing to compare
4162 $options = (array) $options;
4163 if ( in_array( 'include_old', $options ) ) {
4166 if ( in_array( 'include_new', $options ) ) {
4169 if ( in_array( 'include_both', $options ) ) {
4173 // No DB query needed if $old and $new are the same or successive revisions:
4174 if ( $old->getId() === $new->getId() ) {
4175 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4176 } else if ( $old->getId() === $new->getParentId() ) {
4177 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4178 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4180 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4182 $dbr = wfGetDB( DB_SLAVE
);
4183 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4185 'rev_page' => $this->getArticleID(),
4186 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4187 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4189 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4191 return (int)$dbr->numRows( $res );
4195 * Compare with another title.
4197 * @param $title Title
4200 public function equals( Title
$title ) {
4201 // Note: === is necessary for proper matching of number-like titles.
4202 return $this->getInterwiki() === $title->getInterwiki()
4203 && $this->getNamespace() == $title->getNamespace()
4204 && $this->getDBkey() === $title->getDBkey();
4208 * Check if this title is a subpage of another title
4210 * @param $title Title
4213 public function isSubpageOf( Title
$title ) {
4214 return $this->getInterwiki() === $title->getInterwiki()
4215 && $this->getNamespace() == $title->getNamespace()
4216 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4220 * Check if page exists. For historical reasons, this function simply
4221 * checks for the existence of the title in the page table, and will
4222 * thus return false for interwiki links, special pages and the like.
4223 * If you want to know if a title can be meaningfully viewed, you should
4224 * probably call the isKnown() method instead.
4228 public function exists() {
4229 return $this->getArticleID() != 0;
4233 * Should links to this title be shown as potentially viewable (i.e. as
4234 * "bluelinks"), even if there's no record by this title in the page
4237 * This function is semi-deprecated for public use, as well as somewhat
4238 * misleadingly named. You probably just want to call isKnown(), which
4239 * calls this function internally.
4241 * (ISSUE: Most of these checks are cheap, but the file existence check
4242 * can potentially be quite expensive. Including it here fixes a lot of
4243 * existing code, but we might want to add an optional parameter to skip
4244 * it and any other expensive checks.)
4248 public function isAlwaysKnown() {
4252 * Allows overriding default behaviour for determining if a page exists.
4253 * If $isKnown is kept as null, regular checks happen. If it's
4254 * a boolean, this value is returned by the isKnown method.
4258 * @param Title $title
4259 * @param boolean|null $isKnown
4261 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4263 if ( !is_null( $isKnown ) ) {
4267 if ( $this->mInterwiki
!= '' ) {
4268 return true; // any interwiki link might be viewable, for all we know
4271 switch( $this->mNamespace
) {
4274 // file exists, possibly in a foreign repo
4275 return (bool)wfFindFile( $this );
4277 // valid special page
4278 return SpecialPageFactory
::exists( $this->getDBkey() );
4280 // selflink, possibly with fragment
4281 return $this->mDbkeyform
== '';
4283 // known system message
4284 return $this->hasSourceText() !== false;
4291 * Does this title refer to a page that can (or might) be meaningfully
4292 * viewed? In particular, this function may be used to determine if
4293 * links to the title should be rendered as "bluelinks" (as opposed to
4294 * "redlinks" to non-existent pages).
4295 * Adding something else to this function will cause inconsistency
4296 * since LinkHolderArray calls isAlwaysKnown() and does its own
4297 * page existence check.
4301 public function isKnown() {
4302 return $this->isAlwaysKnown() ||
$this->exists();
4306 * Does this page have source text?
4310 public function hasSourceText() {
4311 if ( $this->exists() ) {
4315 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4316 // If the page doesn't exist but is a known system message, default
4317 // message content will be displayed, same for language subpages-
4318 // Use always content language to avoid loading hundreds of languages
4319 // to get the link color.
4321 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4322 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4323 return $message->exists();
4330 * Get the default message text or false if the message doesn't exist
4332 * @return String or false
4334 public function getDefaultMessageText() {
4337 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4341 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4342 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4344 if ( $message->exists() ) {
4345 return $message->plain();
4352 * Updates page_touched for this page; called from LinksUpdate.php
4354 * @return Bool true if the update succeded
4356 public function invalidateCache() {
4357 if ( wfReadOnly() ) {
4360 $dbw = wfGetDB( DB_MASTER
);
4361 $success = $dbw->update(
4363 array( 'page_touched' => $dbw->timestamp() ),
4367 HTMLFileCache
::clearFileCache( $this );
4372 * Update page_touched timestamps and send squid purge messages for
4373 * pages linking to this title. May be sent to the job queue depending
4374 * on the number of links. Typically called on create and delete.
4376 public function touchLinks() {
4377 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4380 if ( $this->getNamespace() == NS_CATEGORY
) {
4381 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4387 * Get the last touched timestamp
4389 * @param $db DatabaseBase: optional db
4390 * @return String last-touched timestamp
4392 public function getTouched( $db = null ) {
4393 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4394 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4399 * Get the timestamp when this page was updated since the user last saw it.
4402 * @return String|Null
4404 public function getNotificationTimestamp( $user = null ) {
4405 global $wgUser, $wgShowUpdatedMarker;
4406 // Assume current user if none given
4410 // Check cache first
4411 $uid = $user->getId();
4412 // avoid isset here, as it'll return false for null entries
4413 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4414 return $this->mNotificationTimestamp
[$uid];
4416 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4417 return $this->mNotificationTimestamp
[$uid] = false;
4419 // Don't cache too much!
4420 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4421 $this->mNotificationTimestamp
= array();
4423 $dbr = wfGetDB( DB_SLAVE
);
4424 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4425 'wl_notificationtimestamp',
4427 'wl_user' => $user->getId(),
4428 'wl_namespace' => $this->getNamespace(),
4429 'wl_title' => $this->getDBkey(),
4433 return $this->mNotificationTimestamp
[$uid];
4437 * Generate strings used for xml 'id' names in monobook tabs
4439 * @param $prepend string defaults to 'nstab-'
4440 * @return String XML 'id' name
4442 public function getNamespaceKey( $prepend = 'nstab-' ) {
4444 // Gets the subject namespace if this title
4445 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4446 // Checks if cononical namespace name exists for namespace
4447 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4448 // Uses canonical namespace name
4449 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4451 // Uses text of namespace
4452 $namespaceKey = $this->getSubjectNsText();
4454 // Makes namespace key lowercase
4455 $namespaceKey = $wgContLang->lc( $namespaceKey );
4457 if ( $namespaceKey == '' ) {
4458 $namespaceKey = 'main';
4460 // Changes file to image for backwards compatibility
4461 if ( $namespaceKey == 'file' ) {
4462 $namespaceKey = 'image';
4464 return $prepend . $namespaceKey;
4468 * Get all extant redirects to this Title
4470 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4471 * @return Array of Title redirects to this title
4473 public function getRedirectsHere( $ns = null ) {
4476 $dbr = wfGetDB( DB_SLAVE
);
4478 'rd_namespace' => $this->getNamespace(),
4479 'rd_title' => $this->getDBkey(),
4482 if ( !is_null( $ns ) ) {
4483 $where['page_namespace'] = $ns;
4486 $res = $dbr->select(
4487 array( 'redirect', 'page' ),
4488 array( 'page_namespace', 'page_title' ),
4493 foreach ( $res as $row ) {
4494 $redirs[] = self
::newFromRow( $row );
4500 * Check if this Title is a valid redirect target
4504 public function isValidRedirectTarget() {
4505 global $wgInvalidRedirectTargets;
4507 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4508 if ( $this->isSpecial( 'Userlogout' ) ) {
4512 foreach ( $wgInvalidRedirectTargets as $target ) {
4513 if ( $this->isSpecial( $target ) ) {
4522 * Get a backlink cache object
4524 * @return BacklinkCache
4526 function getBacklinkCache() {
4527 if ( is_null( $this->mBacklinkCache
) ) {
4528 $this->mBacklinkCache
= new BacklinkCache( $this );
4530 return $this->mBacklinkCache
;
4534 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4538 public function canUseNoindex() {
4539 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4541 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4542 ?
$wgContentNamespaces
4543 : $wgExemptFromUserRobotsControl;
4545 return !in_array( $this->mNamespace
, $bannedNamespaces );
4550 * Returns the raw sort key to be used for categories, with the specified
4551 * prefix. This will be fed to Collation::getSortKey() to get a
4552 * binary sortkey that can be used for actual sorting.
4554 * @param $prefix string The prefix to be used, specified using
4555 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4559 public function getCategorySortkey( $prefix = '' ) {
4560 $unprefixed = $this->getText();
4562 // Anything that uses this hook should only depend
4563 // on the Title object passed in, and should probably
4564 // tell the users to run updateCollations.php --force
4565 // in order to re-sort existing category relations.
4566 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4567 if ( $prefix !== '' ) {
4568 # Separate with a line feed, so the unprefixed part is only used as
4569 # a tiebreaker when two pages have the exact same prefix.
4570 # In UCA, tab is the only character that can sort above LF
4571 # so we strip both of them from the original prefix.
4572 $prefix = strtr( $prefix, "\n\t", ' ' );
4573 return "$prefix\n$unprefixed";
4579 * Get the language in which the content of this page is written in
4580 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4581 * e.g. $wgLang (such as special pages, which are in the user language).
4586 public function getPageLanguage() {
4588 if ( $this->isSpecialPage() ) {
4589 // special pages are in the user language
4591 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4592 // Parse mediawiki messages with correct target language
4593 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4594 return wfGetLangObj( $lang );
4597 //TODO: use the LinkCache to cache this!
4598 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4599 $contentHandler = ContentHandler
::getForTitle( $this );
4600 $pageLang = $contentHandler->getPageLanguage( $this );
4602 // Hook at the end because we don't want to override the above stuff
4603 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4604 return wfGetLangObj( $pageLang );
4608 * Get the language in which the content of this page is written when
4609 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4610 * e.g. $wgLang (such as special pages, which are in the user language).
4615 public function getPageViewLanguage() {
4616 $pageLang = $this->getPageLanguage();
4617 // If this is nothing special (so the content is converted when viewed)
4618 if ( !$this->isSpecialPage()
4619 && !$this->isCssOrJsPage() && !$this->isCssJsSubpage()
4620 && $this->getNamespace() !== NS_MEDIAWIKI
4622 // If the user chooses a variant, the content is actually
4623 // in a language whose code is the variant code.
4624 $variant = $pageLang->getPreferredVariant();
4625 if ( $pageLang->getCode() !== $variant ) {
4626 $pageLang = Language
::factory( $variant );