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 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
69 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
70 var $mOldRestrictions = false;
71 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
72 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
73 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
74 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
75 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
76 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
77 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
78 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
79 # Don't change the following default, NS_MAIN is hardcoded in several
80 # places. See bug 696.
81 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
82 # Zero except in {{transclusion}} tags
83 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
84 var $mLength = -1; // /< The page length, 0 for special pages
85 var $mRedirect = null; // /< Is the article at this title a redirect?
86 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
87 var $mBacklinkCache = null; // /< Cache of links to this title
88 var $mHasSubpage; // /< Whether a page has any subpages
95 /*protected*/ function __construct() { }
98 * Create a new Title from a prefixed DB key
100 * @param $key String the database key, which has underscores
101 * instead of spaces, possibly including namespace and
103 * @return Title, or NULL on an error
105 public static function newFromDBkey( $key ) {
107 $t->mDbkeyform
= $key;
108 if ( $t->secureAndSplit() ) {
116 * Create a new Title from text, such as what one would find in a link. De-
117 * codes any HTML entities in the text.
119 * @param $text String the link text; spaces, prefixes, and an
120 * initial ':' indicating the main namespace are accepted.
121 * @param $defaultNamespace Int the namespace to use if none is speci-
122 * fied by a prefix. If you want to force a specific namespace even if
123 * $text might begin with a namespace prefix, use makeTitle() or
125 * @throws MWException
126 * @return Title|null - Title or null on an error.
128 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
129 if ( is_object( $text ) ) {
130 throw new MWException( 'Title::newFromText given an object' );
134 * Wiki pages often contain multiple links to the same page.
135 * Title normalization and parsing can become expensive on
136 * pages with many links, so we can save a little time by
139 * In theory these are value objects and won't get changed...
141 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
142 return Title
::$titleCache[$text];
145 # Convert things like é ā or 〗 into normalized (bug 14952) text
146 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
149 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
150 $t->mDefaultNamespace
= $defaultNamespace;
152 static $cachedcount = 0 ;
153 if ( $t->secureAndSplit() ) {
154 if ( $defaultNamespace == NS_MAIN
) {
155 if ( $cachedcount >= self
::CACHE_MAX
) {
156 # Avoid memory leaks on mass operations...
157 Title
::$titleCache = array();
161 Title
::$titleCache[$text] =& $t;
171 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
173 * Example of wrong and broken code:
174 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
176 * Example of right code:
177 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
179 * Create a new Title from URL-encoded text. Ensures that
180 * the given title's length does not exceed the maximum.
182 * @param $url String the title, as might be taken from a URL
183 * @return Title the new object, or NULL on an error
185 public static function newFromURL( $url ) {
188 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
189 # but some URLs used it as a space replacement and they still come
190 # from some external search tools.
191 if ( strpos( self
::legalChars(), '+' ) === false ) {
192 $url = str_replace( '+', ' ', $url );
195 $t->mDbkeyform
= str_replace( ' ', '_', $url );
196 if ( $t->secureAndSplit() ) {
204 * Create a new Title from an article ID
206 * @param $id Int the page_id corresponding to the Title to create
207 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
208 * @return Title the new object, or NULL on an error
210 public static function newFromID( $id, $flags = 0 ) {
211 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
212 $row = $db->selectRow(
215 'page_namespace', 'page_title', 'page_id',
216 'page_len', 'page_is_redirect', 'page_latest',
218 array( 'page_id' => $id ),
221 if ( $row !== false ) {
222 $title = Title
::newFromRow( $row );
230 * Make an array of titles from an array of IDs
232 * @param $ids Array of Int Array of IDs
233 * @return Array of Titles
235 public static function newFromIDs( $ids ) {
236 if ( !count( $ids ) ) {
239 $dbr = wfGetDB( DB_SLAVE
);
244 'page_namespace', 'page_title', 'page_id',
245 'page_len', 'page_is_redirect', 'page_latest',
247 array( 'page_id' => $ids ),
252 foreach ( $res as $row ) {
253 $titles[] = Title
::newFromRow( $row );
259 * Make a Title object from a DB row
261 * @param $row Object database row (needs at least page_title,page_namespace)
262 * @return Title corresponding Title
264 public static function newFromRow( $row ) {
265 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
266 $t->loadFromRow( $row );
271 * Load Title object fields from a DB row.
272 * If false is given, the title will be treated as non-existing.
274 * @param $row Object|bool database row
276 public function loadFromRow( $row ) {
277 if ( $row ) { // page found
278 if ( isset( $row->page_id
) )
279 $this->mArticleID
= (int)$row->page_id
;
280 if ( isset( $row->page_len
) )
281 $this->mLength
= (int)$row->page_len
;
282 if ( isset( $row->page_is_redirect
) )
283 $this->mRedirect
= (bool)$row->page_is_redirect
;
284 if ( isset( $row->page_latest
) )
285 $this->mLatestID
= (int)$row->page_latest
;
286 } else { // page not found
287 $this->mArticleID
= 0;
289 $this->mRedirect
= false;
290 $this->mLatestID
= 0;
295 * Create a new Title from a namespace index and a DB key.
296 * It's assumed that $ns and $title are *valid*, for instance when
297 * they came directly from the database or a special page name.
298 * For convenience, spaces are converted to underscores so that
299 * eg user_text fields can be used directly.
301 * @param $ns Int the namespace of the article
302 * @param $title String the unprefixed database key form
303 * @param $fragment String the link fragment (after the "#")
304 * @param $interwiki String the interwiki prefix
305 * @return Title the new object
307 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
309 $t->mInterwiki
= $interwiki;
310 $t->mFragment
= $fragment;
311 $t->mNamespace
= $ns = intval( $ns );
312 $t->mDbkeyform
= str_replace( ' ', '_', $title );
313 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
314 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
315 $t->mTextform
= str_replace( '_', ' ', $title );
320 * Create a new Title from a namespace index and a DB key.
321 * The parameters will be checked for validity, which is a bit slower
322 * than makeTitle() but safer for user-provided data.
324 * @param $ns Int the namespace of the article
325 * @param $title String database key form
326 * @param $fragment String the link fragment (after the "#")
327 * @param $interwiki String interwiki prefix
328 * @return Title the new object, or NULL on an error
330 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
331 if ( !MWNamespace
::exists( $ns ) ) {
336 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
337 if ( $t->secureAndSplit() ) {
345 * Create a new Title for the Main Page
347 * @return Title the new object
349 public static function newMainPage() {
350 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
351 // Don't give fatal errors if the message is broken
353 $title = Title
::newFromText( 'Main Page' );
359 * Extract a redirect destination from a string and return the
360 * Title, or null if the text doesn't contain a valid redirect
361 * This will only return the very next target, useful for
362 * the redirect table and other checks that don't need full recursion
364 * @param $text String: Text with possible redirect
365 * @return Title: The corresponding Title
367 public static function newFromRedirect( $text ) {
368 return self
::newFromRedirectInternal( $text );
372 * Extract a redirect destination from a string and return the
373 * Title, or null if the text doesn't contain a valid redirect
374 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
375 * in order to provide (hopefully) the Title of the final destination instead of another redirect
377 * @param $text String Text with possible redirect
380 public static function newFromRedirectRecurse( $text ) {
381 $titles = self
::newFromRedirectArray( $text );
382 return $titles ?
array_pop( $titles ) : null;
386 * Extract a redirect destination from a string and return an
387 * array of Titles, or null if the text doesn't contain a valid redirect
388 * The last element in the array is the final destination after all redirects
389 * have been resolved (up to $wgMaxRedirects times)
391 * @param $text String Text with possible redirect
392 * @return Array of Titles, with the destination last
394 public static function newFromRedirectArray( $text ) {
395 global $wgMaxRedirects;
396 $title = self
::newFromRedirectInternal( $text );
397 if ( is_null( $title ) ) {
400 // recursive check to follow double redirects
401 $recurse = $wgMaxRedirects;
402 $titles = array( $title );
403 while ( --$recurse > 0 ) {
404 if ( $title->isRedirect() ) {
405 $page = WikiPage
::factory( $title );
406 $newtitle = $page->getRedirectTarget();
410 // Redirects to some special pages are not permitted
411 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
412 // the new title passes the checks, so make that our current title so that further recursion can be checked
414 $titles[] = $newtitle;
423 * Really extract the redirect destination
424 * Do not call this function directly, use one of the newFromRedirect* functions above
426 * @param $text String Text with possible redirect
429 protected static function newFromRedirectInternal( $text ) {
430 global $wgMaxRedirects;
431 if ( $wgMaxRedirects < 1 ) {
432 //redirects are disabled, so quit early
435 $redir = MagicWord
::get( 'redirect' );
436 $text = trim( $text );
437 if ( $redir->matchStartAndRemove( $text ) ) {
438 // Extract the first link and see if it's usable
439 // Ensure that it really does come directly after #REDIRECT
440 // Some older redirects included a colon, so don't freak about that!
442 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
443 // Strip preceding colon used to "escape" categories, etc.
444 // and URL-decode links
445 if ( strpos( $m[1], '%' ) !== false ) {
446 // Match behavior of inline link parsing here;
447 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
449 $title = Title
::newFromText( $m[1] );
450 // If the title is a redirect to bad special pages or is invalid, return null
451 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
461 * Get the prefixed DB key associated with an ID
463 * @param $id Int the page_id of the article
464 * @return Title an object representing the article, or NULL if no such article was found
466 public static function nameOf( $id ) {
467 $dbr = wfGetDB( DB_SLAVE
);
469 $s = $dbr->selectRow(
471 array( 'page_namespace', 'page_title' ),
472 array( 'page_id' => $id ),
475 if ( $s === false ) {
479 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
484 * Get a regex character class describing the legal characters in a link
486 * @return String the list of characters, not delimited
488 public static function legalChars() {
489 global $wgLegalTitleChars;
490 return $wgLegalTitleChars;
494 * Returns a simple regex that will match on characters and sequences invalid in titles.
495 * Note that this doesn't pick up many things that could be wrong with titles, but that
496 * replacing this regex with something valid will make many titles valid.
498 * @return String regex string
500 static function getTitleInvalidRegex() {
501 static $rxTc = false;
503 # Matching titles will be held as illegal.
505 # Any character not allowed is forbidden...
506 '[^' . self
::legalChars() . ']' .
507 # URL percent encoding sequences interfere with the ability
508 # to round-trip titles -- you can't link to them consistently.
510 # XML/HTML character references produce similar issues.
511 '|&[A-Za-z0-9\x80-\xff]+;' .
513 '|&#x[0-9A-Fa-f]+;' .
521 * Get a string representation of a title suitable for
522 * including in a search index
524 * @param $ns Int a namespace index
525 * @param $title String text-form main part
526 * @return String a stripped-down title string ready for the search index
528 public static function indexTitle( $ns, $title ) {
531 $lc = SearchEngine
::legalSearchChars() . '&#;';
532 $t = $wgContLang->normalizeForSearch( $title );
533 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
534 $t = $wgContLang->lc( $t );
537 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
538 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
540 $t = preg_replace( "/\\s+/", ' ', $t );
542 if ( $ns == NS_FILE
) {
543 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
549 * Make a prefixed DB key from a DB key and a namespace index
551 * @param $ns Int numerical representation of the namespace
552 * @param $title String the DB key form the title
553 * @param $fragment String The link fragment (after the "#")
554 * @param $interwiki String The interwiki prefix
555 * @return String the prefixed form of the title
557 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
560 $namespace = $wgContLang->getNsText( $ns );
561 $name = $namespace == '' ?
$title : "$namespace:$title";
562 if ( strval( $interwiki ) != '' ) {
563 $name = "$interwiki:$name";
565 if ( strval( $fragment ) != '' ) {
566 $name .= '#' . $fragment;
572 * Escape a text fragment, say from a link, for a URL
574 * @param $fragment string containing a URL or link fragment (after the "#")
575 * @return String: escaped string
577 static function escapeFragmentForURL( $fragment ) {
578 # Note that we don't urlencode the fragment. urlencoded Unicode
579 # fragments appear not to work in IE (at least up to 7) or in at least
580 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
581 # to care if they aren't encoded.
582 return Sanitizer
::escapeId( $fragment, 'noninitial' );
586 * Callback for usort() to do title sorts by (namespace, title)
591 * @return Integer: result of string comparison, or namespace comparison
593 public static function compare( $a, $b ) {
594 if ( $a->getNamespace() == $b->getNamespace() ) {
595 return strcmp( $a->getText(), $b->getText() );
597 return $a->getNamespace() - $b->getNamespace();
602 * Determine whether the object refers to a page within
605 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
607 public function isLocal() {
608 if ( $this->mInterwiki
!= '' ) {
609 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
616 * Is this Title interwiki?
620 public function isExternal() {
621 return ( $this->mInterwiki
!= '' );
625 * Get the interwiki prefix (or null string)
627 * @return String Interwiki prefix
629 public function getInterwiki() {
630 return $this->mInterwiki
;
634 * Determine whether the object refers to a page within
635 * this project and is transcludable.
637 * @return Bool TRUE if this is transcludable
639 public function isTrans() {
640 if ( $this->mInterwiki
== '' ) {
644 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
648 * Returns the DB name of the distant wiki which owns the object.
650 * @return String the DB name
652 public function getTransWikiID() {
653 if ( $this->mInterwiki
== '' ) {
657 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
661 * Get the text form (spaces not underscores) of the main part
663 * @return String Main part of the title
665 public function getText() {
666 return $this->mTextform
;
670 * Get the URL-encoded form of the main part
672 * @return String Main part of the title, URL-encoded
674 public function getPartialURL() {
675 return $this->mUrlform
;
679 * Get the main part with underscores
681 * @return String: Main part of the title, with underscores
683 public function getDBkey() {
684 return $this->mDbkeyform
;
688 * Get the DB key with the initial letter case as specified by the user
690 * @return String DB key
692 function getUserCaseDBKey() {
693 return $this->mUserCaseDBKey
;
697 * Get the namespace index, i.e. one of the NS_xxxx constants.
699 * @return Integer: Namespace index
701 public function getNamespace() {
702 return $this->mNamespace
;
706 * Get the namespace text
708 * @return String: Namespace text
710 public function getNsText() {
713 if ( $this->mInterwiki
!= '' ) {
714 // This probably shouldn't even happen. ohh man, oh yuck.
715 // But for interwiki transclusion it sometimes does.
716 // Shit. Shit shit shit.
718 // Use the canonical namespaces if possible to try to
719 // resolve a foreign namespace.
720 if ( MWNamespace
::exists( $this->mNamespace
) ) {
721 return MWNamespace
::getCanonicalName( $this->mNamespace
);
725 if ( $wgContLang->needsGenderDistinction() &&
726 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
727 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
728 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
731 return $wgContLang->getNsText( $this->mNamespace
);
735 * Get the namespace text of the subject (rather than talk) page
737 * @return String Namespace text
739 public function getSubjectNsText() {
741 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
745 * Get the namespace text of the talk page
747 * @return String Namespace text
749 public function getTalkNsText() {
751 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
755 * Could this title have a corresponding talk page?
757 * @return Bool TRUE or FALSE
759 public function canTalk() {
760 return( MWNamespace
::canTalk( $this->mNamespace
) );
764 * Is this in a namespace that allows actual pages?
767 * @internal note -- uses hardcoded namespace index instead of constants
769 public function canExist() {
770 return $this->mNamespace
>= NS_MAIN
;
774 * Can this title be added to a user's watchlist?
776 * @return Bool TRUE or FALSE
778 public function isWatchable() {
779 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
783 * Returns true if this is a special page.
787 public function isSpecialPage() {
788 return $this->getNamespace() == NS_SPECIAL
;
792 * Returns true if this title resolves to the named special page
794 * @param $name String The special page name
797 public function isSpecial( $name ) {
798 if ( $this->isSpecialPage() ) {
799 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
800 if ( $name == $thisName ) {
808 * If the Title refers to a special page alias which is not the local default, resolve
809 * the alias, and localise the name as necessary. Otherwise, return $this
813 public function fixSpecialName() {
814 if ( $this->isSpecialPage() ) {
815 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
816 if ( $canonicalName ) {
817 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
818 if ( $localName != $this->mDbkeyform
) {
819 return Title
::makeTitle( NS_SPECIAL
, $localName );
827 * Returns true if the title is inside the specified namespace.
829 * Please make use of this instead of comparing to getNamespace()
830 * This function is much more resistant to changes we may make
831 * to namespaces than code that makes direct comparisons.
832 * @param $ns int The namespace
836 public function inNamespace( $ns ) {
837 return MWNamespace
::equals( $this->getNamespace(), $ns );
841 * Returns true if the title is inside one of the specified namespaces.
843 * @param ...$namespaces The namespaces to check for
847 public function inNamespaces( /* ... */ ) {
848 $namespaces = func_get_args();
849 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
850 $namespaces = $namespaces[0];
853 foreach ( $namespaces as $ns ) {
854 if ( $this->inNamespace( $ns ) ) {
863 * Returns true if the title has the same subject namespace as the
864 * namespace specified.
865 * For example this method will take NS_USER and return true if namespace
866 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
867 * as their subject namespace.
869 * This is MUCH simpler than individually testing for equivilance
870 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
875 public function hasSubjectNamespace( $ns ) {
876 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
880 * Is this Title in a namespace which contains content?
881 * In other words, is this a content page, for the purposes of calculating
886 public function isContentPage() {
887 return MWNamespace
::isContent( $this->getNamespace() );
891 * Would anybody with sufficient privileges be able to move this page?
892 * Some pages just aren't movable.
894 * @return Bool TRUE or FALSE
896 public function isMovable() {
897 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
898 // Interwiki title or immovable namespace. Hooks don't get to override here
903 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
908 * Is this the mainpage?
909 * @note Title::newFromText seams to be sufficiently optimized by the title
910 * cache that we don't need to over-optimize by doing direct comparisons and
911 * acidentally creating new bugs where $title->equals( Title::newFromText() )
912 * ends up reporting something differently than $title->isMainPage();
917 public function isMainPage() {
918 return $this->equals( Title
::newMainPage() );
926 public function isSubpage() {
927 return MWNamespace
::hasSubpages( $this->mNamespace
)
928 ?
strpos( $this->getText(), '/' ) !== false
933 * Is this a conversion table for the LanguageConverter?
937 public function isConversionTable() {
938 return $this->getNamespace() == NS_MEDIAWIKI
&&
939 strpos( $this->getText(), 'Conversiontable/' ) === 0;
943 * Does that page contain wikitext, or it is JS, CSS or whatever?
947 public function isWikitextPage() {
948 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
949 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
954 * Could this page contain custom CSS or JavaScript, based
959 public function isCssOrJsPage() {
960 $retval = $this->mNamespace
== NS_MEDIAWIKI
961 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
962 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
967 * Is this a .css or .js subpage of a user page?
970 public function isCssJsSubpage() {
971 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
975 * Trim down a .css or .js subpage title to get the corresponding skin name
977 * @return string containing skin name from .css or .js subpage title
979 public function getSkinFromCssJsSubpage() {
980 $subpage = explode( '/', $this->mTextform
);
981 $subpage = $subpage[ count( $subpage ) - 1 ];
982 $lastdot = strrpos( $subpage, '.' );
983 if ( $lastdot === false )
984 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
985 return substr( $subpage, 0, $lastdot );
989 * Is this a .css subpage of a user page?
993 public function isCssSubpage() {
994 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
998 * Is this a .js subpage of a user page?
1002 public function isJsSubpage() {
1003 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1007 * Is this a talk page of some sort?
1011 public function isTalkPage() {
1012 return MWNamespace
::isTalk( $this->getNamespace() );
1016 * Get a Title object associated with the talk page of this article
1018 * @return Title the object for the talk page
1020 public function getTalkPage() {
1021 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1025 * Get a title object associated with the subject page of this
1028 * @return Title the object for the subject page
1030 public function getSubjectPage() {
1031 // Is this the same title?
1032 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1033 if ( $this->getNamespace() == $subjectNS ) {
1036 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1040 * Get the default namespace index, for when there is no namespace
1042 * @return Int Default namespace index
1044 public function getDefaultNamespace() {
1045 return $this->mDefaultNamespace
;
1049 * Get title for search index
1051 * @return String a stripped-down title string ready for the
1054 public function getIndexTitle() {
1055 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1059 * Get the Title fragment (i.e.\ the bit after the #) in text form
1061 * @return String Title fragment
1063 public function getFragment() {
1064 return $this->mFragment
;
1068 * Get the fragment in URL form, including the "#" character if there is one
1069 * @return String Fragment in URL form
1071 public function getFragmentForURL() {
1072 if ( $this->mFragment
== '' ) {
1075 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1080 * Set the fragment for this title. Removes the first character from the
1081 * specified fragment before setting, so it assumes you're passing it with
1084 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1085 * Still in active use privately.
1087 * @param $fragment String text
1089 public function setFragment( $fragment ) {
1090 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1094 * Prefix some arbitrary text with the namespace or interwiki prefix
1097 * @param $name String the text
1098 * @return String the prefixed text
1101 private function prefix( $name ) {
1103 if ( $this->mInterwiki
!= '' ) {
1104 $p = $this->mInterwiki
. ':';
1107 if ( 0 != $this->mNamespace
) {
1108 $p .= $this->getNsText() . ':';
1114 * Get the prefixed database key form
1116 * @return String the prefixed title, with underscores and
1117 * any interwiki and namespace prefixes
1119 public function getPrefixedDBkey() {
1120 $s = $this->prefix( $this->mDbkeyform
);
1121 $s = str_replace( ' ', '_', $s );
1126 * Get the prefixed title with spaces.
1127 * This is the form usually used for display
1129 * @return String the prefixed title, with spaces
1131 public function getPrefixedText() {
1132 // @todo FIXME: Bad usage of empty() ?
1133 if ( empty( $this->mPrefixedText
) ) {
1134 $s = $this->prefix( $this->mTextform
);
1135 $s = str_replace( '_', ' ', $s );
1136 $this->mPrefixedText
= $s;
1138 return $this->mPrefixedText
;
1142 * Return a string representation of this title
1144 * @return String representation of this title
1146 public function __toString() {
1147 return $this->getPrefixedText();
1151 * Get the prefixed title with spaces, plus any fragment
1152 * (part beginning with '#')
1154 * @return String the prefixed title, with spaces and the fragment, including '#'
1156 public function getFullText() {
1157 $text = $this->getPrefixedText();
1158 if ( $this->mFragment
!= '' ) {
1159 $text .= '#' . $this->mFragment
;
1165 * Get the base page name, i.e. the leftmost part before any slashes
1167 * @return String Base name
1169 public function getBaseText() {
1170 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1171 return $this->getText();
1174 $parts = explode( '/', $this->getText() );
1175 # Don't discard the real title if there's no subpage involved
1176 if ( count( $parts ) > 1 ) {
1177 unset( $parts[count( $parts ) - 1] );
1179 return implode( '/', $parts );
1183 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1185 * @return String Subpage name
1187 public function getSubpageText() {
1188 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1189 return( $this->mTextform
);
1191 $parts = explode( '/', $this->mTextform
);
1192 return( $parts[count( $parts ) - 1] );
1196 * Get the HTML-escaped displayable text form.
1197 * Used for the title field in <a> tags.
1199 * @return String the text, including any prefixes
1201 public function getEscapedText() {
1202 wfDeprecated( __METHOD__
, '1.19' );
1203 return htmlspecialchars( $this->getPrefixedText() );
1207 * Get a URL-encoded form of the subpage text
1209 * @return String URL-encoded subpage name
1211 public function getSubpageUrlForm() {
1212 $text = $this->getSubpageText();
1213 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1218 * Get a URL-encoded title (not an actual URL) including interwiki
1220 * @return String the URL-encoded form
1222 public function getPrefixedURL() {
1223 $s = $this->prefix( $this->mDbkeyform
);
1224 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1229 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1230 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1231 * second argument named variant. This was deprecated in favor
1232 * of passing an array of option with a "variant" key
1233 * Once $query2 is removed for good, this helper can be dropped
1234 * andthe wfArrayToCGI moved to getLocalURL();
1236 * @since 1.19 (r105919)
1238 * @param $query2 bool
1241 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1242 if( $query2 !== false ) {
1243 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" );
1245 if ( is_array( $query ) ) {
1246 $query = wfArrayToCGI( $query );
1249 if ( is_string( $query2 ) ) {
1250 // $query2 is a string, we will consider this to be
1251 // a deprecated $variant argument and add it to the query
1252 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1254 $query2 = wfArrayToCGI( $query2 );
1256 // If we have $query content add a & to it first
1260 // Now append the queries together
1267 * Get a real URL referring to this title, with interwiki link and
1270 * See getLocalURL for the arguments.
1272 * @see self::getLocalURL
1273 * @return String the URL
1275 public function getFullURL( $query = '', $query2 = false ) {
1276 $query = self
::fixUrlQueryArgs( $query, $query2 );
1278 # Hand off all the decisions on urls to getLocalURL
1279 $url = $this->getLocalURL( $query );
1281 # Expand the url to make it a full url. Note that getLocalURL has the
1282 # potential to output full urls for a variety of reasons, so we use
1283 # wfExpandUrl instead of simply prepending $wgServer
1284 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1286 # Finally, add the fragment.
1287 $url .= $this->getFragmentForURL();
1289 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1294 * Get a URL with no fragment or server name. If this page is generated
1295 * with action=render, $wgServer is prepended.
1298 * @param $query string|array an optional query string,
1299 * not used for interwiki links. Can be specified as an associative array as well,
1300 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1301 * Some query patterns will trigger various shorturl path replacements.
1302 * @param $query2 Mixed: An optional secondary query array. This one MUST
1303 * be an array. If a string is passed it will be interpreted as a deprecated
1304 * variant argument and urlencoded into a variant= argument.
1305 * This second query argument will be added to the $query
1306 * The second parameter is deprecated since 1.19. Pass it as a key,value
1307 * pair in the first parameter array instead.
1309 * @return String the URL
1311 public function getLocalURL( $query = '', $query2 = false ) {
1312 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1314 $query = self
::fixUrlQueryArgs( $query, $query2 );
1316 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1318 $namespace = $this->getNsText();
1319 if ( $namespace != '' ) {
1320 # Can this actually happen? Interwikis shouldn't be parsed.
1321 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1324 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1325 $url = wfAppendQuery( $url, $query );
1327 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1328 if ( $query == '' ) {
1329 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1330 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1332 global $wgVariantArticlePath, $wgActionPaths;
1336 if ( !empty( $wgActionPaths ) &&
1337 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1339 $action = urldecode( $matches[2] );
1340 if ( isset( $wgActionPaths[$action] ) ) {
1341 $query = $matches[1];
1342 if ( isset( $matches[4] ) ) {
1343 $query .= $matches[4];
1345 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1346 if ( $query != '' ) {
1347 $url = wfAppendQuery( $url, $query );
1352 if ( $url === false &&
1353 $wgVariantArticlePath &&
1354 $this->getPageLanguage()->hasVariants() &&
1355 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1357 $variant = urldecode( $matches[1] );
1358 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1359 // Only do the variant replacement if the given variant is a valid
1360 // variant for the page's language.
1361 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1362 $url = str_replace( '$1', $dbkey, $url );
1366 if ( $url === false ) {
1367 if ( $query == '-' ) {
1370 $url = "{$wgScript}?title={$dbkey}&{$query}";
1374 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1376 // @todo FIXME: This causes breakage in various places when we
1377 // actually expected a local URL and end up with dupe prefixes.
1378 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1379 $url = $wgServer . $url;
1382 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1387 * Get a URL that's the simplest URL that will be valid to link, locally,
1388 * to the current Title. It includes the fragment, but does not include
1389 * the server unless action=render is used (or the link is external). If
1390 * there's a fragment but the prefixed text is empty, we just return a link
1393 * The result obviously should not be URL-escaped, but does need to be
1394 * HTML-escaped if it's being output in HTML.
1396 * See getLocalURL for the arguments.
1398 * @see self::getLocalURL
1399 * @return String the URL
1401 public function getLinkURL( $query = '', $query2 = false ) {
1402 wfProfileIn( __METHOD__
);
1403 if ( $this->isExternal() ) {
1404 $ret = $this->getFullURL( $query, $query2 );
1405 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1406 $ret = $this->getFragmentForURL();
1408 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1410 wfProfileOut( __METHOD__
);
1415 * Get an HTML-escaped version of the URL form, suitable for
1416 * using in a link, without a server name or fragment
1418 * See getLocalURL for the arguments.
1420 * @see self::getLocalURL
1421 * @param $query string
1422 * @param $query2 bool|string
1423 * @return String the URL
1425 public function escapeLocalURL( $query = '', $query2 = false ) {
1426 wfDeprecated( __METHOD__
, '1.19' );
1427 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1431 * Get an HTML-escaped version of the URL form, suitable for
1432 * using in a link, including the server name and fragment
1434 * See getLocalURL for the arguments.
1436 * @see self::getLocalURL
1437 * @return String the URL
1439 public function escapeFullURL( $query = '', $query2 = false ) {
1440 wfDeprecated( __METHOD__
, '1.19' );
1441 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1445 * Get the URL form for an internal link.
1446 * - Used in various Squid-related code, in case we have a different
1447 * internal hostname for the server from the exposed one.
1449 * This uses $wgInternalServer to qualify the path, or $wgServer
1450 * if $wgInternalServer is not set. If the server variable used is
1451 * protocol-relative, the URL will be expanded to http://
1453 * See getLocalURL for the arguments.
1455 * @see self::getLocalURL
1456 * @return String the URL
1458 public function getInternalURL( $query = '', $query2 = false ) {
1459 global $wgInternalServer, $wgServer;
1460 $query = self
::fixUrlQueryArgs( $query, $query2 );
1461 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1462 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1463 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1468 * Get the URL for a canonical link, for use in things like IRC and
1469 * e-mail notifications. Uses $wgCanonicalServer and the
1470 * GetCanonicalURL hook.
1472 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1474 * See getLocalURL for the arguments.
1476 * @see self::getLocalURL
1477 * @return string The URL
1480 public function getCanonicalURL( $query = '', $query2 = false ) {
1481 $query = self
::fixUrlQueryArgs( $query, $query2 );
1482 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1483 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1488 * HTML-escaped version of getCanonicalURL()
1490 * See getLocalURL for the arguments.
1492 * @see self::getLocalURL
1496 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1497 wfDeprecated( __METHOD__
, '1.19' );
1498 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1502 * Get the edit URL for this Title
1504 * @return String the URL, or a null string if this is an
1507 public function getEditURL() {
1508 if ( $this->mInterwiki
!= '' ) {
1511 $s = $this->getLocalURL( 'action=edit' );
1517 * Is $wgUser watching this page?
1519 * @deprecated in 1.20; use User::isWatched() instead.
1522 public function userIsWatching() {
1525 if ( is_null( $this->mWatched
) ) {
1526 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1527 $this->mWatched
= false;
1529 $this->mWatched
= $wgUser->isWatched( $this );
1532 return $this->mWatched
;
1536 * Can $wgUser read this page?
1538 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1540 * @todo fold these checks into userCan()
1542 public function userCanRead() {
1543 wfDeprecated( __METHOD__
, '1.19' );
1544 return $this->userCan( 'read' );
1548 * Can $user perform $action on this page?
1549 * This skips potentially expensive cascading permission checks
1550 * as well as avoids expensive error formatting
1552 * Suitable for use for nonessential UI controls in common cases, but
1553 * _not_ for functional access control.
1555 * May provide false positives, but should never provide a false negative.
1557 * @param $action String action that permission needs to be checked for
1558 * @param $user User to check (since 1.19); $wgUser will be used if not
1562 public function quickUserCan( $action, $user = null ) {
1563 return $this->userCan( $action, $user, false );
1567 * Can $user perform $action on this page?
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
1572 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1573 * unnecessary queries.
1576 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1577 if ( !$user instanceof User
) {
1581 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1585 * Can $user perform $action on this page?
1587 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1589 * @param $action String action that permission needs to be checked for
1590 * @param $user User to check
1591 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1592 * queries by skipping checks for cascading protections and user blocks.
1593 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1594 * whose corresponding errors may be ignored.
1595 * @return Array of arguments to wfMsg to explain permissions problems.
1597 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1598 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1600 // Remove the errors being ignored.
1601 foreach ( $errors as $index => $error ) {
1602 $error_key = is_array( $error ) ?
$error[0] : $error;
1604 if ( in_array( $error_key, $ignoreErrors ) ) {
1605 unset( $errors[$index] );
1613 * Permissions checks that fail most often, and which are easiest to test.
1615 * @param $action String the action to check
1616 * @param $user User user to check
1617 * @param $errors Array list of current errors
1618 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1619 * @param $short Boolean short circuit on first error
1621 * @return Array list of errors
1623 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1624 if ( $action == 'create' ) {
1625 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1626 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1627 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1629 } elseif ( $action == 'move' ) {
1630 if ( !$user->isAllowed( 'move-rootuserpages' )
1631 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1632 // Show user page-specific message only if the user can move other pages
1633 $errors[] = array( 'cant-move-user-page' );
1636 // Check if user is allowed to move files if it's a file
1637 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1638 $errors[] = array( 'movenotallowedfile' );
1641 if ( !$user->isAllowed( 'move' ) ) {
1642 // User can't move anything
1643 global $wgGroupPermissions;
1644 $userCanMove = false;
1645 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1646 $userCanMove = $wgGroupPermissions['user']['move'];
1648 $autoconfirmedCanMove = false;
1649 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1650 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1652 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1653 // custom message if logged-in users without any special rights can move
1654 $errors[] = array( 'movenologintext' );
1656 $errors[] = array( 'movenotallowed' );
1659 } elseif ( $action == 'move-target' ) {
1660 if ( !$user->isAllowed( 'move' ) ) {
1661 // User can't move anything
1662 $errors[] = array( 'movenotallowed' );
1663 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1664 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1665 // Show user page-specific message only if the user can move other pages
1666 $errors[] = array( 'cant-move-to-user-page' );
1668 } elseif ( !$user->isAllowed( $action ) ) {
1669 $errors[] = $this->missingPermissionError( $action, $short );
1676 * Add the resulting error code to the errors array
1678 * @param $errors Array list of current errors
1679 * @param $result Mixed result of errors
1681 * @return Array list of errors
1683 private function resultToError( $errors, $result ) {
1684 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1685 // A single array representing an error
1686 $errors[] = $result;
1687 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1688 // A nested array representing multiple errors
1689 $errors = array_merge( $errors, $result );
1690 } elseif ( $result !== '' && is_string( $result ) ) {
1691 // A string representing a message-id
1692 $errors[] = array( $result );
1693 } elseif ( $result === false ) {
1694 // a generic "We don't want them to do that"
1695 $errors[] = array( 'badaccess-group0' );
1701 * Check various permission hooks
1703 * @param $action String the action to check
1704 * @param $user User user to check
1705 * @param $errors Array list of current errors
1706 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1707 * @param $short Boolean short circuit on first error
1709 * @return Array list of errors
1711 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1712 // Use getUserPermissionsErrors instead
1714 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1715 return $result ?
array() : array( array( 'badaccess-group0' ) );
1717 // Check getUserPermissionsErrors hook
1718 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1719 $errors = $this->resultToError( $errors, $result );
1721 // Check getUserPermissionsErrorsExpensive hook
1722 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1723 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1724 $errors = $this->resultToError( $errors, $result );
1731 * Check permissions on special pages & namespaces
1733 * @param $action String the action to check
1734 * @param $user User user to check
1735 * @param $errors Array list of current errors
1736 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1737 * @param $short Boolean short circuit on first error
1739 * @return Array list of errors
1741 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1742 # Only 'createaccount' and 'execute' can be performed on
1743 # special pages, which don't actually exist in the DB.
1744 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1745 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1746 $errors[] = array( 'ns-specialprotected' );
1749 # Check $wgNamespaceProtection for restricted namespaces
1750 if ( $this->isNamespaceProtected( $user ) ) {
1751 $ns = $this->mNamespace
== NS_MAIN ?
1752 wfMsg( 'nstab-main' ) : $this->getNsText();
1753 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1754 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1761 * Check CSS/JS sub-page permissions
1763 * @param $action String the action to check
1764 * @param $user User user to check
1765 * @param $errors Array list of current errors
1766 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1767 * @param $short Boolean short circuit on first error
1769 * @return Array list of errors
1771 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1772 # Protect css/js subpages of user pages
1773 # XXX: this might be better using restrictions
1774 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1775 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1776 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1777 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1778 $errors[] = array( 'customcssprotected' );
1779 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1780 $errors[] = array( 'customjsprotected' );
1788 * Check against page_restrictions table requirements on this
1789 * page. The user must possess all required rights for this
1792 * @param $action String the action to check
1793 * @param $user User user to check
1794 * @param $errors Array list of current errors
1795 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1796 * @param $short Boolean short circuit on first error
1798 * @return Array list of errors
1800 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1801 foreach ( $this->getRestrictions( $action ) as $right ) {
1802 // Backwards compatibility, rewrite sysop -> protect
1803 if ( $right == 'sysop' ) {
1806 if ( $right != '' && !$user->isAllowed( $right ) ) {
1807 // Users with 'editprotected' permission can edit protected pages
1808 // without cascading option turned on.
1809 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1810 ||
$this->mCascadeRestriction
)
1812 $errors[] = array( 'protectedpagetext', $right );
1821 * Check restrictions on cascading pages.
1823 * @param $action String the action to check
1824 * @param $user User to check
1825 * @param $errors Array list of current errors
1826 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1827 * @param $short Boolean short circuit on first error
1829 * @return Array list of errors
1831 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1832 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1833 # We /could/ use the protection level on the source page, but it's
1834 # fairly ugly as we have to establish a precedence hierarchy for pages
1835 # included by multiple cascade-protected pages. So just restrict
1836 # it to people with 'protect' permission, as they could remove the
1837 # protection anyway.
1838 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1839 # Cascading protection depends on more than this page...
1840 # Several cascading protected pages may include this page...
1841 # Check each cascading level
1842 # This is only for protection restrictions, not for all actions
1843 if ( isset( $restrictions[$action] ) ) {
1844 foreach ( $restrictions[$action] as $right ) {
1845 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1846 if ( $right != '' && !$user->isAllowed( $right ) ) {
1848 foreach ( $cascadingSources as $page )
1849 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1850 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1860 * Check action permissions not already checked in checkQuickPermissions
1862 * @param $action String the action to check
1863 * @param $user User to check
1864 * @param $errors Array list of current errors
1865 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1866 * @param $short Boolean short circuit on first error
1868 * @return Array list of errors
1870 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1871 global $wgDeleteRevisionsLimit, $wgLang;
1873 if ( $action == 'protect' ) {
1874 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1875 // If they can't edit, they shouldn't protect.
1876 $errors[] = array( 'protect-cantedit' );
1878 } elseif ( $action == 'create' ) {
1879 $title_protection = $this->getTitleProtection();
1880 if( $title_protection ) {
1881 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1882 $title_protection['pt_create_perm'] = 'protect'; // B/C
1884 if( $title_protection['pt_create_perm'] == '' ||
1885 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1887 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1890 } elseif ( $action == 'move' ) {
1891 // Check for immobile pages
1892 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1893 // Specific message for this case
1894 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1895 } elseif ( !$this->isMovable() ) {
1896 // Less specific message for rarer cases
1897 $errors[] = array( 'immobile-source-page' );
1899 } elseif ( $action == 'move-target' ) {
1900 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1901 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1902 } elseif ( !$this->isMovable() ) {
1903 $errors[] = array( 'immobile-target-page' );
1905 } elseif ( $action == 'delete' ) {
1906 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1907 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1909 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1916 * Check that the user isn't blocked from editting.
1918 * @param $action String the action to check
1919 * @param $user User to check
1920 * @param $errors Array list of current errors
1921 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1922 * @param $short Boolean short circuit on first error
1924 * @return Array list of errors
1926 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1927 // Account creation blocks handled at userlogin.
1928 // Unblocking handled in SpecialUnblock
1929 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1933 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1935 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1936 $errors[] = array( 'confirmedittext' );
1939 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1940 // Don't block the user from editing their own talk page unless they've been
1941 // explicitly blocked from that too.
1942 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1943 $block = $user->getBlock();
1945 // This is from OutputPage::blockedPage
1946 // Copied at r23888 by werdna
1948 $id = $user->blockedBy();
1949 $reason = $user->blockedFor();
1950 if ( $reason == '' ) {
1951 $reason = wfMsg( 'blockednoreason' );
1953 $ip = $user->getRequest()->getIP();
1955 if ( is_numeric( $id ) ) {
1956 $name = User
::whoIs( $id );
1961 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1962 $blockid = $block->getId();
1963 $blockExpiry = $block->getExpiry();
1964 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1965 if ( $blockExpiry == 'infinity' ) {
1966 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1968 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1971 $intended = strval( $block->getTarget() );
1973 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1974 $blockid, $blockExpiry, $intended, $blockTimestamp );
1981 * Check that the user is allowed to read this page.
1983 * @param $action String the action to check
1984 * @param $user User to check
1985 * @param $errors Array list of current errors
1986 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1987 * @param $short Boolean short circuit on first error
1989 * @return Array list of errors
1991 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1992 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1993 static $useShortcut = null;
1995 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1996 if ( is_null( $useShortcut ) ) {
1997 $useShortcut = true;
1998 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1999 # Not a public wiki, so no shortcut
2000 $useShortcut = false;
2001 } elseif ( !empty( $wgRevokePermissions ) ) {
2003 * Iterate through each group with permissions being revoked (key not included since we don't care
2004 * what the group name is), then check if the read permission is being revoked. If it is, then
2005 * we don't use the shortcut below since the user might not be able to read, even though anon
2006 * reading is allowed.
2008 foreach ( $wgRevokePermissions as $perms ) {
2009 if ( !empty( $perms['read'] ) ) {
2010 # We might be removing the read right from the user, so no shortcut
2011 $useShortcut = false;
2018 $whitelisted = false;
2019 if ( $useShortcut ) {
2020 # Shortcut for public wikis, allows skipping quite a bit of code
2021 $whitelisted = true;
2022 } elseif ( $user->isAllowed( 'read' ) ) {
2023 # If the user is allowed to read pages, he is allowed to read all pages
2024 $whitelisted = true;
2025 } elseif ( $this->isSpecial( 'Userlogin' )
2026 ||
$this->isSpecial( 'ChangePassword' )
2027 ||
$this->isSpecial( 'PasswordReset' )
2029 # Always grant access to the login page.
2030 # Even anons need to be able to log in.
2031 $whitelisted = true;
2032 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2033 # Time to check the whitelist
2034 # Only do these checks is there's something to check against
2035 $name = $this->getPrefixedText();
2036 $dbName = $this->getPrefixedDBKey();
2038 // Check for explicit whitelisting with and without underscores
2039 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2040 $whitelisted = true;
2041 } elseif ( $this->getNamespace() == NS_MAIN
) {
2042 # Old settings might have the title prefixed with
2043 # a colon for main-namespace pages
2044 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2045 $whitelisted = true;
2047 } elseif ( $this->isSpecialPage() ) {
2048 # If it's a special page, ditch the subpage bit and check again
2049 $name = $this->getDBkey();
2050 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2051 if ( $name !== false ) {
2052 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2053 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2054 $whitelisted = true;
2060 if ( !$whitelisted ) {
2061 # If the title is not whitelisted, give extensions a chance to do so...
2062 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2063 if ( !$whitelisted ) {
2064 $errors[] = $this->missingPermissionError( $action, $short );
2072 * Get a description array when the user doesn't have the right to perform
2073 * $action (i.e. when User::isAllowed() returns false)
2075 * @param $action String the action to check
2076 * @param $short Boolean short circuit on first error
2077 * @return Array list of errors
2079 private function missingPermissionError( $action, $short ) {
2080 // We avoid expensive display logic for quickUserCan's and such
2082 return array( 'badaccess-group0' );
2085 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2086 User
::getGroupsWithPermission( $action ) );
2088 if ( count( $groups ) ) {
2092 $wgLang->commaList( $groups ),
2096 return array( 'badaccess-group0' );
2101 * Can $user perform $action on this page? This is an internal function,
2102 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2103 * checks on wfReadOnly() and blocks)
2105 * @param $action String action that permission needs to be checked for
2106 * @param $user User to check
2107 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2108 * @param $short Bool Set this to true to stop after the first permission error.
2109 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2111 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2112 wfProfileIn( __METHOD__
);
2114 # Read has special handling
2115 if ( $action == 'read' ) {
2117 'checkPermissionHooks',
2118 'checkReadPermissions',
2122 'checkQuickPermissions',
2123 'checkPermissionHooks',
2124 'checkSpecialsAndNSPermissions',
2125 'checkCSSandJSPermissions',
2126 'checkPageRestrictions',
2127 'checkCascadingSourcesRestrictions',
2128 'checkActionPermissions',
2134 while( count( $checks ) > 0 &&
2135 !( $short && count( $errors ) > 0 ) ) {
2136 $method = array_shift( $checks );
2137 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2140 wfProfileOut( __METHOD__
);
2145 * Protect css subpages of user pages: can $wgUser edit
2148 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2151 public function userCanEditCssSubpage() {
2153 wfDeprecated( __METHOD__
, '1.19' );
2154 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2155 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2159 * Protect js subpages of user pages: can $wgUser edit
2162 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2165 public function userCanEditJsSubpage() {
2167 wfDeprecated( __METHOD__
, '1.19' );
2168 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2169 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2173 * Get a filtered list of all restriction types supported by this wiki.
2174 * @param bool $exists True to get all restriction types that apply to
2175 * titles that do exist, False for all restriction types that apply to
2176 * titles that do not exist
2179 public static function getFilteredRestrictionTypes( $exists = true ) {
2180 global $wgRestrictionTypes;
2181 $types = $wgRestrictionTypes;
2183 # Remove the create restriction for existing titles
2184 $types = array_diff( $types, array( 'create' ) );
2186 # Only the create and upload restrictions apply to non-existing titles
2187 $types = array_intersect( $types, array( 'create', 'upload' ) );
2193 * Returns restriction types for the current Title
2195 * @return array applicable restriction types
2197 public function getRestrictionTypes() {
2198 if ( $this->isSpecialPage() ) {
2202 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2204 if ( $this->getNamespace() != NS_FILE
) {
2205 # Remove the upload restriction for non-file titles
2206 $types = array_diff( $types, array( 'upload' ) );
2209 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2211 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2212 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2218 * Is this title subject to title protection?
2219 * Title protection is the one applied against creation of such title.
2221 * @return Mixed An associative array representing any existent title
2222 * protection, or false if there's none.
2224 private function getTitleProtection() {
2225 // Can't protect pages in special namespaces
2226 if ( $this->getNamespace() < 0 ) {
2230 // Can't protect pages that exist.
2231 if ( $this->exists() ) {
2235 if ( !isset( $this->mTitleProtection
) ) {
2236 $dbr = wfGetDB( DB_SLAVE
);
2237 $res = $dbr->select( 'protected_titles', '*',
2238 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2241 // fetchRow returns false if there are no rows.
2242 $this->mTitleProtection
= $dbr->fetchRow( $res );
2244 return $this->mTitleProtection
;
2248 * Update the title protection status
2250 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2251 * @param $create_perm String Permission required for creation
2252 * @param $reason String Reason for protection
2253 * @param $expiry String Expiry timestamp
2254 * @return boolean true
2256 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2257 wfDeprecated( __METHOD__
, '1.19' );
2261 $limit = array( 'create' => $create_perm );
2262 $expiry = array( 'create' => $expiry );
2264 $page = WikiPage
::factory( $this );
2265 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2267 return $status->isOK();
2271 * Remove any title protection due to page existing
2273 public function deleteTitleProtection() {
2274 $dbw = wfGetDB( DB_MASTER
);
2278 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2281 $this->mTitleProtection
= false;
2285 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2287 * @param $action String Action to check (default: edit)
2290 public function isSemiProtected( $action = 'edit' ) {
2291 if ( $this->exists() ) {
2292 $restrictions = $this->getRestrictions( $action );
2293 if ( count( $restrictions ) > 0 ) {
2294 foreach ( $restrictions as $restriction ) {
2295 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2305 # If it doesn't exist, it can't be protected
2311 * Does the title correspond to a protected article?
2313 * @param $action String the action the page is protected from,
2314 * by default checks all actions.
2317 public function isProtected( $action = '' ) {
2318 global $wgRestrictionLevels;
2320 $restrictionTypes = $this->getRestrictionTypes();
2322 # Special pages have inherent protection
2323 if( $this->isSpecialPage() ) {
2327 # Check regular protection levels
2328 foreach ( $restrictionTypes as $type ) {
2329 if ( $action == $type ||
$action == '' ) {
2330 $r = $this->getRestrictions( $type );
2331 foreach ( $wgRestrictionLevels as $level ) {
2332 if ( in_array( $level, $r ) && $level != '' ) {
2343 * Determines if $user is unable to edit this page because it has been protected
2344 * by $wgNamespaceProtection.
2346 * @param $user User object to check permissions
2349 public function isNamespaceProtected( User
$user ) {
2350 global $wgNamespaceProtection;
2352 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2353 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2354 if ( $right != '' && !$user->isAllowed( $right ) ) {
2363 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2365 * @return Bool If the page is subject to cascading restrictions.
2367 public function isCascadeProtected() {
2368 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2369 return ( $sources > 0 );
2373 * Cascading protection: Get the source of any cascading restrictions on this page.
2375 * @param $getPages Bool Whether or not to retrieve the actual pages
2376 * that the restrictions have come from.
2377 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2378 * have come, false for none, or true if such restrictions exist, but $getPages
2379 * was not set. The restriction array is an array of each type, each of which
2380 * contains a array of unique groups.
2382 public function getCascadeProtectionSources( $getPages = true ) {
2384 $pagerestrictions = array();
2386 if ( isset( $this->mCascadeSources
) && $getPages ) {
2387 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2388 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2389 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2392 wfProfileIn( __METHOD__
);
2394 $dbr = wfGetDB( DB_SLAVE
);
2396 if ( $this->getNamespace() == NS_FILE
) {
2397 $tables = array( 'imagelinks', 'page_restrictions' );
2398 $where_clauses = array(
2399 'il_to' => $this->getDBkey(),
2404 $tables = array( 'templatelinks', 'page_restrictions' );
2405 $where_clauses = array(
2406 'tl_namespace' => $this->getNamespace(),
2407 'tl_title' => $this->getDBkey(),
2414 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2415 'pr_expiry', 'pr_type', 'pr_level' );
2416 $where_clauses[] = 'page_id=pr_page';
2419 $cols = array( 'pr_expiry' );
2422 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2424 $sources = $getPages ?
array() : false;
2425 $now = wfTimestampNow();
2426 $purgeExpired = false;
2428 foreach ( $res as $row ) {
2429 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2430 if ( $expiry > $now ) {
2432 $page_id = $row->pr_page
;
2433 $page_ns = $row->page_namespace
;
2434 $page_title = $row->page_title
;
2435 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2436 # Add groups needed for each restriction type if its not already there
2437 # Make sure this restriction type still exists
2439 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2440 $pagerestrictions[$row->pr_type
] = array();
2443 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2444 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2445 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2451 // Trigger lazy purge of expired restrictions from the db
2452 $purgeExpired = true;
2455 if ( $purgeExpired ) {
2456 Title
::purgeExpiredRestrictions();
2460 $this->mCascadeSources
= $sources;
2461 $this->mCascadingRestrictions
= $pagerestrictions;
2463 $this->mHasCascadingRestrictions
= $sources;
2466 wfProfileOut( __METHOD__
);
2467 return array( $sources, $pagerestrictions );
2471 * Accessor/initialisation for mRestrictions
2473 * @param $action String action that permission needs to be checked for
2474 * @return Array of Strings the array of groups allowed to edit this article
2476 public function getRestrictions( $action ) {
2477 if ( !$this->mRestrictionsLoaded
) {
2478 $this->loadRestrictions();
2480 return isset( $this->mRestrictions
[$action] )
2481 ?
$this->mRestrictions
[$action]
2486 * Get the expiry time for the restriction against a given action
2489 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2490 * or not protected at all, or false if the action is not recognised.
2492 public function getRestrictionExpiry( $action ) {
2493 if ( !$this->mRestrictionsLoaded
) {
2494 $this->loadRestrictions();
2496 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2500 * Returns cascading restrictions for the current article
2504 function areRestrictionsCascading() {
2505 if ( !$this->mRestrictionsLoaded
) {
2506 $this->loadRestrictions();
2509 return $this->mCascadeRestriction
;
2513 * Loads a string into mRestrictions array
2515 * @param $res Resource restrictions as an SQL result.
2516 * @param $oldFashionedRestrictions String comma-separated list of page
2517 * restrictions from page table (pre 1.10)
2519 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2522 foreach ( $res as $row ) {
2526 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2530 * Compiles list of active page restrictions from both page table (pre 1.10)
2531 * and page_restrictions table for this existing page.
2532 * Public for usage by LiquidThreads.
2534 * @param $rows array of db result objects
2535 * @param $oldFashionedRestrictions string comma-separated list of page
2536 * restrictions from page table (pre 1.10)
2538 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2540 $dbr = wfGetDB( DB_SLAVE
);
2542 $restrictionTypes = $this->getRestrictionTypes();
2544 foreach ( $restrictionTypes as $type ) {
2545 $this->mRestrictions
[$type] = array();
2546 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2549 $this->mCascadeRestriction
= false;
2551 # Backwards-compatibility: also load the restrictions from the page record (old format).
2553 if ( $oldFashionedRestrictions === null ) {
2554 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2555 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2558 if ( $oldFashionedRestrictions != '' ) {
2560 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2561 $temp = explode( '=', trim( $restrict ) );
2562 if ( count( $temp ) == 1 ) {
2563 // old old format should be treated as edit/move restriction
2564 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2565 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2567 $restriction = trim( $temp[1] );
2568 if( $restriction != '' ) { //some old entries are empty
2569 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2574 $this->mOldRestrictions
= true;
2578 if ( count( $rows ) ) {
2579 # Current system - load second to make them override.
2580 $now = wfTimestampNow();
2581 $purgeExpired = false;
2583 # Cycle through all the restrictions.
2584 foreach ( $rows as $row ) {
2586 // Don't take care of restrictions types that aren't allowed
2587 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2590 // This code should be refactored, now that it's being used more generally,
2591 // But I don't really see any harm in leaving it in Block for now -werdna
2592 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2594 // Only apply the restrictions if they haven't expired!
2595 if ( !$expiry ||
$expiry > $now ) {
2596 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2597 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2599 $this->mCascadeRestriction |
= $row->pr_cascade
;
2601 // Trigger a lazy purge of expired restrictions
2602 $purgeExpired = true;
2606 if ( $purgeExpired ) {
2607 Title
::purgeExpiredRestrictions();
2611 $this->mRestrictionsLoaded
= true;
2615 * Load restrictions from the page_restrictions table
2617 * @param $oldFashionedRestrictions String comma-separated list of page
2618 * restrictions from page table (pre 1.10)
2620 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2622 if ( !$this->mRestrictionsLoaded
) {
2623 if ( $this->exists() ) {
2624 $dbr = wfGetDB( DB_SLAVE
);
2626 $res = $dbr->select(
2627 'page_restrictions',
2629 array( 'pr_page' => $this->getArticleID() ),
2633 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2635 $title_protection = $this->getTitleProtection();
2637 if ( $title_protection ) {
2638 $now = wfTimestampNow();
2639 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2641 if ( !$expiry ||
$expiry > $now ) {
2642 // Apply the restrictions
2643 $this->mRestrictionsExpiry
['create'] = $expiry;
2644 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2645 } else { // Get rid of the old restrictions
2646 Title
::purgeExpiredRestrictions();
2647 $this->mTitleProtection
= false;
2650 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2652 $this->mRestrictionsLoaded
= true;
2658 * Flush the protection cache in this object and force reload from the database.
2659 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2661 public function flushRestrictions() {
2662 $this->mRestrictionsLoaded
= false;
2663 $this->mTitleProtection
= null;
2667 * Purge expired restrictions from the page_restrictions table
2669 static function purgeExpiredRestrictions() {
2670 $dbw = wfGetDB( DB_MASTER
);
2672 'page_restrictions',
2673 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2679 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2685 * Does this have subpages? (Warning, usually requires an extra DB query.)
2689 public function hasSubpages() {
2690 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2695 # We dynamically add a member variable for the purpose of this method
2696 # alone to cache the result. There's no point in having it hanging
2697 # around uninitialized in every Title object; therefore we only add it
2698 # if needed and don't declare it statically.
2699 if ( isset( $this->mHasSubpages
) ) {
2700 return $this->mHasSubpages
;
2703 $subpages = $this->getSubpages( 1 );
2704 if ( $subpages instanceof TitleArray
) {
2705 return $this->mHasSubpages
= (bool)$subpages->count();
2707 return $this->mHasSubpages
= false;
2711 * Get all subpages of this page.
2713 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2714 * @return mixed TitleArray, or empty array if this page's namespace
2715 * doesn't allow subpages
2717 public function getSubpages( $limit = -1 ) {
2718 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2722 $dbr = wfGetDB( DB_SLAVE
);
2723 $conds['page_namespace'] = $this->getNamespace();
2724 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2726 if ( $limit > -1 ) {
2727 $options['LIMIT'] = $limit;
2729 return $this->mSubpages
= TitleArray
::newFromResult(
2730 $dbr->select( 'page',
2731 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2740 * Is there a version of this page in the deletion archive?
2742 * @return Int the number of archived revisions
2744 public function isDeleted() {
2745 if ( $this->getNamespace() < 0 ) {
2748 $dbr = wfGetDB( DB_SLAVE
);
2750 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2751 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2754 if ( $this->getNamespace() == NS_FILE
) {
2755 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2756 array( 'fa_name' => $this->getDBkey() ),
2765 * Is there a version of this page in the deletion archive?
2769 public function isDeletedQuick() {
2770 if ( $this->getNamespace() < 0 ) {
2773 $dbr = wfGetDB( DB_SLAVE
);
2774 $deleted = (bool)$dbr->selectField( 'archive', '1',
2775 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2778 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2779 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2780 array( 'fa_name' => $this->getDBkey() ),
2788 * Get the article ID for this Title from the link cache,
2789 * adding it if necessary
2791 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2793 * @return Int the ID
2795 public function getArticleID( $flags = 0 ) {
2796 if ( $this->getNamespace() < 0 ) {
2797 return $this->mArticleID
= 0;
2799 $linkCache = LinkCache
::singleton();
2800 if ( $flags & self
::GAID_FOR_UPDATE
) {
2801 $oldUpdate = $linkCache->forUpdate( true );
2802 $linkCache->clearLink( $this );
2803 $this->mArticleID
= $linkCache->addLinkObj( $this );
2804 $linkCache->forUpdate( $oldUpdate );
2806 if ( -1 == $this->mArticleID
) {
2807 $this->mArticleID
= $linkCache->addLinkObj( $this );
2810 return $this->mArticleID
;
2814 * Is this an article that is a redirect page?
2815 * Uses link cache, adding it if necessary
2817 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2820 public function isRedirect( $flags = 0 ) {
2821 if ( !is_null( $this->mRedirect
) ) {
2822 return $this->mRedirect
;
2824 # Calling getArticleID() loads the field from cache as needed
2825 if ( !$this->getArticleID( $flags ) ) {
2826 return $this->mRedirect
= false;
2828 $linkCache = LinkCache
::singleton();
2829 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2831 return $this->mRedirect
;
2835 * What is the length of this page?
2836 * Uses link cache, adding it if necessary
2838 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2841 public function getLength( $flags = 0 ) {
2842 if ( $this->mLength
!= -1 ) {
2843 return $this->mLength
;
2845 # Calling getArticleID() loads the field from cache as needed
2846 if ( !$this->getArticleID( $flags ) ) {
2847 return $this->mLength
= 0;
2849 $linkCache = LinkCache
::singleton();
2850 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2852 return $this->mLength
;
2856 * What is the page_latest field for this page?
2858 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2859 * @return Int or 0 if the page doesn't exist
2861 public function getLatestRevID( $flags = 0 ) {
2862 if ( $this->mLatestID
!== false ) {
2863 return intval( $this->mLatestID
);
2865 # Calling getArticleID() loads the field from cache as needed
2866 if ( !$this->getArticleID( $flags ) ) {
2867 return $this->mLatestID
= 0;
2869 $linkCache = LinkCache
::singleton();
2870 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2872 return $this->mLatestID
;
2876 * This clears some fields in this object, and clears any associated
2877 * keys in the "bad links" section of the link cache.
2879 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2880 * loading of the new page_id. It's also called from
2881 * WikiPage::doDeleteArticleReal()
2883 * @param $newid Int the new Article ID
2885 public function resetArticleID( $newid ) {
2886 $linkCache = LinkCache
::singleton();
2887 $linkCache->clearLink( $this );
2889 if ( $newid === false ) {
2890 $this->mArticleID
= -1;
2892 $this->mArticleID
= intval( $newid );
2894 $this->mRestrictionsLoaded
= false;
2895 $this->mRestrictions
= array();
2896 $this->mRedirect
= null;
2897 $this->mLength
= -1;
2898 $this->mLatestID
= false;
2899 $this->mEstimateRevisions
= null;
2903 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2905 * @param $text String containing title to capitalize
2906 * @param $ns int namespace index, defaults to NS_MAIN
2907 * @return String containing capitalized title
2909 public static function capitalize( $text, $ns = NS_MAIN
) {
2912 if ( MWNamespace
::isCapitalized( $ns ) ) {
2913 return $wgContLang->ucfirst( $text );
2920 * Secure and split - main initialisation function for this object
2922 * Assumes that mDbkeyform has been set, and is urldecoded
2923 * and uses underscores, but not otherwise munged. This function
2924 * removes illegal characters, splits off the interwiki and
2925 * namespace prefixes, sets the other forms, and canonicalizes
2928 * @return Bool true on success
2930 private function secureAndSplit() {
2931 global $wgContLang, $wgLocalInterwiki;
2934 $this->mInterwiki
= $this->mFragment
= '';
2935 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2937 $dbkey = $this->mDbkeyform
;
2939 # Strip Unicode bidi override characters.
2940 # Sometimes they slip into cut-n-pasted page titles, where the
2941 # override chars get included in list displays.
2942 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2944 # Clean up whitespace
2945 # Note: use of the /u option on preg_replace here will cause
2946 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2947 # conveniently disabling them.
2948 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2949 $dbkey = trim( $dbkey, '_' );
2951 if ( $dbkey == '' ) {
2955 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2956 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2960 $this->mDbkeyform
= $dbkey;
2962 # Initial colon indicates main namespace rather than specified default
2963 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2964 if ( ':' == $dbkey[0] ) {
2965 $this->mNamespace
= NS_MAIN
;
2966 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2967 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2970 # Namespace or interwiki prefix
2972 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2975 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2977 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2978 # Ordinary namespace
2980 $this->mNamespace
= $ns;
2981 # For Talk:X pages, check if X has a "namespace" prefix
2982 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2983 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2984 # Disallow Talk:File:x type titles...
2986 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2987 # Disallow Talk:Interwiki:x type titles...
2991 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2992 if ( !$firstPass ) {
2993 # Can't make a local interwiki link to an interwiki link.
2994 # That's just crazy!
3000 $this->mInterwiki
= $wgContLang->lc( $p );
3002 # Redundant interwiki prefix to the local wiki
3003 if ( $wgLocalInterwiki !== false
3004 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3006 if ( $dbkey == '' ) {
3007 # Can't have an empty self-link
3010 $this->mInterwiki
= '';
3012 # Do another namespace split...
3016 # If there's an initial colon after the interwiki, that also
3017 # resets the default namespace
3018 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3019 $this->mNamespace
= NS_MAIN
;
3020 $dbkey = substr( $dbkey, 1 );
3023 # If there's no recognized interwiki or namespace,
3024 # then let the colon expression be part of the title.
3029 # We already know that some pages won't be in the database!
3030 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3031 $this->mArticleID
= 0;
3033 $fragment = strstr( $dbkey, '#' );
3034 if ( false !== $fragment ) {
3035 $this->setFragment( $fragment );
3036 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3037 # remove whitespace again: prevents "Foo_bar_#"
3038 # becoming "Foo_bar_"
3039 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3042 # Reject illegal characters.
3043 $rxTc = self
::getTitleInvalidRegex();
3044 if ( preg_match( $rxTc, $dbkey ) ) {
3048 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3049 # reachable due to the way web browsers deal with 'relative' URLs.
3050 # Also, they conflict with subpage syntax. Forbid them explicitly.
3051 if ( strpos( $dbkey, '.' ) !== false &&
3052 ( $dbkey === '.' ||
$dbkey === '..' ||
3053 strpos( $dbkey, './' ) === 0 ||
3054 strpos( $dbkey, '../' ) === 0 ||
3055 strpos( $dbkey, '/./' ) !== false ||
3056 strpos( $dbkey, '/../' ) !== false ||
3057 substr( $dbkey, -2 ) == '/.' ||
3058 substr( $dbkey, -3 ) == '/..' ) )
3063 # Magic tilde sequences? Nu-uh!
3064 if ( strpos( $dbkey, '~~~' ) !== false ) {
3068 # Limit the size of titles to 255 bytes. This is typically the size of the
3069 # underlying database field. We make an exception for special pages, which
3070 # don't need to be stored in the database, and may edge over 255 bytes due
3071 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3072 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3073 strlen( $dbkey ) > 512 )
3078 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3079 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3080 # other site might be case-sensitive.
3081 $this->mUserCaseDBKey
= $dbkey;
3082 if ( $this->mInterwiki
== '' ) {
3083 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3086 # Can't make a link to a namespace alone... "empty" local links can only be
3087 # self-links with a fragment identifier.
3088 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3092 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3093 // IP names are not allowed for accounts, and can only be referring to
3094 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3095 // there are numerous ways to present the same IP. Having sp:contribs scan
3096 // them all is silly and having some show the edits and others not is
3097 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3098 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3099 ? IP
::sanitizeIP( $dbkey )
3102 // Any remaining initial :s are illegal.
3103 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3108 $this->mDbkeyform
= $dbkey;
3109 $this->mUrlform
= wfUrlencode( $dbkey );
3111 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3117 * Get an array of Title objects linking to this Title
3118 * Also stores the IDs in the link cache.
3120 * WARNING: do not use this function on arbitrary user-supplied titles!
3121 * On heavily-used templates it will max out the memory.
3123 * @param $options Array: may be FOR UPDATE
3124 * @param $table String: table name
3125 * @param $prefix String: fields prefix
3126 * @return Array of Title objects linking here
3128 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3129 if ( count( $options ) > 0 ) {
3130 $db = wfGetDB( DB_MASTER
);
3132 $db = wfGetDB( DB_SLAVE
);
3136 array( 'page', $table ),
3137 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3139 "{$prefix}_from=page_id",
3140 "{$prefix}_namespace" => $this->getNamespace(),
3141 "{$prefix}_title" => $this->getDBkey() ),
3147 if ( $res->numRows() ) {
3148 $linkCache = LinkCache
::singleton();
3149 foreach ( $res as $row ) {
3150 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3152 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3153 $retVal[] = $titleObj;
3161 * Get an array of Title objects using this Title as a template
3162 * Also stores the IDs in the link cache.
3164 * WARNING: do not use this function on arbitrary user-supplied titles!
3165 * On heavily-used templates it will max out the memory.
3167 * @param $options Array: may be FOR UPDATE
3168 * @return Array of Title the Title objects linking here
3170 public function getTemplateLinksTo( $options = array() ) {
3171 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3175 * Get an array of Title objects linked from this Title
3176 * Also stores the IDs in the link cache.
3178 * WARNING: do not use this function on arbitrary user-supplied titles!
3179 * On heavily-used templates it will max out the memory.
3181 * @param $options Array: may be FOR UPDATE
3182 * @param $table String: table name
3183 * @param $prefix String: fields prefix
3184 * @return Array of Title objects linking here
3186 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3187 $id = $this->getArticleID();
3189 # If the page doesn't exist; there can't be any link from this page
3194 if ( count( $options ) > 0 ) {
3195 $db = wfGetDB( DB_MASTER
);
3197 $db = wfGetDB( DB_SLAVE
);
3200 $namespaceFiled = "{$prefix}_namespace";
3201 $titleField = "{$prefix}_title";
3204 array( $table, 'page' ),
3205 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3206 array( "{$prefix}_from" => $id ),
3209 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3213 if ( $res->numRows() ) {
3214 $linkCache = LinkCache
::singleton();
3215 foreach ( $res as $row ) {
3216 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3218 if ( $row->page_id
) {
3219 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3221 $linkCache->addBadLinkObj( $titleObj );
3223 $retVal[] = $titleObj;
3231 * Get an array of Title objects used on this Title as a template
3232 * Also stores the IDs in the link cache.
3234 * WARNING: do not use this function on arbitrary user-supplied titles!
3235 * On heavily-used templates it will max out the memory.
3237 * @param $options Array: may be FOR UPDATE
3238 * @return Array of Title the Title objects used here
3240 public function getTemplateLinksFrom( $options = array() ) {
3241 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3245 * Get an array of Title objects referring to non-existent articles linked from this page
3247 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3248 * @return Array of Title the Title objects
3250 public function getBrokenLinksFrom() {
3251 if ( $this->getArticleID() == 0 ) {
3252 # All links from article ID 0 are false positives
3256 $dbr = wfGetDB( DB_SLAVE
);
3257 $res = $dbr->select(
3258 array( 'page', 'pagelinks' ),
3259 array( 'pl_namespace', 'pl_title' ),
3261 'pl_from' => $this->getArticleID(),
3262 'page_namespace IS NULL'
3264 __METHOD__
, array(),
3268 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3274 foreach ( $res as $row ) {
3275 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3282 * Get a list of URLs to purge from the Squid cache when this
3285 * @return Array of String the URLs
3287 public function getSquidURLs() {
3289 $this->getInternalURL(),
3290 $this->getInternalURL( 'action=history' )
3293 $pageLang = $this->getPageLanguage();
3294 if ( $pageLang->hasVariants() ) {
3295 $variants = $pageLang->getVariants();
3296 foreach ( $variants as $vCode ) {
3297 $urls[] = $this->getInternalURL( '', $vCode );
3305 * Purge all applicable Squid URLs
3307 public function purgeSquid() {
3309 if ( $wgUseSquid ) {
3310 $urls = $this->getSquidURLs();
3311 $u = new SquidUpdate( $urls );
3317 * Move this page without authentication
3319 * @param $nt Title the new page Title
3320 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3322 public function moveNoAuth( &$nt ) {
3323 return $this->moveTo( $nt, false );
3327 * Check whether a given move operation would be valid.
3328 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3330 * @param $nt Title the new title
3331 * @param $auth Bool indicates whether $wgUser's permissions
3333 * @param $reason String is the log summary of the move, used for spam checking
3334 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3336 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3341 // Normally we'd add this to $errors, but we'll get
3342 // lots of syntax errors if $nt is not an object
3343 return array( array( 'badtitletext' ) );
3345 if ( $this->equals( $nt ) ) {
3346 $errors[] = array( 'selfmove' );
3348 if ( !$this->isMovable() ) {
3349 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3351 if ( $nt->getInterwiki() != '' ) {
3352 $errors[] = array( 'immobile-target-namespace-iw' );
3354 if ( !$nt->isMovable() ) {
3355 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3358 $oldid = $this->getArticleID();
3359 $newid = $nt->getArticleID();
3361 if ( strlen( $nt->getDBkey() ) < 1 ) {
3362 $errors[] = array( 'articleexists' );
3364 if ( ( $this->getDBkey() == '' ) ||
3366 ( $nt->getDBkey() == '' ) ) {
3367 $errors[] = array( 'badarticleerror' );
3370 // Image-specific checks
3371 if ( $this->getNamespace() == NS_FILE
) {
3372 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3375 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3376 $errors[] = array( 'nonfile-cannot-move-to-file' );
3380 $errors = wfMergeErrorArrays( $errors,
3381 $this->getUserPermissionsErrors( 'move', $wgUser ),
3382 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3383 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3384 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3387 $match = EditPage
::matchSummarySpamRegex( $reason );
3388 if ( $match !== false ) {
3389 // This is kind of lame, won't display nice
3390 $errors[] = array( 'spamprotectiontext' );
3394 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3395 $errors[] = array( 'hookaborted', $err );
3398 # The move is allowed only if (1) the target doesn't exist, or
3399 # (2) the target is a redirect to the source, and has no history
3400 # (so we can undo bad moves right after they're done).
3402 if ( 0 != $newid ) { # Target exists; check for validity
3403 if ( !$this->isValidMoveTarget( $nt ) ) {
3404 $errors[] = array( 'articleexists' );
3407 $tp = $nt->getTitleProtection();
3408 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3409 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3410 $errors[] = array( 'cantmove-titleprotected' );
3413 if ( empty( $errors ) ) {
3420 * Check if the requested move target is a valid file move target
3421 * @param Title $nt Target title
3422 * @return array List of errors
3424 protected function validateFileMoveOperation( $nt ) {
3429 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3431 $file = wfLocalFile( $this );
3432 if ( $file->exists() ) {
3433 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3434 $errors[] = array( 'imageinvalidfilename' );
3436 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3437 $errors[] = array( 'imagetypemismatch' );
3441 if ( $nt->getNamespace() != NS_FILE
) {
3442 $errors[] = array( 'imagenocrossnamespace' );
3443 // From here we want to do checks on a file object, so if we can't
3444 // create one, we must return.
3448 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3450 $destFile = wfLocalFile( $nt );
3451 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3452 $errors[] = array( 'file-exists-sharedrepo' );
3459 * Move a title to a new location
3461 * @param $nt Title the new title
3462 * @param $auth Bool indicates whether $wgUser's permissions
3464 * @param $reason String the reason for the move
3465 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3466 * Ignored if the user doesn't have the suppressredirect right.
3467 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3469 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3471 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3472 if ( is_array( $err ) ) {
3473 // Auto-block user's IP if the account was "hard" blocked
3474 $wgUser->spreadAnyEditBlock();
3478 // If it is a file, move it first.
3479 // It is done before all other moving stuff is done because it's hard to revert.
3480 $dbw = wfGetDB( DB_MASTER
);
3481 if ( $this->getNamespace() == NS_FILE
) {
3482 $file = wfLocalFile( $this );
3483 if ( $file->exists() ) {
3484 $status = $file->move( $nt );
3485 if ( !$status->isOk() ) {
3486 return $status->getErrorsArray();
3489 // Clear RepoGroup process cache
3490 RepoGroup
::singleton()->clearCache( $this );
3491 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3494 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3495 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3496 $protected = $this->isProtected();
3498 // Do the actual move
3499 $this->moveToInternal( $nt, $reason, $createRedirect );
3501 // Refresh the sortkey for this row. Be careful to avoid resetting
3502 // cl_timestamp, which may disturb time-based lists on some sites.
3503 $prefixes = $dbw->select(
3505 array( 'cl_sortkey_prefix', 'cl_to' ),
3506 array( 'cl_from' => $pageid ),
3509 foreach ( $prefixes as $prefixRow ) {
3510 $prefix = $prefixRow->cl_sortkey_prefix
;
3511 $catTo = $prefixRow->cl_to
;
3512 $dbw->update( 'categorylinks',
3514 'cl_sortkey' => Collation
::singleton()->getSortKey(
3515 $nt->getCategorySortkey( $prefix ) ),
3516 'cl_timestamp=cl_timestamp' ),
3518 'cl_from' => $pageid,
3519 'cl_to' => $catTo ),
3524 $redirid = $this->getArticleID();
3527 # Protect the redirect title as the title used to be...
3528 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3530 'pr_page' => $redirid,
3531 'pr_type' => 'pr_type',
3532 'pr_level' => 'pr_level',
3533 'pr_cascade' => 'pr_cascade',
3534 'pr_user' => 'pr_user',
3535 'pr_expiry' => 'pr_expiry'
3537 array( 'pr_page' => $pageid ),
3541 # Update the protection log
3542 $log = new LogPage( 'protect' );
3543 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3545 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3547 // @todo FIXME: $params?
3548 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3552 $oldnamespace = $this->getNamespace() & ~
1;
3553 $newnamespace = $nt->getNamespace() & ~
1;
3554 $oldtitle = $this->getDBkey();
3555 $newtitle = $nt->getDBkey();
3557 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3558 WatchedItem
::duplicateEntries( $this, $nt );
3561 $dbw->commit( __METHOD__
);
3563 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3568 * Move page to a title which is either a redirect to the
3569 * source page or nonexistent
3571 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3572 * @param $reason String The reason for the move
3573 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3574 * if the user doesn't have the suppressredirect right
3575 * @throws MWException
3577 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3578 global $wgUser, $wgContLang;
3580 if ( $nt->exists() ) {
3581 $moveOverRedirect = true;
3582 $logType = 'move_redir';
3584 $moveOverRedirect = false;
3588 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3590 $logEntry = new ManualLogEntry( 'move', $logType );
3591 $logEntry->setPerformer( $wgUser );
3592 $logEntry->setTarget( $this );
3593 $logEntry->setComment( $reason );
3594 $logEntry->setParameters( array(
3595 '4::target' => $nt->getPrefixedText(),
3596 '5::noredir' => $redirectSuppressed ?
'1': '0',
3599 $formatter = LogFormatter
::newFromEntry( $logEntry );
3600 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3601 $comment = $formatter->getPlainActionText();
3603 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3605 # Truncate for whole multibyte characters.
3606 $comment = $wgContLang->truncate( $comment, 255 );
3608 $oldid = $this->getArticleID();
3610 $dbw = wfGetDB( DB_MASTER
);
3612 $newpage = WikiPage
::factory( $nt );
3614 if ( $moveOverRedirect ) {
3615 $newid = $nt->getArticleID();
3617 # Delete the old redirect. We don't save it to history since
3618 # by definition if we've got here it's rather uninteresting.
3619 # We have to remove it so that the next step doesn't trigger
3620 # a conflict on the unique namespace+title index...
3621 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3623 $newpage->doDeleteUpdates( $newid );
3626 # Save a null revision in the page's history notifying of the move
3627 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3628 if ( !is_object( $nullRevision ) ) {
3629 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3631 $nullRevId = $nullRevision->insertOn( $dbw );
3633 # Change the name of the target page:
3634 $dbw->update( 'page',
3636 'page_namespace' => $nt->getNamespace(),
3637 'page_title' => $nt->getDBkey(),
3639 /* WHERE */ array( 'page_id' => $oldid ),
3643 $this->resetArticleID( 0 );
3644 $nt->resetArticleID( $oldid );
3646 $newpage->updateRevisionOn( $dbw, $nullRevision );
3648 wfRunHooks( 'NewRevisionFromEditComplete',
3649 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3651 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3653 if ( !$moveOverRedirect ) {
3654 WikiPage
::onArticleCreate( $nt );
3657 # Recreate the redirect, this time in the other direction.
3658 if ( $redirectSuppressed ) {
3659 WikiPage
::onArticleDelete( $this );
3661 $mwRedir = MagicWord
::get( 'redirect' );
3662 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3663 $redirectArticle = WikiPage
::factory( $this );
3664 $newid = $redirectArticle->insertOn( $dbw );
3665 if ( $newid ) { // sanity
3666 $redirectRevision = new Revision( array(
3668 'comment' => $comment,
3669 'text' => $redirectText ) );
3670 $redirectRevision->insertOn( $dbw );
3671 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3673 wfRunHooks( 'NewRevisionFromEditComplete',
3674 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3676 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3681 $logid = $logEntry->insert();
3682 $logEntry->publish( $logid );
3686 * Move this page's subpages to be subpages of $nt
3688 * @param $nt Title Move target
3689 * @param $auth bool Whether $wgUser's permissions should be checked
3690 * @param $reason string The reason for the move
3691 * @param $createRedirect bool Whether to create redirects from the old subpages to
3692 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3693 * @return mixed array with old page titles as keys, and strings (new page titles) or
3694 * arrays (errors) as values, or an error array with numeric indices if no pages
3697 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3698 global $wgMaximumMovedPages;
3699 // Check permissions
3700 if ( !$this->userCan( 'move-subpages' ) ) {
3701 return array( 'cant-move-subpages' );
3703 // Do the source and target namespaces support subpages?
3704 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3705 return array( 'namespace-nosubpages',
3706 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3708 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3709 return array( 'namespace-nosubpages',
3710 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3713 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3716 foreach ( $subpages as $oldSubpage ) {
3718 if ( $count > $wgMaximumMovedPages ) {
3719 $retval[$oldSubpage->getPrefixedTitle()] =
3720 array( 'movepage-max-pages',
3721 $wgMaximumMovedPages );
3725 // We don't know whether this function was called before
3726 // or after moving the root page, so check both
3728 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3729 $oldSubpage->getArticleID() == $nt->getArticleID() )
3731 // When moving a page to a subpage of itself,
3732 // don't move it twice
3735 $newPageName = preg_replace(
3736 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3737 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3738 $oldSubpage->getDBkey() );
3739 if ( $oldSubpage->isTalkPage() ) {
3740 $newNs = $nt->getTalkPage()->getNamespace();
3742 $newNs = $nt->getSubjectPage()->getNamespace();
3744 # Bug 14385: we need makeTitleSafe because the new page names may
3745 # be longer than 255 characters.
3746 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3748 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3749 if ( $success === true ) {
3750 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3752 $retval[$oldSubpage->getPrefixedText()] = $success;
3759 * Checks if this page is just a one-rev redirect.
3760 * Adds lock, so don't use just for light purposes.
3764 public function isSingleRevRedirect() {
3765 $dbw = wfGetDB( DB_MASTER
);
3767 $row = $dbw->selectRow( 'page',
3768 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3771 array( 'FOR UPDATE' )
3773 # Cache some fields we may want
3774 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3775 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3776 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3777 if ( !$this->mRedirect
) {
3780 # Does the article have a history?
3781 $row = $dbw->selectField( array( 'page', 'revision' ),
3783 array( 'page_namespace' => $this->getNamespace(),
3784 'page_title' => $this->getDBkey(),
3786 'page_latest != rev_id'
3789 array( 'FOR UPDATE' )
3791 # Return true if there was no history
3792 return ( $row === false );
3796 * Checks if $this can be moved to a given Title
3797 * - Selects for update, so don't call it unless you mean business
3799 * @param $nt Title the new title to check
3802 public function isValidMoveTarget( $nt ) {
3803 # Is it an existing file?
3804 if ( $nt->getNamespace() == NS_FILE
) {
3805 $file = wfLocalFile( $nt );
3806 if ( $file->exists() ) {
3807 wfDebug( __METHOD__
. ": file exists\n" );
3811 # Is it a redirect with no history?
3812 if ( !$nt->isSingleRevRedirect() ) {
3813 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3816 # Get the article text
3817 $rev = Revision
::newFromTitle( $nt );
3818 if( !is_object( $rev ) ){
3821 $text = $rev->getText();
3822 # Does the redirect point to the source?
3823 # Or is it a broken self-redirect, usually caused by namespace collisions?
3825 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3826 $redirTitle = Title
::newFromText( $m[1] );
3827 if ( !is_object( $redirTitle ) ||
3828 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3829 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3830 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3835 wfDebug( __METHOD__
. ": failsafe\n" );
3842 * Get categories to which this Title belongs and return an array of
3843 * categories' names.
3845 * @return Array of parents in the form:
3846 * $parent => $currentarticle
3848 public function getParentCategories() {
3853 $titleKey = $this->getArticleID();
3855 if ( $titleKey === 0 ) {
3859 $dbr = wfGetDB( DB_SLAVE
);
3861 $res = $dbr->select( 'categorylinks', '*',
3863 'cl_from' => $titleKey,
3869 if ( $dbr->numRows( $res ) > 0 ) {
3870 foreach ( $res as $row ) {
3871 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3872 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3879 * Get a tree of parent categories
3881 * @param $children Array with the children in the keys, to check for circular refs
3882 * @return Array Tree of parent categories
3884 public function getParentCategoryTree( $children = array() ) {
3886 $parents = $this->getParentCategories();
3889 foreach ( $parents as $parent => $current ) {
3890 if ( array_key_exists( $parent, $children ) ) {
3891 # Circular reference
3892 $stack[$parent] = array();
3894 $nt = Title
::newFromText( $parent );
3896 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3906 * Get an associative array for selecting this title from
3909 * @return Array suitable for the $where parameter of DB::select()
3911 public function pageCond() {
3912 if ( $this->mArticleID
> 0 ) {
3913 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3914 return array( 'page_id' => $this->mArticleID
);
3916 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3921 * Get the revision ID of the previous revision
3923 * @param $revId Int Revision ID. Get the revision that was before this one.
3924 * @param $flags Int Title::GAID_FOR_UPDATE
3925 * @return Int|Bool Old revision ID, or FALSE if none exists
3927 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3928 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3929 $revId = $db->selectField( 'revision', 'rev_id',
3931 'rev_page' => $this->getArticleID( $flags ),
3932 'rev_id < ' . intval( $revId )
3935 array( 'ORDER BY' => 'rev_id DESC' )
3938 if ( $revId === false ) {
3941 return intval( $revId );
3946 * Get the revision ID of the next revision
3948 * @param $revId Int Revision ID. Get the revision that was after this one.
3949 * @param $flags Int Title::GAID_FOR_UPDATE
3950 * @return Int|Bool Next revision ID, or FALSE if none exists
3952 public function getNextRevisionID( $revId, $flags = 0 ) {
3953 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3954 $revId = $db->selectField( 'revision', 'rev_id',
3956 'rev_page' => $this->getArticleID( $flags ),
3957 'rev_id > ' . intval( $revId )
3960 array( 'ORDER BY' => 'rev_id' )
3963 if ( $revId === false ) {
3966 return intval( $revId );
3971 * Get the first revision of the page
3973 * @param $flags Int Title::GAID_FOR_UPDATE
3974 * @return Revision|Null if page doesn't exist
3976 public function getFirstRevision( $flags = 0 ) {
3977 $pageId = $this->getArticleID( $flags );
3979 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3980 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3981 array( 'rev_page' => $pageId ),
3983 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3986 return new Revision( $row );
3993 * Get the oldest revision timestamp of this page
3995 * @param $flags Int Title::GAID_FOR_UPDATE
3996 * @return String: MW timestamp
3998 public function getEarliestRevTime( $flags = 0 ) {
3999 $rev = $this->getFirstRevision( $flags );
4000 return $rev ?
$rev->getTimestamp() : null;
4004 * Check if this is a new page
4008 public function isNewPage() {
4009 $dbr = wfGetDB( DB_SLAVE
);
4010 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4014 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4018 public function isBigDeletion() {
4019 global $wgDeleteRevisionsLimit;
4021 if ( !$wgDeleteRevisionsLimit ) {
4025 $revCount = $this->estimateRevisionCount();
4026 return $revCount > $wgDeleteRevisionsLimit;
4030 * Get the approximate revision count of this page.
4034 public function estimateRevisionCount() {
4035 if ( !$this->exists() ) {
4039 if ( $this->mEstimateRevisions
=== null ) {
4040 $dbr = wfGetDB( DB_SLAVE
);
4041 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4042 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4045 return $this->mEstimateRevisions
;
4049 * Get the number of revisions between the given revision.
4050 * Used for diffs and other things that really need it.
4052 * @param $old int|Revision Old revision or rev ID (first before range)
4053 * @param $new int|Revision New revision or rev ID (first after range)
4054 * @return Int Number of revisions between these revisions.
4056 public function countRevisionsBetween( $old, $new ) {
4057 if ( !( $old instanceof Revision
) ) {
4058 $old = Revision
::newFromTitle( $this, (int)$old );
4060 if ( !( $new instanceof Revision
) ) {
4061 $new = Revision
::newFromTitle( $this, (int)$new );
4063 if ( !$old ||
!$new ) {
4064 return 0; // nothing to compare
4066 $dbr = wfGetDB( DB_SLAVE
);
4067 return (int)$dbr->selectField( 'revision', 'count(*)',
4069 'rev_page' => $this->getArticleID(),
4070 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4071 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4078 * Get the number of authors between the given revision IDs.
4079 * Used for diffs and other things that really need it.
4081 * @param $old int|Revision Old revision or rev ID (first before range)
4082 * @param $new int|Revision New revision or rev ID (first after range)
4083 * @param $limit Int Maximum number of authors
4084 * @return Int Number of revision authors between these revisions.
4086 public function countAuthorsBetween( $old, $new, $limit ) {
4087 if ( !( $old instanceof Revision
) ) {
4088 $old = Revision
::newFromTitle( $this, (int)$old );
4090 if ( !( $new instanceof Revision
) ) {
4091 $new = Revision
::newFromTitle( $this, (int)$new );
4093 if ( !$old ||
!$new ) {
4094 return 0; // nothing to compare
4096 $dbr = wfGetDB( DB_SLAVE
);
4097 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4099 'rev_page' => $this->getArticleID(),
4100 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4101 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4103 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4105 return (int)$dbr->numRows( $res );
4109 * Compare with another title.
4111 * @param $title Title
4114 public function equals( Title
$title ) {
4115 // Note: === is necessary for proper matching of number-like titles.
4116 return $this->getInterwiki() === $title->getInterwiki()
4117 && $this->getNamespace() == $title->getNamespace()
4118 && $this->getDBkey() === $title->getDBkey();
4122 * Check if this title is a subpage of another title
4124 * @param $title Title
4127 public function isSubpageOf( Title
$title ) {
4128 return $this->getInterwiki() === $title->getInterwiki()
4129 && $this->getNamespace() == $title->getNamespace()
4130 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4134 * Check if page exists. For historical reasons, this function simply
4135 * checks for the existence of the title in the page table, and will
4136 * thus return false for interwiki links, special pages and the like.
4137 * If you want to know if a title can be meaningfully viewed, you should
4138 * probably call the isKnown() method instead.
4142 public function exists() {
4143 return $this->getArticleID() != 0;
4147 * Should links to this title be shown as potentially viewable (i.e. as
4148 * "bluelinks"), even if there's no record by this title in the page
4151 * This function is semi-deprecated for public use, as well as somewhat
4152 * misleadingly named. You probably just want to call isKnown(), which
4153 * calls this function internally.
4155 * (ISSUE: Most of these checks are cheap, but the file existence check
4156 * can potentially be quite expensive. Including it here fixes a lot of
4157 * existing code, but we might want to add an optional parameter to skip
4158 * it and any other expensive checks.)
4162 public function isAlwaysKnown() {
4166 * Allows overriding default behaviour for determining if a page exists.
4167 * If $isKnown is kept as null, regular checks happen. If it's
4168 * a boolean, this value is returned by the isKnown method.
4172 * @param Title $title
4173 * @param boolean|null $isKnown
4175 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4177 if ( !is_null( $isKnown ) ) {
4181 if ( $this->mInterwiki
!= '' ) {
4182 return true; // any interwiki link might be viewable, for all we know
4185 switch( $this->mNamespace
) {
4188 // file exists, possibly in a foreign repo
4189 return (bool)wfFindFile( $this );
4191 // valid special page
4192 return SpecialPageFactory
::exists( $this->getDBkey() );
4194 // selflink, possibly with fragment
4195 return $this->mDbkeyform
== '';
4197 // known system message
4198 return $this->hasSourceText() !== false;
4205 * Does this title refer to a page that can (or might) be meaningfully
4206 * viewed? In particular, this function may be used to determine if
4207 * links to the title should be rendered as "bluelinks" (as opposed to
4208 * "redlinks" to non-existent pages).
4209 * Adding something else to this function will cause inconsistency
4210 * since LinkHolderArray calls isAlwaysKnown() and does its own
4211 * page existence check.
4215 public function isKnown() {
4216 return $this->isAlwaysKnown() ||
$this->exists();
4220 * Does this page have source text?
4224 public function hasSourceText() {
4225 if ( $this->exists() ) {
4229 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4230 // If the page doesn't exist but is a known system message, default
4231 // message content will be displayed, same for language subpages-
4232 // Use always content language to avoid loading hundreds of languages
4233 // to get the link color.
4235 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4236 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4237 return $message->exists();
4244 * Get the default message text or false if the message doesn't exist
4246 * @return String or false
4248 public function getDefaultMessageText() {
4251 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4255 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4256 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4258 if ( $message->exists() ) {
4259 return $message->plain();
4266 * Updates page_touched for this page; called from LinksUpdate.php
4268 * @return Bool true if the update succeded
4270 public function invalidateCache() {
4271 if ( wfReadOnly() ) {
4274 $dbw = wfGetDB( DB_MASTER
);
4275 $success = $dbw->update(
4277 array( 'page_touched' => $dbw->timestamp() ),
4281 HTMLFileCache
::clearFileCache( $this );
4286 * Update page_touched timestamps and send squid purge messages for
4287 * pages linking to this title. May be sent to the job queue depending
4288 * on the number of links. Typically called on create and delete.
4290 public function touchLinks() {
4291 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4294 if ( $this->getNamespace() == NS_CATEGORY
) {
4295 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4301 * Get the last touched timestamp
4303 * @param $db DatabaseBase: optional db
4304 * @return String last-touched timestamp
4306 public function getTouched( $db = null ) {
4307 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4308 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4313 * Get the timestamp when this page was updated since the user last saw it.
4316 * @return String|Null
4318 public function getNotificationTimestamp( $user = null ) {
4319 global $wgUser, $wgShowUpdatedMarker;
4320 // Assume current user if none given
4324 // Check cache first
4325 $uid = $user->getId();
4326 // avoid isset here, as it'll return false for null entries
4327 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4328 return $this->mNotificationTimestamp
[$uid];
4330 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4331 return $this->mNotificationTimestamp
[$uid] = false;
4333 // Don't cache too much!
4334 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4335 $this->mNotificationTimestamp
= array();
4337 $dbr = wfGetDB( DB_SLAVE
);
4338 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4339 'wl_notificationtimestamp',
4341 'wl_user' => $user->getId(),
4342 'wl_namespace' => $this->getNamespace(),
4343 'wl_title' => $this->getDBkey(),
4347 return $this->mNotificationTimestamp
[$uid];
4351 * Generate strings used for xml 'id' names in monobook tabs
4353 * @param $prepend string defaults to 'nstab-'
4354 * @return String XML 'id' name
4356 public function getNamespaceKey( $prepend = 'nstab-' ) {
4358 // Gets the subject namespace if this title
4359 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4360 // Checks if cononical namespace name exists for namespace
4361 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4362 // Uses canonical namespace name
4363 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4365 // Uses text of namespace
4366 $namespaceKey = $this->getSubjectNsText();
4368 // Makes namespace key lowercase
4369 $namespaceKey = $wgContLang->lc( $namespaceKey );
4371 if ( $namespaceKey == '' ) {
4372 $namespaceKey = 'main';
4374 // Changes file to image for backwards compatibility
4375 if ( $namespaceKey == 'file' ) {
4376 $namespaceKey = 'image';
4378 return $prepend . $namespaceKey;
4382 * Get all extant redirects to this Title
4384 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4385 * @return Array of Title redirects to this title
4387 public function getRedirectsHere( $ns = null ) {
4390 $dbr = wfGetDB( DB_SLAVE
);
4392 'rd_namespace' => $this->getNamespace(),
4393 'rd_title' => $this->getDBkey(),
4396 if ( !is_null( $ns ) ) {
4397 $where['page_namespace'] = $ns;
4400 $res = $dbr->select(
4401 array( 'redirect', 'page' ),
4402 array( 'page_namespace', 'page_title' ),
4407 foreach ( $res as $row ) {
4408 $redirs[] = self
::newFromRow( $row );
4414 * Check if this Title is a valid redirect target
4418 public function isValidRedirectTarget() {
4419 global $wgInvalidRedirectTargets;
4421 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4422 if ( $this->isSpecial( 'Userlogout' ) ) {
4426 foreach ( $wgInvalidRedirectTargets as $target ) {
4427 if ( $this->isSpecial( $target ) ) {
4436 * Get a backlink cache object
4438 * @return BacklinkCache
4440 function getBacklinkCache() {
4441 if ( is_null( $this->mBacklinkCache
) ) {
4442 $this->mBacklinkCache
= new BacklinkCache( $this );
4444 return $this->mBacklinkCache
;
4448 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4452 public function canUseNoindex() {
4453 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4455 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4456 ?
$wgContentNamespaces
4457 : $wgExemptFromUserRobotsControl;
4459 return !in_array( $this->mNamespace
, $bannedNamespaces );
4464 * Returns the raw sort key to be used for categories, with the specified
4465 * prefix. This will be fed to Collation::getSortKey() to get a
4466 * binary sortkey that can be used for actual sorting.
4468 * @param $prefix string The prefix to be used, specified using
4469 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4473 public function getCategorySortkey( $prefix = '' ) {
4474 $unprefixed = $this->getText();
4476 // Anything that uses this hook should only depend
4477 // on the Title object passed in, and should probably
4478 // tell the users to run updateCollations.php --force
4479 // in order to re-sort existing category relations.
4480 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4481 if ( $prefix !== '' ) {
4482 # Separate with a line feed, so the unprefixed part is only used as
4483 # a tiebreaker when two pages have the exact same prefix.
4484 # In UCA, tab is the only character that can sort above LF
4485 # so we strip both of them from the original prefix.
4486 $prefix = strtr( $prefix, "\n\t", ' ' );
4487 return "$prefix\n$unprefixed";
4493 * Get the language in which the content of this page is written.
4494 * Defaults to $wgContLang, but in certain cases it can be e.g.
4495 * $wgLang (such as special pages, which are in the user language).
4500 public function getPageLanguage() {
4502 if ( $this->isSpecialPage() ) {
4503 // special pages are in the user language
4505 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4506 // css/js should always be LTR and is, in fact, English
4507 return wfGetLangObj( 'en' );
4508 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4509 // Parse mediawiki messages with correct target language
4510 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4511 return wfGetLangObj( $lang );
4514 // If nothing special, it should be in the wiki content language
4515 $pageLang = $wgContLang;
4516 // Hook at the end because we don't want to override the above stuff
4517 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4518 return wfGetLangObj( $pageLang );