5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mCounter = -1; // /< Number of times this page has been viewed (-1 means "not loaded")
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
92 /*protected*/ function __construct() { }
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
104 $t->mDbkeyform
= $key;
105 if ( $t->secureAndSplit() ) {
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
138 return Title
::$titleCache[$text];
141 # Convert things like é ā or 〗 into normalized (bug 14952) text
142 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
145 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace
= $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN
) {
151 if ( $cachedcount >= self
::CACHE_MAX
) {
152 # Avoid memory leaks on mass operations...
153 Title
::$titleCache = array();
157 Title
::$titleCache[$text] =& $t;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform
= str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
210 if ( $row !== false ) {
211 $title = Title
::newFromRow( $row );
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
228 $dbr = wfGetDB( DB_SLAVE
);
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
241 foreach ( $res as $row ) {
242 $titles[] = Title
::newFromRow( $row );
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
255 $t->loadFromRow( $row );
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|false database row
266 public function loadFromRow( $row ) {
267 if ( $row ) { // page found
268 if ( isset( $row->page_id
) )
269 $this->mArticleID
= (int)$row->page_id
;
270 if ( isset( $row->page_len
) )
271 $this->mLength
= (int)$row->page_len
;
272 if ( isset( $row->page_is_redirect
) )
273 $this->mRedirect
= (bool)$row->page_is_redirect
;
274 if ( isset( $row->page_latest
) )
275 $this->mLatestID
= (int)$row->page_latest
;
276 if ( isset( $row->page_counter
) )
277 $this->mCounter
= (int)$row->page_counter
;
278 } else { // page not found
279 $this->mArticleID
= 0;
281 $this->mRedirect
= false;
282 $this->mLatestID
= 0;
288 * Create a new Title from a namespace index and a DB key.
289 * It's assumed that $ns and $title are *valid*, for instance when
290 * they came directly from the database or a special page name.
291 * For convenience, spaces are converted to underscores so that
292 * eg user_text fields can be used directly.
294 * @param $ns Int the namespace of the article
295 * @param $title String the unprefixed database key form
296 * @param $fragment String the link fragment (after the "#")
297 * @param $interwiki String the interwiki prefix
298 * @return Title the new object
300 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
302 $t->mInterwiki
= $interwiki;
303 $t->mFragment
= $fragment;
304 $t->mNamespace
= $ns = intval( $ns );
305 $t->mDbkeyform
= str_replace( ' ', '_', $title );
306 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
307 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
308 $t->mTextform
= str_replace( '_', ' ', $title );
313 * Create a new Title from a namespace index and a DB key.
314 * The parameters will be checked for validity, which is a bit slower
315 * than makeTitle() but safer for user-provided data.
317 * @param $ns Int the namespace of the article
318 * @param $title String database key form
319 * @param $fragment String the link fragment (after the "#")
320 * @param $interwiki String interwiki prefix
321 * @return Title the new object, or NULL on an error
323 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
325 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
326 if ( $t->secureAndSplit() ) {
334 * Create a new Title for the Main Page
336 * @return Title the new object
338 public static function newMainPage() {
339 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
340 // Don't give fatal errors if the message is broken
342 $title = Title
::newFromText( 'Main Page' );
348 * Extract a redirect destination from a string and return the
349 * Title, or null if the text doesn't contain a valid redirect
350 * This will only return the very next target, useful for
351 * the redirect table and other checks that don't need full recursion
353 * @param $text String: Text with possible redirect
354 * @return Title: The corresponding Title
356 public static function newFromRedirect( $text ) {
357 return self
::newFromRedirectInternal( $text );
361 * Extract a redirect destination from a string and return the
362 * Title, or null if the text doesn't contain a valid redirect
363 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
364 * in order to provide (hopefully) the Title of the final destination instead of another redirect
366 * @param $text String Text with possible redirect
369 public static function newFromRedirectRecurse( $text ) {
370 $titles = self
::newFromRedirectArray( $text );
371 return $titles ?
array_pop( $titles ) : null;
375 * Extract a redirect destination from a string and return an
376 * array of Titles, or null if the text doesn't contain a valid redirect
377 * The last element in the array is the final destination after all redirects
378 * have been resolved (up to $wgMaxRedirects times)
380 * @param $text String Text with possible redirect
381 * @return Array of Titles, with the destination last
383 public static function newFromRedirectArray( $text ) {
384 global $wgMaxRedirects;
385 $title = self
::newFromRedirectInternal( $text );
386 if ( is_null( $title ) ) {
389 // recursive check to follow double redirects
390 $recurse = $wgMaxRedirects;
391 $titles = array( $title );
392 while ( --$recurse > 0 ) {
393 if ( $title->isRedirect() ) {
394 $page = WikiPage
::factory( $title );
395 $newtitle = $page->getRedirectTarget();
399 // Redirects to some special pages are not permitted
400 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
401 // the new title passes the checks, so make that our current title so that further recursion can be checked
403 $titles[] = $newtitle;
412 * Really extract the redirect destination
413 * Do not call this function directly, use one of the newFromRedirect* functions above
415 * @param $text String Text with possible redirect
418 protected static function newFromRedirectInternal( $text ) {
419 global $wgMaxRedirects;
420 if ( $wgMaxRedirects < 1 ) {
421 //redirects are disabled, so quit early
424 $redir = MagicWord
::get( 'redirect' );
425 $text = trim( $text );
426 if ( $redir->matchStartAndRemove( $text ) ) {
427 // Extract the first link and see if it's usable
428 // Ensure that it really does come directly after #REDIRECT
429 // Some older redirects included a colon, so don't freak about that!
431 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
432 // Strip preceding colon used to "escape" categories, etc.
433 // and URL-decode links
434 if ( strpos( $m[1], '%' ) !== false ) {
435 // Match behavior of inline link parsing here;
436 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
438 $title = Title
::newFromText( $m[1] );
439 // If the title is a redirect to bad special pages or is invalid, return null
440 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
450 * Get the prefixed DB key associated with an ID
452 * @param $id Int the page_id of the article
453 * @return Title an object representing the article, or NULL if no such article was found
455 public static function nameOf( $id ) {
456 $dbr = wfGetDB( DB_SLAVE
);
458 $s = $dbr->selectRow(
460 array( 'page_namespace', 'page_title' ),
461 array( 'page_id' => $id ),
464 if ( $s === false ) {
468 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
473 * Get a regex character class describing the legal characters in a link
475 * @return String the list of characters, not delimited
477 public static function legalChars() {
478 global $wgLegalTitleChars;
479 return $wgLegalTitleChars;
483 * Returns a simple regex that will match on characters and sequences invalid in titles.
484 * Note that this doesn't pick up many things that could be wrong with titles, but that
485 * replacing this regex with something valid will make many titles valid.
487 * @return String regex string
489 static function getTitleInvalidRegex() {
490 static $rxTc = false;
492 # Matching titles will be held as illegal.
494 # Any character not allowed is forbidden...
495 '[^' . self
::legalChars() . ']' .
496 # URL percent encoding sequences interfere with the ability
497 # to round-trip titles -- you can't link to them consistently.
499 # XML/HTML character references produce similar issues.
500 '|&[A-Za-z0-9\x80-\xff]+;' .
502 '|&#x[0-9A-Fa-f]+;' .
510 * Get a string representation of a title suitable for
511 * including in a search index
513 * @param $ns Int a namespace index
514 * @param $title String text-form main part
515 * @return String a stripped-down title string ready for the search index
517 public static function indexTitle( $ns, $title ) {
520 $lc = SearchEngine
::legalSearchChars() . '&#;';
521 $t = $wgContLang->normalizeForSearch( $title );
522 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
523 $t = $wgContLang->lc( $t );
526 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
527 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
529 $t = preg_replace( "/\\s+/", ' ', $t );
531 if ( $ns == NS_FILE
) {
532 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
538 * Make a prefixed DB key from a DB key and a namespace index
540 * @param $ns Int numerical representation of the namespace
541 * @param $title String the DB key form the title
542 * @param $fragment String The link fragment (after the "#")
543 * @param $interwiki String The interwiki prefix
544 * @return String the prefixed form of the title
546 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
549 $namespace = $wgContLang->getNsText( $ns );
550 $name = $namespace == '' ?
$title : "$namespace:$title";
551 if ( strval( $interwiki ) != '' ) {
552 $name = "$interwiki:$name";
554 if ( strval( $fragment ) != '' ) {
555 $name .= '#' . $fragment;
561 * Escape a text fragment, say from a link, for a URL
563 * @param $fragment string containing a URL or link fragment (after the "#")
564 * @return String: escaped string
566 static function escapeFragmentForURL( $fragment ) {
567 # Note that we don't urlencode the fragment. urlencoded Unicode
568 # fragments appear not to work in IE (at least up to 7) or in at least
569 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
570 # to care if they aren't encoded.
571 return Sanitizer
::escapeId( $fragment, 'noninitial' );
575 * Callback for usort() to do title sorts by (namespace, title)
580 * @return Integer: result of string comparison, or namespace comparison
582 public static function compare( $a, $b ) {
583 if ( $a->getNamespace() == $b->getNamespace() ) {
584 return strcmp( $a->getText(), $b->getText() );
586 return $a->getNamespace() - $b->getNamespace();
591 * Determine whether the object refers to a page within
594 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
596 public function isLocal() {
597 if ( $this->mInterwiki
!= '' ) {
598 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
605 * Is this Title interwiki?
609 public function isExternal() {
610 return ( $this->mInterwiki
!= '' );
614 * Get the interwiki prefix (or null string)
616 * @return String Interwiki prefix
618 public function getInterwiki() {
619 return $this->mInterwiki
;
623 * Determine whether the object refers to a page within
624 * this project and is transcludable.
626 * @return Bool TRUE if this is transcludable
628 public function isTrans() {
629 if ( $this->mInterwiki
== '' ) {
633 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
637 * Returns the DB name of the distant wiki which owns the object.
639 * @return String the DB name
641 public function getTransWikiID() {
642 if ( $this->mInterwiki
== '' ) {
646 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
650 * Get the text form (spaces not underscores) of the main part
652 * @return String Main part of the title
654 public function getText() {
655 return $this->mTextform
;
659 * Get the URL-encoded form of the main part
661 * @return String Main part of the title, URL-encoded
663 public function getPartialURL() {
664 return $this->mUrlform
;
668 * Get the main part with underscores
670 * @return String: Main part of the title, with underscores
672 public function getDBkey() {
673 return $this->mDbkeyform
;
677 * Get the DB key with the initial letter case as specified by the user
679 * @return String DB key
681 function getUserCaseDBKey() {
682 return $this->mUserCaseDBKey
;
686 * Get the namespace index, i.e. one of the NS_xxxx constants.
688 * @return Integer: Namespace index
690 public function getNamespace() {
691 return $this->mNamespace
;
695 * Get the namespace text
697 * @return String: Namespace text
699 public function getNsText() {
702 if ( $this->mInterwiki
!= '' ) {
703 // This probably shouldn't even happen. ohh man, oh yuck.
704 // But for interwiki transclusion it sometimes does.
705 // Shit. Shit shit shit.
707 // Use the canonical namespaces if possible to try to
708 // resolve a foreign namespace.
709 if ( MWNamespace
::exists( $this->mNamespace
) ) {
710 return MWNamespace
::getCanonicalName( $this->mNamespace
);
714 // Strip off subpages
715 $pagename = $this->getText();
716 if ( strpos( $pagename, '/' ) !== false ) {
717 list( $username , ) = explode( '/', $pagename, 2 );
719 $username = $pagename;
722 if ( $wgContLang->needsGenderDistinction() &&
723 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
724 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
725 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
728 return $wgContLang->getNsText( $this->mNamespace
);
732 * Get the namespace text of the subject (rather than talk) page
734 * @return String Namespace text
736 public function getSubjectNsText() {
738 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
742 * Get the namespace text of the talk page
744 * @return String Namespace text
746 public function getTalkNsText() {
748 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
752 * Could this title have a corresponding talk page?
754 * @return Bool TRUE or FALSE
756 public function canTalk() {
757 return( MWNamespace
::canTalk( $this->mNamespace
) );
761 * Is this in a namespace that allows actual pages?
764 * @internal note -- uses hardcoded namespace index instead of constants
766 public function canExist() {
767 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
771 * Can this title be added to a user's watchlist?
773 * @return Bool TRUE or FALSE
775 public function isWatchable() {
776 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
780 * Returns true if this is a special page.
784 public function isSpecialPage() {
785 return $this->getNamespace() == NS_SPECIAL
;
789 * Returns true if this title resolves to the named special page
791 * @param $name String The special page name
794 public function isSpecial( $name ) {
795 if ( $this->isSpecialPage() ) {
796 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
797 if ( $name == $thisName ) {
805 * If the Title refers to a special page alias which is not the local default, resolve
806 * the alias, and localise the name as necessary. Otherwise, return $this
810 public function fixSpecialName() {
811 if ( $this->isSpecialPage() ) {
812 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
813 if ( $canonicalName ) {
814 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
815 if ( $localName != $this->mDbkeyform
) {
816 return Title
::makeTitle( NS_SPECIAL
, $localName );
824 * Returns true if the title is inside the specified namespace.
826 * Please make use of this instead of comparing to getNamespace()
827 * This function is much more resistant to changes we may make
828 * to namespaces than code that makes direct comparisons.
829 * @param $ns int The namespace
833 public function inNamespace( $ns ) {
834 return MWNamespace
::equals( $this->getNamespace(), $ns );
838 * Returns true if the title is inside one of the specified namespaces.
840 * @param ...$namespaces The namespaces to check for
844 public function inNamespaces( /* ... */ ) {
845 $namespaces = func_get_args();
846 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
847 $namespaces = $namespaces[0];
850 foreach ( $namespaces as $ns ) {
851 if ( $this->inNamespace( $ns ) ) {
860 * Returns true if the title has the same subject namespace as the
861 * namespace specified.
862 * For example this method will take NS_USER and return true if namespace
863 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
864 * as their subject namespace.
866 * This is MUCH simpler than individually testing for equivilance
867 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
870 public function hasSubjectNamespace( $ns ) {
871 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
875 * Is this Title in a namespace which contains content?
876 * In other words, is this a content page, for the purposes of calculating
881 public function isContentPage() {
882 return MWNamespace
::isContent( $this->getNamespace() );
886 * Would anybody with sufficient privileges be able to move this page?
887 * Some pages just aren't movable.
889 * @return Bool TRUE or FALSE
891 public function isMovable() {
892 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
893 // Interwiki title or immovable namespace. Hooks don't get to override here
898 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
903 * Is this the mainpage?
904 * @note Title::newFromText seams to be sufficiently optimized by the title
905 * cache that we don't need to over-optimize by doing direct comparisons and
906 * acidentally creating new bugs where $title->equals( Title::newFromText() )
907 * ends up reporting something differently than $title->isMainPage();
912 public function isMainPage() {
913 return $this->equals( Title
::newMainPage() );
921 public function isSubpage() {
922 return MWNamespace
::hasSubpages( $this->mNamespace
)
923 ?
strpos( $this->getText(), '/' ) !== false
928 * Is this a conversion table for the LanguageConverter?
932 public function isConversionTable() {
933 return $this->getNamespace() == NS_MEDIAWIKI
&&
934 strpos( $this->getText(), 'Conversiontable' ) !== false;
938 * Does that page contain wikitext, or it is JS, CSS or whatever?
942 public function isWikitextPage() {
943 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
944 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
949 * Could this page contain custom CSS or JavaScript, based
954 public function isCssOrJsPage() {
955 $retval = $this->mNamespace
== NS_MEDIAWIKI
956 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
957 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
962 * Is this a .css or .js subpage of a user page?
965 public function isCssJsSubpage() {
966 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
970 * Is this a *valid* .css or .js subpage of a user page?
973 * @deprecated since 1.17
975 public function isValidCssJsSubpage() {
976 return $this->isCssJsSubpage();
980 * Trim down a .css or .js subpage title to get the corresponding skin name
982 * @return string containing skin name from .css or .js subpage title
984 public function getSkinFromCssJsSubpage() {
985 $subpage = explode( '/', $this->mTextform
);
986 $subpage = $subpage[ count( $subpage ) - 1 ];
987 $lastdot = strrpos( $subpage, '.' );
988 if ( $lastdot === false )
989 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
990 return substr( $subpage, 0, $lastdot );
994 * Is this a .css subpage of a user page?
998 public function isCssSubpage() {
999 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1003 * Is this a .js subpage of a user page?
1007 public function isJsSubpage() {
1008 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1012 * Is this a talk page of some sort?
1016 public function isTalkPage() {
1017 return MWNamespace
::isTalk( $this->getNamespace() );
1021 * Get a Title object associated with the talk page of this article
1023 * @return Title the object for the talk page
1025 public function getTalkPage() {
1026 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1030 * Get a title object associated with the subject page of this
1033 * @return Title the object for the subject page
1035 public function getSubjectPage() {
1036 // Is this the same title?
1037 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1038 if ( $this->getNamespace() == $subjectNS ) {
1041 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1045 * Get the default namespace index, for when there is no namespace
1047 * @return Int Default namespace index
1049 public function getDefaultNamespace() {
1050 return $this->mDefaultNamespace
;
1054 * Get title for search index
1056 * @return String a stripped-down title string ready for the
1059 public function getIndexTitle() {
1060 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1064 * Get the Title fragment (i.e.\ the bit after the #) in text form
1066 * @return String Title fragment
1068 public function getFragment() {
1069 return $this->mFragment
;
1073 * Get the fragment in URL form, including the "#" character if there is one
1074 * @return String Fragment in URL form
1076 public function getFragmentForURL() {
1077 if ( $this->mFragment
== '' ) {
1080 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1085 * Set the fragment for this title. Removes the first character from the
1086 * specified fragment before setting, so it assumes you're passing it with
1089 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1090 * Still in active use privately.
1092 * @param $fragment String text
1094 public function setFragment( $fragment ) {
1095 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1099 * Prefix some arbitrary text with the namespace or interwiki prefix
1102 * @param $name String the text
1103 * @return String the prefixed text
1106 private function prefix( $name ) {
1108 if ( $this->mInterwiki
!= '' ) {
1109 $p = $this->mInterwiki
. ':';
1112 if ( 0 != $this->mNamespace
) {
1113 $p .= $this->getNsText() . ':';
1119 * Get the prefixed database key form
1121 * @return String the prefixed title, with underscores and
1122 * any interwiki and namespace prefixes
1124 public function getPrefixedDBkey() {
1125 $s = $this->prefix( $this->mDbkeyform
);
1126 $s = str_replace( ' ', '_', $s );
1131 * Get the prefixed title with spaces.
1132 * This is the form usually used for display
1134 * @return String the prefixed title, with spaces
1136 public function getPrefixedText() {
1137 // @todo FIXME: Bad usage of empty() ?
1138 if ( empty( $this->mPrefixedText
) ) {
1139 $s = $this->prefix( $this->mTextform
);
1140 $s = str_replace( '_', ' ', $s );
1141 $this->mPrefixedText
= $s;
1143 return $this->mPrefixedText
;
1147 * Return a string representation of this title
1149 * @return String representation of this title
1151 public function __toString() {
1152 return $this->getPrefixedText();
1156 * Get the prefixed title with spaces, plus any fragment
1157 * (part beginning with '#')
1159 * @return String the prefixed title, with spaces and the fragment, including '#'
1161 public function getFullText() {
1162 $text = $this->getPrefixedText();
1163 if ( $this->mFragment
!= '' ) {
1164 $text .= '#' . $this->mFragment
;
1170 * Get the base page name, i.e. the leftmost part before any slashes
1172 * @return String Base name
1174 public function getBaseText() {
1175 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1176 return $this->getText();
1179 $parts = explode( '/', $this->getText() );
1180 # Don't discard the real title if there's no subpage involved
1181 if ( count( $parts ) > 1 ) {
1182 unset( $parts[count( $parts ) - 1] );
1184 return implode( '/', $parts );
1188 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1190 * @return String Subpage name
1192 public function getSubpageText() {
1193 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1194 return( $this->mTextform
);
1196 $parts = explode( '/', $this->mTextform
);
1197 return( $parts[count( $parts ) - 1] );
1201 * Get the HTML-escaped displayable text form.
1202 * Used for the title field in <a> tags.
1204 * @return String the text, including any prefixes
1206 public function getEscapedText() {
1207 return htmlspecialchars( $this->getPrefixedText() );
1211 * Get a URL-encoded form of the subpage text
1213 * @return String URL-encoded subpage name
1215 public function getSubpageUrlForm() {
1216 $text = $this->getSubpageText();
1217 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1222 * Get a URL-encoded title (not an actual URL) including interwiki
1224 * @return String the URL-encoded form
1226 public function getPrefixedURL() {
1227 $s = $this->prefix( $this->mDbkeyform
);
1228 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1233 * Get a real URL referring to this title, with interwiki link and
1236 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
1237 * links. Can be specified as an associative array as well, e.g.,
1238 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1239 * @param $variant String language variant of url (for sr, zh..)
1240 * @return String the URL
1242 public function getFullURL( $query = '', $variant = false ) {
1243 # Hand off all the decisions on urls to getLocalURL
1244 $url = $this->getLocalURL( $query, $variant );
1246 # Expand the url to make it a full url. Note that getLocalURL has the
1247 # potential to output full urls for a variety of reasons, so we use
1248 # wfExpandUrl instead of simply prepending $wgServer
1249 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1251 # Finally, add the fragment.
1252 $url .= $this->getFragmentForURL();
1254 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
1259 * Get a URL with no fragment or server name. If this page is generated
1260 * with action=render, $wgServer is prepended.
1262 * @param $query Mixed: an optional query string; if not specified,
1263 * $wgArticlePath will be used. Can be specified as an associative array
1264 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
1266 * @param $variant String language variant of url (for sr, zh..)
1267 * @return String the URL
1269 public function getLocalURL( $query = '', $variant = false ) {
1270 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1271 global $wgVariantArticlePath;
1273 if ( is_array( $query ) ) {
1274 $query = wfArrayToCGI( $query );
1277 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1279 $namespace = $this->getNsText();
1280 if ( $namespace != '' ) {
1281 # Can this actually happen? Interwikis shouldn't be parsed.
1282 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1285 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1286 $url = wfAppendQuery( $url, $query );
1288 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1289 if ( $query == '' ) {
1290 if ( $variant != false && $this->getPageLanguage()->hasVariants() ) {
1291 if ( !$wgVariantArticlePath ) {
1292 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
1294 $variantArticlePath = $wgVariantArticlePath;
1296 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
1297 $url = str_replace( '$1', $dbkey, $url );
1299 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1300 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1303 global $wgActionPaths;
1306 if ( !empty( $wgActionPaths ) &&
1307 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1309 $action = urldecode( $matches[2] );
1310 if ( isset( $wgActionPaths[$action] ) ) {
1311 $query = $matches[1];
1312 if ( isset( $matches[4] ) ) {
1313 $query .= $matches[4];
1315 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1316 if ( $query != '' ) {
1317 $url = wfAppendQuery( $url, $query );
1322 if ( $url === false ) {
1323 if ( $query == '-' ) {
1326 $url = "{$wgScript}?title={$dbkey}&{$query}";
1330 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
1332 // @todo FIXME: This causes breakage in various places when we
1333 // actually expected a local URL and end up with dupe prefixes.
1334 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1335 $url = $wgServer . $url;
1338 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
1343 * Get a URL that's the simplest URL that will be valid to link, locally,
1344 * to the current Title. It includes the fragment, but does not include
1345 * the server unless action=render is used (or the link is external). If
1346 * there's a fragment but the prefixed text is empty, we just return a link
1349 * The result obviously should not be URL-escaped, but does need to be
1350 * HTML-escaped if it's being output in HTML.
1352 * @param $query Array of Strings An associative array of key => value pairs for the
1353 * query string. Keys and values will be escaped.
1354 * @param $variant String language variant of URL (for sr, zh..). Ignored
1355 * for external links. Default is "false" (same variant as current page,
1356 * for anonymous users).
1357 * @return String the URL
1359 public function getLinkURL( $query = array(), $variant = false ) {
1360 wfProfileIn( __METHOD__
);
1361 if ( $this->isExternal() ) {
1362 $ret = $this->getFullURL( $query );
1363 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1364 $ret = $this->getFragmentForURL();
1366 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
1368 wfProfileOut( __METHOD__
);
1373 * Get an HTML-escaped version of the URL form, suitable for
1374 * using in a link, without a server name or fragment
1376 * @param $query String an optional query string
1377 * @return String the URL
1379 public function escapeLocalURL( $query = '' ) {
1380 return htmlspecialchars( $this->getLocalURL( $query ) );
1384 * Get an HTML-escaped version of the URL form, suitable for
1385 * using in a link, including the server name and fragment
1387 * @param $query String an optional query string
1388 * @return String the URL
1390 public function escapeFullURL( $query = '' ) {
1391 return htmlspecialchars( $this->getFullURL( $query ) );
1395 * Get the URL form for an internal link.
1396 * - Used in various Squid-related code, in case we have a different
1397 * internal hostname for the server from the exposed one.
1399 * This uses $wgInternalServer to qualify the path, or $wgServer
1400 * if $wgInternalServer is not set. If the server variable used is
1401 * protocol-relative, the URL will be expanded to http://
1403 * @param $query String an optional query string
1404 * @param $variant String language variant of url (for sr, zh..)
1405 * @return String the URL
1407 public function getInternalURL( $query = '', $variant = false ) {
1408 global $wgInternalServer, $wgServer;
1409 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1410 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1411 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1416 * Get the URL for a canonical link, for use in things like IRC and
1417 * e-mail notifications. Uses $wgCanonicalServer and the
1418 * GetCanonicalURL hook.
1420 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1422 * @param $query string An optional query string
1423 * @param $variant string Language variant of URL (for sr, zh, ...)
1424 * @return string The URL
1427 public function getCanonicalURL( $query = '', $variant = false ) {
1428 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1429 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1434 * HTML-escaped version of getCanonicalURL()
1437 public function escapeCanonicalURL( $query = '', $variant = false ) {
1438 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1442 * Get the edit URL for this Title
1444 * @return String the URL, or a null string if this is an
1447 public function getEditURL() {
1448 if ( $this->mInterwiki
!= '' ) {
1451 $s = $this->getLocalURL( 'action=edit' );
1457 * Is $wgUser watching this page?
1461 public function userIsWatching() {
1464 if ( is_null( $this->mWatched
) ) {
1465 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1466 $this->mWatched
= false;
1468 $this->mWatched
= $wgUser->isWatched( $this );
1471 return $this->mWatched
;
1475 * Can $wgUser read this page?
1477 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1479 * @todo fold these checks into userCan()
1481 public function userCanRead() {
1482 return $this->userCan( 'read' );
1486 * Can $user perform $action on this page?
1487 * This skips potentially expensive cascading permission checks
1488 * as well as avoids expensive error formatting
1490 * Suitable for use for nonessential UI controls in common cases, but
1491 * _not_ for functional access control.
1493 * May provide false positives, but should never provide a false negative.
1495 * @param $action String action that permission needs to be checked for
1496 * @param $user User to check (since 1.19); $wgUser will be used if not
1500 public function quickUserCan( $action, $user = null ) {
1501 return $this->userCan( $action, $user, false );
1505 * Can $user perform $action on this page?
1507 * @param $action String action that permission needs to be checked for
1508 * @param $user User to check (since 1.19); $wgUser will be used if not
1510 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1511 * unnecessary queries.
1514 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1515 if ( !$user instanceof User
) {
1519 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1523 * Can $user perform $action on this page?
1525 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1527 * @param $action String action that permission needs to be checked for
1528 * @param $user User to check
1529 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1530 * queries by skipping checks for cascading protections and user blocks.
1531 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1532 * whose corresponding errors may be ignored.
1533 * @return Array of arguments to wfMsg to explain permissions problems.
1535 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1536 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1538 // Remove the errors being ignored.
1539 foreach ( $errors as $index => $error ) {
1540 $error_key = is_array( $error ) ?
$error[0] : $error;
1542 if ( in_array( $error_key, $ignoreErrors ) ) {
1543 unset( $errors[$index] );
1551 * Permissions checks that fail most often, and which are easiest to test.
1553 * @param $action String the action to check
1554 * @param $user User user to check
1555 * @param $errors Array list of current errors
1556 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1557 * @param $short Boolean short circuit on first error
1559 * @return Array list of errors
1561 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1562 $ns = $this->getNamespace();
1564 if ( $action == 'create' ) {
1565 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1566 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1567 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1569 } elseif ( $action == 'move' ) {
1570 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1571 && $ns == NS_USER
&& !$this->isSubpage() ) {
1572 // Show user page-specific message only if the user can move other pages
1573 $errors[] = array( 'cant-move-user-page' );
1576 // Check if user is allowed to move files if it's a file
1577 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1578 $errors[] = array( 'movenotallowedfile' );
1581 if ( !$user->isAllowed( 'move', $ns) ) {
1582 // User can't move anything
1584 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1585 array( 'user' ), $ns ), true );
1586 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1587 array( 'autoconfirmed' ), $ns ), true );
1589 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1590 // custom message if logged-in users without any special rights can move
1591 $errors[] = array( 'movenologintext' );
1593 $errors[] = array( 'movenotallowed' );
1596 } elseif ( $action == 'move-target' ) {
1597 if ( !$user->isAllowed( 'move', $ns ) ) {
1598 // User can't move anything
1599 $errors[] = array( 'movenotallowed' );
1600 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1601 && $ns == NS_USER
&& !$this->isSubpage() ) {
1602 // Show user page-specific message only if the user can move other pages
1603 $errors[] = array( 'cant-move-to-user-page' );
1605 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1606 $errors[] = $this->missingPermissionError( $action, $short );
1613 * Add the resulting error code to the errors array
1615 * @param $errors Array list of current errors
1616 * @param $result Mixed result of errors
1618 * @return Array list of errors
1620 private function resultToError( $errors, $result ) {
1621 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1622 // A single array representing an error
1623 $errors[] = $result;
1624 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1625 // A nested array representing multiple errors
1626 $errors = array_merge( $errors, $result );
1627 } elseif ( $result !== '' && is_string( $result ) ) {
1628 // A string representing a message-id
1629 $errors[] = array( $result );
1630 } elseif ( $result === false ) {
1631 // a generic "We don't want them to do that"
1632 $errors[] = array( 'badaccess-group0' );
1638 * Check various permission hooks
1640 * @param $action String the action to check
1641 * @param $user User user to check
1642 * @param $errors Array list of current errors
1643 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1644 * @param $short Boolean short circuit on first error
1646 * @return Array list of errors
1648 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1649 // Use getUserPermissionsErrors instead
1651 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1652 return $result ?
array() : array( array( 'badaccess-group0' ) );
1654 // Check getUserPermissionsErrors hook
1655 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1656 $errors = $this->resultToError( $errors, $result );
1658 // Check getUserPermissionsErrorsExpensive hook
1659 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1660 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1661 $errors = $this->resultToError( $errors, $result );
1668 * Check permissions on special pages & namespaces
1670 * @param $action String the action to check
1671 * @param $user User user to check
1672 * @param $errors Array list of current errors
1673 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1674 * @param $short Boolean short circuit on first error
1676 * @return Array list of errors
1678 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1679 # Only 'createaccount' and 'execute' can be performed on
1680 # special pages, which don't actually exist in the DB.
1681 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1682 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1683 $errors[] = array( 'ns-specialprotected' );
1686 # Check $wgNamespaceProtection for restricted namespaces
1687 if ( $this->isNamespaceProtected( $user ) ) {
1688 $ns = $this->mNamespace
== NS_MAIN ?
1689 wfMsg( 'nstab-main' ) : $this->getNsText();
1690 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1691 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1698 * Check CSS/JS sub-page permissions
1700 * @param $action String the action to check
1701 * @param $user User user to check
1702 * @param $errors Array list of current errors
1703 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1704 * @param $short Boolean short circuit on first error
1706 * @return Array list of errors
1708 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1709 # Protect css/js subpages of user pages
1710 # XXX: this might be better using restrictions
1711 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1712 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1713 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1714 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1715 $errors[] = array( 'customcssprotected' );
1716 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1717 $errors[] = array( 'customjsprotected' );
1725 * Check against page_restrictions table requirements on this
1726 * page. The user must possess all required rights for this
1729 * @param $action String the action to check
1730 * @param $user User user to check
1731 * @param $errors Array list of current errors
1732 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1733 * @param $short Boolean short circuit on first error
1735 * @return Array list of errors
1737 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1738 foreach ( $this->getRestrictions( $action ) as $right ) {
1739 // Backwards compatibility, rewrite sysop -> protect
1740 if ( $right == 'sysop' ) {
1743 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1744 // Users with 'editprotected' permission can edit protected pages
1745 // without cascading option turned on.
1746 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected', $this->mNamespace
)
1747 ||
$this->mCascadeRestriction
)
1749 $errors[] = array( 'protectedpagetext', $right );
1758 * Check restrictions on cascading pages.
1760 * @param $action String the action to check
1761 * @param $user User to check
1762 * @param $errors Array list of current errors
1763 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1764 * @param $short Boolean short circuit on first error
1766 * @return Array list of errors
1768 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1769 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1770 # We /could/ use the protection level on the source page, but it's
1771 # fairly ugly as we have to establish a precedence hierarchy for pages
1772 # included by multiple cascade-protected pages. So just restrict
1773 # it to people with 'protect' permission, as they could remove the
1774 # protection anyway.
1775 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1776 # Cascading protection depends on more than this page...
1777 # Several cascading protected pages may include this page...
1778 # Check each cascading level
1779 # This is only for protection restrictions, not for all actions
1780 if ( isset( $restrictions[$action] ) ) {
1781 foreach ( $restrictions[$action] as $right ) {
1782 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1783 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1785 foreach ( $cascadingSources as $page )
1786 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1787 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1797 * Check action permissions not already checked in checkQuickPermissions
1799 * @param $action String the action to check
1800 * @param $user User to check
1801 * @param $errors Array list of current errors
1802 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1803 * @param $short Boolean short circuit on first error
1805 * @return Array list of errors
1807 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1808 if ( $action == 'protect' ) {
1809 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1810 // If they can't edit, they shouldn't protect.
1811 $errors[] = array( 'protect-cantedit' );
1813 } elseif ( $action == 'create' ) {
1814 $title_protection = $this->getTitleProtection();
1815 if( $title_protection ) {
1816 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1817 $title_protection['pt_create_perm'] = 'protect'; // B/C
1819 if( $title_protection['pt_create_perm'] == '' ||
1820 !$user->isAllowed( $title_protection['pt_create_perm'],
1821 $this->mNamespace
) ) {
1822 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1825 } elseif ( $action == 'move' ) {
1826 // Check for immobile pages
1827 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1828 // Specific message for this case
1829 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1830 } elseif ( !$this->isMovable() ) {
1831 // Less specific message for rarer cases
1832 $errors[] = array( 'immobile-source-page' );
1834 } elseif ( $action == 'move-target' ) {
1835 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1836 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1837 } elseif ( !$this->isMovable() ) {
1838 $errors[] = array( 'immobile-target-page' );
1845 * Check that the user isn't blocked from editting.
1847 * @param $action String the action to check
1848 * @param $user User to check
1849 * @param $errors Array list of current errors
1850 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1851 * @param $short Boolean short circuit on first error
1853 * @return Array list of errors
1855 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1856 // Account creation blocks handled at userlogin.
1857 // Unblocking handled in SpecialUnblock
1858 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1862 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1864 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1865 $errors[] = array( 'confirmedittext' );
1868 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1869 // Don't block the user from editing their own talk page unless they've been
1870 // explicitly blocked from that too.
1871 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1872 $block = $user->mBlock
;
1874 // This is from OutputPage::blockedPage
1875 // Copied at r23888 by werdna
1877 $id = $user->blockedBy();
1878 $reason = $user->blockedFor();
1879 if ( $reason == '' ) {
1880 $reason = wfMsg( 'blockednoreason' );
1882 $ip = $user->getRequest()->getIP();
1884 if ( is_numeric( $id ) ) {
1885 $name = User
::whoIs( $id );
1890 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1891 $blockid = $block->getId();
1892 $blockExpiry = $user->mBlock
->mExpiry
;
1893 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1894 if ( $blockExpiry == 'infinity' ) {
1895 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1897 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1900 $intended = strval( $user->mBlock
->getTarget() );
1902 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1903 $blockid, $blockExpiry, $intended, $blockTimestamp );
1910 * Check that the user is allowed to read this page.
1912 * @param $action String the action to check
1913 * @param $user User to check
1914 * @param $errors Array list of current errors
1915 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1916 * @param $short Boolean short circuit on first error
1918 * @return Array list of errors
1920 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1921 static $useShortcut = null;
1923 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1924 if ( is_null( $useShortcut ) ) {
1925 global $wgGroupPermissions, $wgRevokePermissions;
1926 $useShortcut = true;
1927 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1928 # Not a public wiki, so no shortcut
1929 $useShortcut = false;
1930 } elseif ( !empty( $wgRevokePermissions ) ) {
1932 * Iterate through each group with permissions being revoked (key not included since we don't care
1933 * what the group name is), then check if the read permission is being revoked. If it is, then
1934 * we don't use the shortcut below since the user might not be able to read, even though anon
1935 * reading is allowed.
1937 foreach ( $wgRevokePermissions as $perms ) {
1938 if ( !empty( $perms['read'] ) ) {
1939 # We might be removing the read right from the user, so no shortcut
1940 $useShortcut = false;
1947 # Shortcut for public wikis, allows skipping quite a bit of code
1948 if ( $useShortcut ) {
1952 # If the user is allowed to read pages, he is allowed to read all pages
1953 if ( $user->isAllowed( 'read', $this->mNamespace
) ) {
1957 # Always grant access to the login page.
1958 # Even anons need to be able to log in.
1959 if ( $this->isSpecial( 'Userlogin' )
1960 ||
$this->isSpecial( 'ChangePassword' )
1961 ||
$this->isSpecial( 'PasswordReset' )
1966 # Time to check the whitelist
1967 global $wgWhitelistRead;
1969 # Only to these checks is there's something to check against
1970 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1971 # Check for explicit whitelisting
1972 $name = $this->getPrefixedText();
1973 $dbName = $this->getPrefixedDBKey();
1975 // Check with and without underscores
1976 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
1980 # Old settings might have the title prefixed with
1981 # a colon for main-namespace pages
1982 if ( $this->getNamespace() == NS_MAIN
) {
1983 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1988 # If it's a special page, ditch the subpage bit and check again
1989 if ( $this->isSpecialPage() ) {
1990 $name = $this->getDBkey();
1991 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1992 if ( $name !== false ) {
1993 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1994 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2001 $errors[] = $this->missingPermissionError( $action, $short );
2006 * Get a description array when the user doesn't have the right to perform
2007 * $action (i.e. when User::isAllowed() returns false)
2009 * @param $action String the action to check
2010 * @param $short Boolean short circuit on first error
2011 * @return Array list of errors
2013 private function missingPermissionError( $action, $short ) {
2014 // We avoid expensive display logic for quickUserCan's and such
2016 return array( 'badaccess-group0' );
2019 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2020 User
::getGroupsWithPermission( $action, $this->mNamespace
) );
2022 if ( count( $groups ) ) {
2026 $wgLang->commaList( $groups ),
2030 return array( 'badaccess-group0' );
2035 * Can $user perform $action on this page? This is an internal function,
2036 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2037 * checks on wfReadOnly() and blocks)
2039 * @param $action String action that permission needs to be checked for
2040 * @param $user User to check
2041 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2042 * @param $short Bool Set this to true to stop after the first permission error.
2043 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2045 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2046 wfProfileIn( __METHOD__
);
2048 # Read has special handling
2049 if ( $action == 'read' ) {
2051 'checkPermissionHooks',
2052 'checkReadPermissions',
2056 'checkQuickPermissions',
2057 'checkPermissionHooks',
2058 'checkSpecialsAndNSPermissions',
2059 'checkCSSandJSPermissions',
2060 'checkPageRestrictions',
2061 'checkCascadingSourcesRestrictions',
2062 'checkActionPermissions',
2068 while( count( $checks ) > 0 &&
2069 !( $short && count( $errors ) > 0 ) ) {
2070 $method = array_shift( $checks );
2071 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2074 wfProfileOut( __METHOD__
);
2079 * Protect css subpages of user pages: can $wgUser edit
2082 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2085 public function userCanEditCssSubpage() {
2087 wfDeprecated( __METHOD__
);
2088 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2089 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2093 * Protect js subpages of user pages: can $wgUser edit
2096 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2099 public function userCanEditJsSubpage() {
2101 wfDeprecated( __METHOD__
);
2102 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2103 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2107 * Get a filtered list of all restriction types supported by this wiki.
2108 * @param bool $exists True to get all restriction types that apply to
2109 * titles that do exist, False for all restriction types that apply to
2110 * titles that do not exist
2113 public static function getFilteredRestrictionTypes( $exists = true ) {
2114 global $wgRestrictionTypes;
2115 $types = $wgRestrictionTypes;
2117 # Remove the create restriction for existing titles
2118 $types = array_diff( $types, array( 'create' ) );
2120 # Only the create and upload restrictions apply to non-existing titles
2121 $types = array_intersect( $types, array( 'create', 'upload' ) );
2127 * Returns restriction types for the current Title
2129 * @return array applicable restriction types
2131 public function getRestrictionTypes() {
2132 if ( $this->isSpecialPage() ) {
2136 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2138 if ( $this->getNamespace() != NS_FILE
) {
2139 # Remove the upload restriction for non-file titles
2140 $types = array_diff( $types, array( 'upload' ) );
2143 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2145 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2146 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2152 * Is this title subject to title protection?
2153 * Title protection is the one applied against creation of such title.
2155 * @return Mixed An associative array representing any existent title
2156 * protection, or false if there's none.
2158 private function getTitleProtection() {
2159 // Can't protect pages in special namespaces
2160 if ( $this->getNamespace() < 0 ) {
2164 // Can't protect pages that exist.
2165 if ( $this->exists() ) {
2169 if ( !isset( $this->mTitleProtection
) ) {
2170 $dbr = wfGetDB( DB_SLAVE
);
2171 $res = $dbr->select( 'protected_titles', '*',
2172 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2175 // fetchRow returns false if there are no rows.
2176 $this->mTitleProtection
= $dbr->fetchRow( $res );
2178 return $this->mTitleProtection
;
2182 * Update the title protection status
2184 * @param $create_perm String Permission required for creation
2185 * @param $reason String Reason for protection
2186 * @param $expiry String Expiry timestamp
2187 * @return boolean true
2189 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2190 global $wgUser, $wgContLang;
2192 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
2193 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
2198 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
2200 $dbw = wfGetDB( DB_MASTER
);
2202 $encodedExpiry = $dbw->encodeExpiry( $expiry );
2204 $expiry_description = '';
2205 if ( $encodedExpiry != $dbw->getInfinity() ) {
2206 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
2207 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
2209 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
2212 # Update protection table
2213 if ( $create_perm != '' ) {
2214 $this->mTitleProtection
= array(
2215 'pt_namespace' => $namespace,
2216 'pt_title' => $title,
2217 'pt_create_perm' => $create_perm,
2218 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
2219 'pt_expiry' => $encodedExpiry,
2220 'pt_user' => $wgUser->getId(),
2221 'pt_reason' => $reason,
2223 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
2224 $this->mTitleProtection
, __METHOD__
);
2226 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
2227 'pt_title' => $title ), __METHOD__
);
2228 $this->mTitleProtection
= false;
2231 # Update the protection log
2232 if ( $dbw->affectedRows() ) {
2233 $log = new LogPage( 'protect' );
2235 if ( $create_perm ) {
2236 $params = array( "[create=$create_perm] $expiry_description", '' );
2237 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
2239 $log->addEntry( 'unprotect', $this, $reason );
2247 * Remove any title protection due to page existing
2249 public function deleteTitleProtection() {
2250 $dbw = wfGetDB( DB_MASTER
);
2254 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2257 $this->mTitleProtection
= false;
2261 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2263 * @param $action String Action to check (default: edit)
2266 public function isSemiProtected( $action = 'edit' ) {
2267 if ( $this->exists() ) {
2268 $restrictions = $this->getRestrictions( $action );
2269 if ( count( $restrictions ) > 0 ) {
2270 foreach ( $restrictions as $restriction ) {
2271 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2281 # If it doesn't exist, it can't be protected
2287 * Does the title correspond to a protected article?
2289 * @param $action String the action the page is protected from,
2290 * by default checks all actions.
2293 public function isProtected( $action = '' ) {
2294 global $wgRestrictionLevels;
2296 $restrictionTypes = $this->getRestrictionTypes();
2298 # Special pages have inherent protection
2299 if( $this->isSpecialPage() ) {
2303 # Check regular protection levels
2304 foreach ( $restrictionTypes as $type ) {
2305 if ( $action == $type ||
$action == '' ) {
2306 $r = $this->getRestrictions( $type );
2307 foreach ( $wgRestrictionLevels as $level ) {
2308 if ( in_array( $level, $r ) && $level != '' ) {
2319 * Determines if $user is unable to edit this page because it has been protected
2320 * by $wgNamespaceProtection.
2322 * @param $user User object to check permissions
2325 public function isNamespaceProtected( User
$user ) {
2326 global $wgNamespaceProtection;
2328 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2329 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2330 if ( $right != '' && !$user->isAllowed( $right ) ) {
2339 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2341 * @return Bool If the page is subject to cascading restrictions.
2343 public function isCascadeProtected() {
2344 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2345 return ( $sources > 0 );
2349 * Cascading protection: Get the source of any cascading restrictions on this page.
2351 * @param $getPages Bool Whether or not to retrieve the actual pages
2352 * that the restrictions have come from.
2353 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2354 * have come, false for none, or true if such restrictions exist, but $getPages
2355 * was not set. The restriction array is an array of each type, each of which
2356 * contains a array of unique groups.
2358 public function getCascadeProtectionSources( $getPages = true ) {
2360 $pagerestrictions = array();
2362 if ( isset( $this->mCascadeSources
) && $getPages ) {
2363 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2364 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2365 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2368 wfProfileIn( __METHOD__
);
2370 $dbr = wfGetDB( DB_SLAVE
);
2372 if ( $this->getNamespace() == NS_FILE
) {
2373 $tables = array( 'imagelinks', 'page_restrictions' );
2374 $where_clauses = array(
2375 'il_to' => $this->getDBkey(),
2380 $tables = array( 'templatelinks', 'page_restrictions' );
2381 $where_clauses = array(
2382 'tl_namespace' => $this->getNamespace(),
2383 'tl_title' => $this->getDBkey(),
2390 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2391 'pr_expiry', 'pr_type', 'pr_level' );
2392 $where_clauses[] = 'page_id=pr_page';
2395 $cols = array( 'pr_expiry' );
2398 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2400 $sources = $getPages ?
array() : false;
2401 $now = wfTimestampNow();
2402 $purgeExpired = false;
2404 foreach ( $res as $row ) {
2405 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2406 if ( $expiry > $now ) {
2408 $page_id = $row->pr_page
;
2409 $page_ns = $row->page_namespace
;
2410 $page_title = $row->page_title
;
2411 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2412 # Add groups needed for each restriction type if its not already there
2413 # Make sure this restriction type still exists
2415 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2416 $pagerestrictions[$row->pr_type
] = array();
2419 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2420 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2421 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2427 // Trigger lazy purge of expired restrictions from the db
2428 $purgeExpired = true;
2431 if ( $purgeExpired ) {
2432 Title
::purgeExpiredRestrictions();
2436 $this->mCascadeSources
= $sources;
2437 $this->mCascadingRestrictions
= $pagerestrictions;
2439 $this->mHasCascadingRestrictions
= $sources;
2442 wfProfileOut( __METHOD__
);
2443 return array( $sources, $pagerestrictions );
2447 * Accessor/initialisation for mRestrictions
2449 * @param $action String action that permission needs to be checked for
2450 * @return Array of Strings the array of groups allowed to edit this article
2452 public function getRestrictions( $action ) {
2453 if ( !$this->mRestrictionsLoaded
) {
2454 $this->loadRestrictions();
2456 return isset( $this->mRestrictions
[$action] )
2457 ?
$this->mRestrictions
[$action]
2462 * Get the expiry time for the restriction against a given action
2464 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2465 * or not protected at all, or false if the action is not recognised.
2467 public function getRestrictionExpiry( $action ) {
2468 if ( !$this->mRestrictionsLoaded
) {
2469 $this->loadRestrictions();
2471 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2475 * Returns cascading restrictions for the current article
2479 function areRestrictionsCascading() {
2480 if ( !$this->mRestrictionsLoaded
) {
2481 $this->loadRestrictions();
2484 return $this->mCascadeRestriction
;
2488 * Loads a string into mRestrictions array
2490 * @param $res Resource restrictions as an SQL result.
2491 * @param $oldFashionedRestrictions String comma-separated list of page
2492 * restrictions from page table (pre 1.10)
2494 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2497 foreach ( $res as $row ) {
2501 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2505 * Compiles list of active page restrictions from both page table (pre 1.10)
2506 * and page_restrictions table for this existing page.
2507 * Public for usage by LiquidThreads.
2509 * @param $rows array of db result objects
2510 * @param $oldFashionedRestrictions string comma-separated list of page
2511 * restrictions from page table (pre 1.10)
2513 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2515 $dbr = wfGetDB( DB_SLAVE
);
2517 $restrictionTypes = $this->getRestrictionTypes();
2519 foreach ( $restrictionTypes as $type ) {
2520 $this->mRestrictions
[$type] = array();
2521 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2524 $this->mCascadeRestriction
= false;
2526 # Backwards-compatibility: also load the restrictions from the page record (old format).
2528 if ( $oldFashionedRestrictions === null ) {
2529 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2530 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2533 if ( $oldFashionedRestrictions != '' ) {
2535 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2536 $temp = explode( '=', trim( $restrict ) );
2537 if ( count( $temp ) == 1 ) {
2538 // old old format should be treated as edit/move restriction
2539 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2540 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2542 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2546 $this->mOldRestrictions
= true;
2550 if ( count( $rows ) ) {
2551 # Current system - load second to make them override.
2552 $now = wfTimestampNow();
2553 $purgeExpired = false;
2555 # Cycle through all the restrictions.
2556 foreach ( $rows as $row ) {
2558 // Don't take care of restrictions types that aren't allowed
2559 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2562 // This code should be refactored, now that it's being used more generally,
2563 // But I don't really see any harm in leaving it in Block for now -werdna
2564 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2566 // Only apply the restrictions if they haven't expired!
2567 if ( !$expiry ||
$expiry > $now ) {
2568 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2569 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2571 $this->mCascadeRestriction |
= $row->pr_cascade
;
2573 // Trigger a lazy purge of expired restrictions
2574 $purgeExpired = true;
2578 if ( $purgeExpired ) {
2579 Title
::purgeExpiredRestrictions();
2583 $this->mRestrictionsLoaded
= true;
2587 * Load restrictions from the page_restrictions table
2589 * @param $oldFashionedRestrictions String comma-separated list of page
2590 * restrictions from page table (pre 1.10)
2592 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2594 if ( !$this->mRestrictionsLoaded
) {
2595 if ( $this->exists() ) {
2596 $dbr = wfGetDB( DB_SLAVE
);
2598 $res = $dbr->select(
2599 'page_restrictions',
2601 array( 'pr_page' => $this->getArticleId() ),
2605 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2607 $title_protection = $this->getTitleProtection();
2609 if ( $title_protection ) {
2610 $now = wfTimestampNow();
2611 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2613 if ( !$expiry ||
$expiry > $now ) {
2614 // Apply the restrictions
2615 $this->mRestrictionsExpiry
['create'] = $expiry;
2616 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2617 } else { // Get rid of the old restrictions
2618 Title
::purgeExpiredRestrictions();
2619 $this->mTitleProtection
= false;
2622 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2624 $this->mRestrictionsLoaded
= true;
2630 * Purge expired restrictions from the page_restrictions table
2632 static function purgeExpiredRestrictions() {
2633 $dbw = wfGetDB( DB_MASTER
);
2635 'page_restrictions',
2636 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2642 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2648 * Does this have subpages? (Warning, usually requires an extra DB query.)
2652 public function hasSubpages() {
2653 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2658 # We dynamically add a member variable for the purpose of this method
2659 # alone to cache the result. There's no point in having it hanging
2660 # around uninitialized in every Title object; therefore we only add it
2661 # if needed and don't declare it statically.
2662 if ( isset( $this->mHasSubpages
) ) {
2663 return $this->mHasSubpages
;
2666 $subpages = $this->getSubpages( 1 );
2667 if ( $subpages instanceof TitleArray
) {
2668 return $this->mHasSubpages
= (bool)$subpages->count();
2670 return $this->mHasSubpages
= false;
2674 * Get all subpages of this page.
2676 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2677 * @return mixed TitleArray, or empty array if this page's namespace
2678 * doesn't allow subpages
2680 public function getSubpages( $limit = -1 ) {
2681 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2685 $dbr = wfGetDB( DB_SLAVE
);
2686 $conds['page_namespace'] = $this->getNamespace();
2687 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2689 if ( $limit > -1 ) {
2690 $options['LIMIT'] = $limit;
2692 return $this->mSubpages
= TitleArray
::newFromResult(
2693 $dbr->select( 'page',
2694 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2703 * Is there a version of this page in the deletion archive?
2705 * @return Int the number of archived revisions
2707 public function isDeleted() {
2708 if ( $this->getNamespace() < 0 ) {
2711 $dbr = wfGetDB( DB_SLAVE
);
2713 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2714 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2717 if ( $this->getNamespace() == NS_FILE
) {
2718 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2719 array( 'fa_name' => $this->getDBkey() ),
2728 * Is there a version of this page in the deletion archive?
2732 public function isDeletedQuick() {
2733 if ( $this->getNamespace() < 0 ) {
2736 $dbr = wfGetDB( DB_SLAVE
);
2737 $deleted = (bool)$dbr->selectField( 'archive', '1',
2738 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2741 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2742 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2743 array( 'fa_name' => $this->getDBkey() ),
2751 * Get the number of views of this page
2753 * @return int The view count for the page
2755 public function getCount() {
2756 if ( $this->mCounter
== -1 ) {
2757 if ( $this->exists() ) {
2758 $dbr = wfGetDB( DB_SLAVE
);
2759 $this->mCounter
= $dbr->selectField( 'page',
2761 array( 'page_id' => $this->getArticleID() ),
2765 $this->mCounter
= 0;
2769 return $this->mCounter
;
2773 * Get the article ID for this Title from the link cache,
2774 * adding it if necessary
2776 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2778 * @return Int the ID
2780 public function getArticleID( $flags = 0 ) {
2781 if ( $this->getNamespace() < 0 ) {
2782 return $this->mArticleID
= 0;
2784 $linkCache = LinkCache
::singleton();
2785 if ( $flags & self
::GAID_FOR_UPDATE
) {
2786 $oldUpdate = $linkCache->forUpdate( true );
2787 $linkCache->clearLink( $this );
2788 $this->mArticleID
= $linkCache->addLinkObj( $this );
2789 $linkCache->forUpdate( $oldUpdate );
2791 if ( -1 == $this->mArticleID
) {
2792 $this->mArticleID
= $linkCache->addLinkObj( $this );
2795 return $this->mArticleID
;
2799 * Is this an article that is a redirect page?
2800 * Uses link cache, adding it if necessary
2802 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2805 public function isRedirect( $flags = 0 ) {
2806 if ( !is_null( $this->mRedirect
) ) {
2807 return $this->mRedirect
;
2809 # Calling getArticleID() loads the field from cache as needed
2810 if ( !$this->getArticleID( $flags ) ) {
2811 return $this->mRedirect
= false;
2813 $linkCache = LinkCache
::singleton();
2814 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2816 return $this->mRedirect
;
2820 * What is the length of this page?
2821 * Uses link cache, adding it if necessary
2823 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2826 public function getLength( $flags = 0 ) {
2827 if ( $this->mLength
!= -1 ) {
2828 return $this->mLength
;
2830 # Calling getArticleID() loads the field from cache as needed
2831 if ( !$this->getArticleID( $flags ) ) {
2832 return $this->mLength
= 0;
2834 $linkCache = LinkCache
::singleton();
2835 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2837 return $this->mLength
;
2841 * What is the page_latest field for this page?
2843 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2844 * @return Int or 0 if the page doesn't exist
2846 public function getLatestRevID( $flags = 0 ) {
2847 if ( $this->mLatestID
!== false ) {
2848 return intval( $this->mLatestID
);
2850 # Calling getArticleID() loads the field from cache as needed
2851 if ( !$this->getArticleID( $flags ) ) {
2852 return $this->mLatestID
= 0;
2854 $linkCache = LinkCache
::singleton();
2855 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2857 return $this->mLatestID
;
2861 * This clears some fields in this object, and clears any associated
2862 * keys in the "bad links" section of the link cache.
2864 * - This is called from Article::doEdit() and Article::insertOn() to allow
2865 * loading of the new page_id. It's also called from
2866 * Article::doDeleteArticle()
2868 * @param $newid Int the new Article ID
2870 public function resetArticleID( $newid ) {
2871 $linkCache = LinkCache
::singleton();
2872 $linkCache->clearLink( $this );
2874 if ( $newid === false ) {
2875 $this->mArticleID
= -1;
2877 $this->mArticleID
= intval( $newid );
2879 $this->mRestrictionsLoaded
= false;
2880 $this->mRestrictions
= array();
2881 $this->mRedirect
= null;
2882 $this->mLength
= -1;
2883 $this->mLatestID
= false;
2884 $this->mCounter
= -1;
2888 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2890 * @param $text String containing title to capitalize
2891 * @param $ns int namespace index, defaults to NS_MAIN
2892 * @return String containing capitalized title
2894 public static function capitalize( $text, $ns = NS_MAIN
) {
2897 if ( MWNamespace
::isCapitalized( $ns ) ) {
2898 return $wgContLang->ucfirst( $text );
2905 * Secure and split - main initialisation function for this object
2907 * Assumes that mDbkeyform has been set, and is urldecoded
2908 * and uses underscores, but not otherwise munged. This function
2909 * removes illegal characters, splits off the interwiki and
2910 * namespace prefixes, sets the other forms, and canonicalizes
2913 * @return Bool true on success
2915 private function secureAndSplit() {
2916 global $wgContLang, $wgLocalInterwiki;
2919 $this->mInterwiki
= $this->mFragment
= '';
2920 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2922 $dbkey = $this->mDbkeyform
;
2924 # Strip Unicode bidi override characters.
2925 # Sometimes they slip into cut-n-pasted page titles, where the
2926 # override chars get included in list displays.
2927 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2929 # Clean up whitespace
2930 # Note: use of the /u option on preg_replace here will cause
2931 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2932 # conveniently disabling them.
2933 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2934 $dbkey = trim( $dbkey, '_' );
2936 if ( $dbkey == '' ) {
2940 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2941 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2945 $this->mDbkeyform
= $dbkey;
2947 # Initial colon indicates main namespace rather than specified default
2948 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2949 if ( ':' == $dbkey[0] ) {
2950 $this->mNamespace
= NS_MAIN
;
2951 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2952 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2955 # Namespace or interwiki prefix
2957 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2960 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2962 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2963 # Ordinary namespace
2965 $this->mNamespace
= $ns;
2966 # For Talk:X pages, check if X has a "namespace" prefix
2967 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2968 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2969 # Disallow Talk:File:x type titles...
2971 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2972 # Disallow Talk:Interwiki:x type titles...
2976 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2977 if ( !$firstPass ) {
2978 # Can't make a local interwiki link to an interwiki link.
2979 # That's just crazy!
2985 $this->mInterwiki
= $wgContLang->lc( $p );
2987 # Redundant interwiki prefix to the local wiki
2988 if ( $wgLocalInterwiki !== false
2989 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2991 if ( $dbkey == '' ) {
2992 # Can't have an empty self-link
2995 $this->mInterwiki
= '';
2997 # Do another namespace split...
3001 # If there's an initial colon after the interwiki, that also
3002 # resets the default namespace
3003 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3004 $this->mNamespace
= NS_MAIN
;
3005 $dbkey = substr( $dbkey, 1 );
3008 # If there's no recognized interwiki or namespace,
3009 # then let the colon expression be part of the title.
3014 # We already know that some pages won't be in the database!
3015 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3016 $this->mArticleID
= 0;
3018 $fragment = strstr( $dbkey, '#' );
3019 if ( false !== $fragment ) {
3020 $this->setFragment( $fragment );
3021 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3022 # remove whitespace again: prevents "Foo_bar_#"
3023 # becoming "Foo_bar_"
3024 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3027 # Reject illegal characters.
3028 $rxTc = self
::getTitleInvalidRegex();
3029 if ( preg_match( $rxTc, $dbkey ) ) {
3033 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3034 # reachable due to the way web browsers deal with 'relative' URLs.
3035 # Also, they conflict with subpage syntax. Forbid them explicitly.
3036 if ( strpos( $dbkey, '.' ) !== false &&
3037 ( $dbkey === '.' ||
$dbkey === '..' ||
3038 strpos( $dbkey, './' ) === 0 ||
3039 strpos( $dbkey, '../' ) === 0 ||
3040 strpos( $dbkey, '/./' ) !== false ||
3041 strpos( $dbkey, '/../' ) !== false ||
3042 substr( $dbkey, -2 ) == '/.' ||
3043 substr( $dbkey, -3 ) == '/..' ) )
3048 # Magic tilde sequences? Nu-uh!
3049 if ( strpos( $dbkey, '~~~' ) !== false ) {
3053 # Limit the size of titles to 255 bytes. This is typically the size of the
3054 # underlying database field. We make an exception for special pages, which
3055 # don't need to be stored in the database, and may edge over 255 bytes due
3056 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3057 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3058 strlen( $dbkey ) > 512 )
3063 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3064 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3065 # other site might be case-sensitive.
3066 $this->mUserCaseDBKey
= $dbkey;
3067 if ( $this->mInterwiki
== '' ) {
3068 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3071 # Can't make a link to a namespace alone... "empty" local links can only be
3072 # self-links with a fragment identifier.
3073 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3077 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3078 // IP names are not allowed for accounts, and can only be referring to
3079 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3080 // there are numerous ways to present the same IP. Having sp:contribs scan
3081 // them all is silly and having some show the edits and others not is
3082 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3083 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3084 ? IP
::sanitizeIP( $dbkey )
3087 // Any remaining initial :s are illegal.
3088 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3093 $this->mDbkeyform
= $dbkey;
3094 $this->mUrlform
= wfUrlencode( $dbkey );
3096 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3102 * Get an array of Title objects linking to this Title
3103 * Also stores the IDs in the link cache.
3105 * WARNING: do not use this function on arbitrary user-supplied titles!
3106 * On heavily-used templates it will max out the memory.
3108 * @param $options Array: may be FOR UPDATE
3109 * @param $table String: table name
3110 * @param $prefix String: fields prefix
3111 * @return Array of Title objects linking here
3113 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3114 $linkCache = LinkCache
::singleton();
3116 if ( count( $options ) > 0 ) {
3117 $db = wfGetDB( DB_MASTER
);
3119 $db = wfGetDB( DB_SLAVE
);
3123 array( 'page', $table ),
3124 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3126 "{$prefix}_from=page_id",
3127 "{$prefix}_namespace" => $this->getNamespace(),
3128 "{$prefix}_title" => $this->getDBkey() ),
3134 if ( $db->numRows( $res ) ) {
3135 foreach ( $res as $row ) {
3136 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3138 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3139 $retVal[] = $titleObj;
3147 * Get an array of Title objects using this Title as a template
3148 * Also stores the IDs in the link cache.
3150 * WARNING: do not use this function on arbitrary user-supplied titles!
3151 * On heavily-used templates it will max out the memory.
3153 * @param $options Array: may be FOR UPDATE
3154 * @return Array of Title the Title objects linking here
3156 public function getTemplateLinksTo( $options = array() ) {
3157 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3161 * Get an array of Title objects referring to non-existent articles linked from this page
3163 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3164 * @return Array of Title the Title objects
3166 public function getBrokenLinksFrom() {
3167 if ( $this->getArticleId() == 0 ) {
3168 # All links from article ID 0 are false positives
3172 $dbr = wfGetDB( DB_SLAVE
);
3173 $res = $dbr->select(
3174 array( 'page', 'pagelinks' ),
3175 array( 'pl_namespace', 'pl_title' ),
3177 'pl_from' => $this->getArticleId(),
3178 'page_namespace IS NULL'
3180 __METHOD__
, array(),
3184 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3190 foreach ( $res as $row ) {
3191 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3198 * Get a list of URLs to purge from the Squid cache when this
3201 * @return Array of String the URLs
3203 public function getSquidURLs() {
3207 $this->getInternalURL(),
3208 $this->getInternalURL( 'action=history' )
3211 // purge variant urls as well
3212 if ( $wgContLang->hasVariants() ) {
3213 $variants = $wgContLang->getVariants();
3214 foreach ( $variants as $vCode ) {
3215 $urls[] = $this->getInternalURL( '', $vCode );
3223 * Purge all applicable Squid URLs
3225 public function purgeSquid() {
3227 if ( $wgUseSquid ) {
3228 $urls = $this->getSquidURLs();
3229 $u = new SquidUpdate( $urls );
3235 * Move this page without authentication
3237 * @param $nt Title the new page Title
3238 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3240 public function moveNoAuth( &$nt ) {
3241 return $this->moveTo( $nt, false );
3245 * Check whether a given move operation would be valid.
3246 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3248 * @param $nt Title the new title
3249 * @param $auth Bool indicates whether $wgUser's permissions
3251 * @param $reason String is the log summary of the move, used for spam checking
3252 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3254 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3259 // Normally we'd add this to $errors, but we'll get
3260 // lots of syntax errors if $nt is not an object
3261 return array( array( 'badtitletext' ) );
3263 if ( $this->equals( $nt ) ) {
3264 $errors[] = array( 'selfmove' );
3266 if ( !$this->isMovable() ) {
3267 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3269 if ( $nt->getInterwiki() != '' ) {
3270 $errors[] = array( 'immobile-target-namespace-iw' );
3272 if ( !$nt->isMovable() ) {
3273 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3276 $oldid = $this->getArticleID();
3277 $newid = $nt->getArticleID();
3279 if ( strlen( $nt->getDBkey() ) < 1 ) {
3280 $errors[] = array( 'articleexists' );
3282 if ( ( $this->getDBkey() == '' ) ||
3284 ( $nt->getDBkey() == '' ) ) {
3285 $errors[] = array( 'badarticleerror' );
3288 // Image-specific checks
3289 if ( $this->getNamespace() == NS_FILE
) {
3290 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3293 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3294 $errors[] = array( 'nonfile-cannot-move-to-file' );
3298 $errors = wfMergeErrorArrays( $errors,
3299 $this->getUserPermissionsErrors( 'move', $wgUser ),
3300 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3301 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3302 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3305 $match = EditPage
::matchSummarySpamRegex( $reason );
3306 if ( $match !== false ) {
3307 // This is kind of lame, won't display nice
3308 $errors[] = array( 'spamprotectiontext' );
3312 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3313 $errors[] = array( 'hookaborted', $err );
3316 # The move is allowed only if (1) the target doesn't exist, or
3317 # (2) the target is a redirect to the source, and has no history
3318 # (so we can undo bad moves right after they're done).
3320 if ( 0 != $newid ) { # Target exists; check for validity
3321 if ( !$this->isValidMoveTarget( $nt ) ) {
3322 $errors[] = array( 'articleexists' );
3325 $tp = $nt->getTitleProtection();
3326 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3327 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3328 $errors[] = array( 'cantmove-titleprotected' );
3331 if ( empty( $errors ) ) {
3338 * Check if the requested move target is a valid file move target
3339 * @param Title $nt Target title
3340 * @return array List of errors
3342 protected function validateFileMoveOperation( $nt ) {
3347 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3349 $file = wfLocalFile( $this );
3350 if ( $file->exists() ) {
3351 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3352 $errors[] = array( 'imageinvalidfilename' );
3354 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3355 $errors[] = array( 'imagetypemismatch' );
3359 if ( $nt->getNamespace() != NS_FILE
) {
3360 $errors[] = array( 'imagenocrossnamespace' );
3361 // From here we want to do checks on a file object, so if we can't
3362 // create one, we must return.
3366 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3368 $destFile = wfLocalFile( $nt );
3369 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3370 $errors[] = array( 'file-exists-sharedrepo' );
3377 * Move a title to a new location
3379 * @param $nt Title the new title
3380 * @param $auth Bool indicates whether $wgUser's permissions
3382 * @param $reason String the reason for the move
3383 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3384 * Ignored if the user doesn't have the suppressredirect right.
3385 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3387 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3389 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3390 if ( is_array( $err ) ) {
3391 // Auto-block user's IP if the account was "hard" blocked
3392 $wgUser->spreadAnyEditBlock();
3396 // If it is a file, move it first.
3397 // It is done before all other moving stuff is done because it's hard to revert.
3398 $dbw = wfGetDB( DB_MASTER
);
3399 if ( $this->getNamespace() == NS_FILE
) {
3400 $file = wfLocalFile( $this );
3401 if ( $file->exists() ) {
3402 $status = $file->move( $nt );
3403 if ( !$status->isOk() ) {
3404 return $status->getErrorsArray();
3408 // Clear RepoGroup process cache
3409 RepoGroup
::singleton()->clearCache( $this );
3410 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3412 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3413 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3414 $protected = $this->isProtected();
3415 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3417 // Do the actual move
3418 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3419 if ( is_array( $err ) ) {
3420 # @todo FIXME: What about the File we have already moved?
3425 $redirid = $this->getArticleID();
3427 // Refresh the sortkey for this row. Be careful to avoid resetting
3428 // cl_timestamp, which may disturb time-based lists on some sites.
3429 $prefixes = $dbw->select(
3431 array( 'cl_sortkey_prefix', 'cl_to' ),
3432 array( 'cl_from' => $pageid ),
3435 foreach ( $prefixes as $prefixRow ) {
3436 $prefix = $prefixRow->cl_sortkey_prefix
;
3437 $catTo = $prefixRow->cl_to
;
3438 $dbw->update( 'categorylinks',
3440 'cl_sortkey' => Collation
::singleton()->getSortKey(
3441 $nt->getCategorySortkey( $prefix ) ),
3442 'cl_timestamp=cl_timestamp' ),
3444 'cl_from' => $pageid,
3445 'cl_to' => $catTo ),
3451 # Protect the redirect title as the title used to be...
3452 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3454 'pr_page' => $redirid,
3455 'pr_type' => 'pr_type',
3456 'pr_level' => 'pr_level',
3457 'pr_cascade' => 'pr_cascade',
3458 'pr_user' => 'pr_user',
3459 'pr_expiry' => 'pr_expiry'
3461 array( 'pr_page' => $pageid ),
3465 # Update the protection log
3466 $log = new LogPage( 'protect' );
3467 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3469 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3471 // @todo FIXME: $params?
3472 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3476 $oldnamespace = $this->getNamespace() & ~
1;
3477 $newnamespace = $nt->getNamespace() & ~
1;
3478 $oldtitle = $this->getDBkey();
3479 $newtitle = $nt->getDBkey();
3481 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3482 WatchedItem
::duplicateEntries( $this, $nt );
3485 # Update search engine
3486 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3488 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3494 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3495 # No longer a content page
3496 # Not viewed, edited, removing
3497 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3498 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3499 # Now a content page
3500 # Not viewed, edited, adding
3501 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3502 } elseif ( $pageCountChange ) {
3504 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3513 # Update message cache for interface messages
3514 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3515 # @bug 17860: old article can be deleted, if this the case,
3516 # delete it from message cache
3517 if ( $this->getArticleID() === 0 ) {
3518 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3520 $rev = Revision
::newFromTitle( $this );
3521 MessageCache
::singleton()->replace( $this->getDBkey(), $rev->getText() );
3524 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3525 $rev = Revision
::newFromTitle( $nt );
3526 MessageCache
::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3529 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3534 * Move page to a title which is either a redirect to the
3535 * source page or nonexistent
3537 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3538 * @param $reason String The reason for the move
3539 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3540 * if the user doesn't have the suppressredirect right
3542 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3543 global $wgUser, $wgContLang;
3545 if ( $nt->exists() ) {
3546 $moveOverRedirect = true;
3547 $logType = 'move_redir';
3549 $moveOverRedirect = false;
3553 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3555 $logEntry = new ManualLogEntry( 'move', $logType );
3556 $logEntry->setPerformer( $wgUser );
3557 $logEntry->setTarget( $this );
3558 $logEntry->setComment( $reason );
3559 $logEntry->setParameters( array(
3560 '4::target' => $nt->getPrefixedText(),
3561 '5::noredir' => $redirectSuppressed ?
'1': '0',
3564 $formatter = LogFormatter
::newFromEntry( $logEntry );
3565 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3566 $comment = $formatter->getPlainActionText();
3568 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3570 # Truncate for whole multibyte characters.
3571 $comment = $wgContLang->truncate( $comment, 255 );
3573 $oldid = $this->getArticleID();
3574 $latest = $this->getLatestRevID();
3576 $dbw = wfGetDB( DB_MASTER
);
3578 if ( $moveOverRedirect ) {
3579 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3581 $newid = $nt->getArticleID();
3582 $newns = $nt->getNamespace();
3583 $newdbk = $nt->getDBkey();
3585 # Delete the old redirect. We don't save it to history since
3586 # by definition if we've got here it's rather uninteresting.
3587 # We have to remove it so that the next step doesn't trigger
3588 # a conflict on the unique namespace+title index...
3589 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3590 if ( !$dbw->cascadingDeletes() ) {
3591 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3593 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3594 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3595 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3596 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3597 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3598 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3599 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__
);
3600 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3601 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3603 // If the target page was recently created, it may have an entry in recentchanges still
3604 $dbw->delete( 'recentchanges',
3605 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3610 # Save a null revision in the page's history notifying of the move
3611 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3612 if ( !is_object( $nullRevision ) ) {
3613 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3615 $nullRevId = $nullRevision->insertOn( $dbw );
3617 $now = wfTimestampNow();
3618 # Change the name of the target page:
3619 $dbw->update( 'page',
3621 'page_touched' => $dbw->timestamp( $now ),
3622 'page_namespace' => $nt->getNamespace(),
3623 'page_title' => $nt->getDBkey(),
3624 'page_latest' => $nullRevId,
3626 /* WHERE */ array( 'page_id' => $oldid ),
3629 $nt->resetArticleID( $oldid );
3631 $article = WikiPage
::factory( $nt );
3632 wfRunHooks( 'NewRevisionFromEditComplete',
3633 array( $article, $nullRevision, $latest, $wgUser ) );
3634 $article->setCachedLastEditTime( $now );
3636 # Recreate the redirect, this time in the other direction.
3637 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3638 $mwRedir = MagicWord
::get( 'redirect' );
3639 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3640 $redirectArticle = WikiPage
::factory( $this );
3641 $newid = $redirectArticle->insertOn( $dbw );
3642 if ( $newid ) { // sanity
3643 $redirectRevision = new Revision( array(
3645 'comment' => $comment,
3646 'text' => $redirectText ) );
3647 $redirectRevision->insertOn( $dbw );
3648 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3650 wfRunHooks( 'NewRevisionFromEditComplete',
3651 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3653 # Now, we record the link from the redirect to the new title.
3654 # It should have no other outgoing links...
3655 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3656 $dbw->insert( 'pagelinks',
3658 'pl_from' => $newid,
3659 'pl_namespace' => $nt->getNamespace(),
3660 'pl_title' => $nt->getDBkey() ),
3664 $this->resetArticleID( 0 );
3668 $logid = $logEntry->insert();
3669 $logEntry->publish( $logid );
3671 # Purge caches for old and new titles
3672 if ( $moveOverRedirect ) {
3673 # A simple purge is enough when moving over a redirect
3676 # Purge caches as per article creation, including any pages that link to this title
3677 Article
::onArticleCreate( $nt );
3679 $this->purgeSquid();
3683 * Move this page's subpages to be subpages of $nt
3685 * @param $nt Title Move target
3686 * @param $auth bool Whether $wgUser's permissions should be checked
3687 * @param $reason string The reason for the move
3688 * @param $createRedirect bool Whether to create redirects from the old subpages to
3689 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3690 * @return mixed array with old page titles as keys, and strings (new page titles) or
3691 * arrays (errors) as values, or an error array with numeric indices if no pages
3694 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3695 global $wgMaximumMovedPages;
3696 // Check permissions
3697 if ( !$this->userCan( 'move-subpages' ) ) {
3698 return array( 'cant-move-subpages' );
3700 // Do the source and target namespaces support subpages?
3701 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3702 return array( 'namespace-nosubpages',
3703 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3705 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3706 return array( 'namespace-nosubpages',
3707 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3710 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3713 foreach ( $subpages as $oldSubpage ) {
3715 if ( $count > $wgMaximumMovedPages ) {
3716 $retval[$oldSubpage->getPrefixedTitle()] =
3717 array( 'movepage-max-pages',
3718 $wgMaximumMovedPages );
3722 // We don't know whether this function was called before
3723 // or after moving the root page, so check both
3725 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3726 $oldSubpage->getArticleID() == $nt->getArticleId() )
3728 // When moving a page to a subpage of itself,
3729 // don't move it twice
3732 $newPageName = preg_replace(
3733 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3734 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3735 $oldSubpage->getDBkey() );
3736 if ( $oldSubpage->isTalkPage() ) {
3737 $newNs = $nt->getTalkPage()->getNamespace();
3739 $newNs = $nt->getSubjectPage()->getNamespace();
3741 # Bug 14385: we need makeTitleSafe because the new page names may
3742 # be longer than 255 characters.
3743 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3745 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3746 if ( $success === true ) {
3747 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3749 $retval[$oldSubpage->getPrefixedText()] = $success;
3756 * Checks if this page is just a one-rev redirect.
3757 * Adds lock, so don't use just for light purposes.
3761 public function isSingleRevRedirect() {
3762 $dbw = wfGetDB( DB_MASTER
);
3764 $row = $dbw->selectRow( 'page',
3765 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3768 array( 'FOR UPDATE' )
3770 # Cache some fields we may want
3771 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3772 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3773 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3774 if ( !$this->mRedirect
) {
3777 # Does the article have a history?
3778 $row = $dbw->selectField( array( 'page', 'revision' ),
3780 array( 'page_namespace' => $this->getNamespace(),
3781 'page_title' => $this->getDBkey(),
3783 'page_latest != rev_id'
3786 array( 'FOR UPDATE' )
3788 # Return true if there was no history
3789 return ( $row === false );
3793 * Checks if $this can be moved to a given Title
3794 * - Selects for update, so don't call it unless you mean business
3796 * @param $nt Title the new title to check
3799 public function isValidMoveTarget( $nt ) {
3800 # Is it an existing file?
3801 if ( $nt->getNamespace() == NS_FILE
) {
3802 $file = wfLocalFile( $nt );
3803 if ( $file->exists() ) {
3804 wfDebug( __METHOD__
. ": file exists\n" );
3808 # Is it a redirect with no history?
3809 if ( !$nt->isSingleRevRedirect() ) {
3810 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3813 # Get the article text
3814 $rev = Revision
::newFromTitle( $nt );
3815 if( !is_object( $rev ) ){
3818 $text = $rev->getText();
3819 # Does the redirect point to the source?
3820 # Or is it a broken self-redirect, usually caused by namespace collisions?
3822 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3823 $redirTitle = Title
::newFromText( $m[1] );
3824 if ( !is_object( $redirTitle ) ||
3825 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3826 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3827 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3832 wfDebug( __METHOD__
. ": failsafe\n" );
3839 * Get categories to which this Title belongs and return an array of
3840 * categories' names.
3842 * @return Array of parents in the form:
3843 * $parent => $currentarticle
3845 public function getParentCategories() {
3850 $titleKey = $this->getArticleId();
3852 if ( $titleKey === 0 ) {
3856 $dbr = wfGetDB( DB_SLAVE
);
3858 $res = $dbr->select( 'categorylinks', '*',
3860 'cl_from' => $titleKey,
3866 if ( $dbr->numRows( $res ) > 0 ) {
3867 foreach ( $res as $row ) {
3868 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3869 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3876 * Get a tree of parent categories
3878 * @param $children Array with the children in the keys, to check for circular refs
3879 * @return Array Tree of parent categories
3881 public function getParentCategoryTree( $children = array() ) {
3883 $parents = $this->getParentCategories();
3886 foreach ( $parents as $parent => $current ) {
3887 if ( array_key_exists( $parent, $children ) ) {
3888 # Circular reference
3889 $stack[$parent] = array();
3891 $nt = Title
::newFromText( $parent );
3893 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3903 * Get an associative array for selecting this title from
3906 * @return Array suitable for the $where parameter of DB::select()
3908 public function pageCond() {
3909 if ( $this->mArticleID
> 0 ) {
3910 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3911 return array( 'page_id' => $this->mArticleID
);
3913 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3918 * Get the revision ID of the previous revision
3920 * @param $revId Int Revision ID. Get the revision that was before this one.
3921 * @param $flags Int Title::GAID_FOR_UPDATE
3922 * @return Int|Bool Old revision ID, or FALSE if none exists
3924 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3925 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3926 return $db->selectField( 'revision', 'rev_id',
3928 'rev_page' => $this->getArticleId( $flags ),
3929 'rev_id < ' . intval( $revId )
3932 array( 'ORDER BY' => 'rev_id DESC' )
3937 * Get the revision ID of the next revision
3939 * @param $revId Int Revision ID. Get the revision that was after this one.
3940 * @param $flags Int Title::GAID_FOR_UPDATE
3941 * @return Int|Bool Next revision ID, or FALSE if none exists
3943 public function getNextRevisionID( $revId, $flags = 0 ) {
3944 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3945 return $db->selectField( 'revision', 'rev_id',
3947 'rev_page' => $this->getArticleId( $flags ),
3948 'rev_id > ' . intval( $revId )
3951 array( 'ORDER BY' => 'rev_id' )
3956 * Get the first revision of the page
3958 * @param $flags Int Title::GAID_FOR_UPDATE
3959 * @return Revision|Null if page doesn't exist
3961 public function getFirstRevision( $flags = 0 ) {
3962 $pageId = $this->getArticleId( $flags );
3964 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3965 $row = $db->selectRow( 'revision', '*',
3966 array( 'rev_page' => $pageId ),
3968 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3971 return new Revision( $row );
3978 * Get the oldest revision timestamp of this page
3980 * @param $flags Int Title::GAID_FOR_UPDATE
3981 * @return String: MW timestamp
3983 public function getEarliestRevTime( $flags = 0 ) {
3984 $rev = $this->getFirstRevision( $flags );
3985 return $rev ?
$rev->getTimestamp() : null;
3989 * Check if this is a new page
3993 public function isNewPage() {
3994 $dbr = wfGetDB( DB_SLAVE
);
3995 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3999 * Get the number of revisions between the given revision.
4000 * Used for diffs and other things that really need it.
4002 * @param $old int|Revision Old revision or rev ID (first before range)
4003 * @param $new int|Revision New revision or rev ID (first after range)
4004 * @return Int Number of revisions between these revisions.
4006 public function countRevisionsBetween( $old, $new ) {
4007 if ( !( $old instanceof Revision
) ) {
4008 $old = Revision
::newFromTitle( $this, (int)$old );
4010 if ( !( $new instanceof Revision
) ) {
4011 $new = Revision
::newFromTitle( $this, (int)$new );
4013 if ( !$old ||
!$new ) {
4014 return 0; // nothing to compare
4016 $dbr = wfGetDB( DB_SLAVE
);
4017 return (int)$dbr->selectField( 'revision', 'count(*)',
4019 'rev_page' => $this->getArticleId(),
4020 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4021 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4028 * Get the number of authors between the given revision IDs.
4029 * Used for diffs and other things that really need it.
4031 * @param $old int|Revision Old revision or rev ID (first before range)
4032 * @param $new int|Revision New revision or rev ID (first after range)
4033 * @param $limit Int Maximum number of authors
4034 * @return Int Number of revision authors between these revisions.
4036 public function countAuthorsBetween( $old, $new, $limit ) {
4037 if ( !( $old instanceof Revision
) ) {
4038 $old = Revision
::newFromTitle( $this, (int)$old );
4040 if ( !( $new instanceof Revision
) ) {
4041 $new = Revision
::newFromTitle( $this, (int)$new );
4043 if ( !$old ||
!$new ) {
4044 return 0; // nothing to compare
4046 $dbr = wfGetDB( DB_SLAVE
);
4047 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4049 'rev_page' => $this->getArticleID(),
4050 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4051 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4053 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4055 return (int)$dbr->numRows( $res );
4059 * Compare with another title.
4061 * @param $title Title
4064 public function equals( Title
$title ) {
4065 // Note: === is necessary for proper matching of number-like titles.
4066 return $this->getInterwiki() === $title->getInterwiki()
4067 && $this->getNamespace() == $title->getNamespace()
4068 && $this->getDBkey() === $title->getDBkey();
4072 * Check if this title is a subpage of another title
4074 * @param $title Title
4077 public function isSubpageOf( Title
$title ) {
4078 return $this->getInterwiki() === $title->getInterwiki()
4079 && $this->getNamespace() == $title->getNamespace()
4080 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4084 * Check if page exists. For historical reasons, this function simply
4085 * checks for the existence of the title in the page table, and will
4086 * thus return false for interwiki links, special pages and the like.
4087 * If you want to know if a title can be meaningfully viewed, you should
4088 * probably call the isKnown() method instead.
4092 public function exists() {
4093 return $this->getArticleId() != 0;
4097 * Should links to this title be shown as potentially viewable (i.e. as
4098 * "bluelinks"), even if there's no record by this title in the page
4101 * This function is semi-deprecated for public use, as well as somewhat
4102 * misleadingly named. You probably just want to call isKnown(), which
4103 * calls this function internally.
4105 * (ISSUE: Most of these checks are cheap, but the file existence check
4106 * can potentially be quite expensive. Including it here fixes a lot of
4107 * existing code, but we might want to add an optional parameter to skip
4108 * it and any other expensive checks.)
4112 public function isAlwaysKnown() {
4113 if ( $this->mInterwiki
!= '' ) {
4114 return true; // any interwiki link might be viewable, for all we know
4116 switch( $this->mNamespace
) {
4119 // file exists, possibly in a foreign repo
4120 return (bool)wfFindFile( $this );
4122 // valid special page
4123 return SpecialPageFactory
::exists( $this->getDBkey() );
4125 // selflink, possibly with fragment
4126 return $this->mDbkeyform
== '';
4128 // known system message
4129 return $this->hasSourceText() !== false;
4136 * Does this title refer to a page that can (or might) be meaningfully
4137 * viewed? In particular, this function may be used to determine if
4138 * links to the title should be rendered as "bluelinks" (as opposed to
4139 * "redlinks" to non-existent pages).
4143 public function isKnown() {
4144 return $this->isAlwaysKnown() ||
$this->exists();
4148 * Does this page have source text?
4152 public function hasSourceText() {
4153 if ( $this->exists() ) {
4157 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4158 // If the page doesn't exist but is a known system message, default
4159 // message content will be displayed, same for language subpages-
4160 // Use always content language to avoid loading hundreds of languages
4161 // to get the link color.
4163 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4164 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4165 return $message->exists();
4172 * Get the default message text or false if the message doesn't exist
4174 * @return String or false
4176 public function getDefaultMessageText() {
4179 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4183 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4184 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4186 if ( $message->exists() ) {
4187 return $message->plain();
4194 * Updates page_touched for this page; called from LinksUpdate.php
4196 * @return Bool true if the update succeded
4198 public function invalidateCache() {
4199 if ( wfReadOnly() ) {
4202 $dbw = wfGetDB( DB_MASTER
);
4203 $success = $dbw->update(
4205 array( 'page_touched' => $dbw->timestamp() ),
4209 HTMLFileCache
::clearFileCache( $this );
4214 * Update page_touched timestamps and send squid purge messages for
4215 * pages linking to this title. May be sent to the job queue depending
4216 * on the number of links. Typically called on create and delete.
4218 public function touchLinks() {
4219 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4222 if ( $this->getNamespace() == NS_CATEGORY
) {
4223 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4229 * Get the last touched timestamp
4231 * @param $db DatabaseBase: optional db
4232 * @return String last-touched timestamp
4234 public function getTouched( $db = null ) {
4235 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4236 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4241 * Get the timestamp when this page was updated since the user last saw it.
4244 * @return String|Null
4246 public function getNotificationTimestamp( $user = null ) {
4247 global $wgUser, $wgShowUpdatedMarker;
4248 // Assume current user if none given
4252 // Check cache first
4253 $uid = $user->getId();
4254 // avoid isset here, as it'll return false for null entries
4255 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4256 return $this->mNotificationTimestamp
[$uid];
4258 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4259 return $this->mNotificationTimestamp
[$uid] = false;
4261 // Don't cache too much!
4262 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4263 $this->mNotificationTimestamp
= array();
4265 $dbr = wfGetDB( DB_SLAVE
);
4266 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4267 'wl_notificationtimestamp',
4268 array( 'wl_namespace' => $this->getNamespace(),
4269 'wl_title' => $this->getDBkey(),
4270 'wl_user' => $user->getId()
4274 return $this->mNotificationTimestamp
[$uid];
4278 * Generate strings used for xml 'id' names in monobook tabs
4280 * @param $prepend string defaults to 'nstab-'
4281 * @return String XML 'id' name
4283 public function getNamespaceKey( $prepend = 'nstab-' ) {
4285 // Gets the subject namespace if this title
4286 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4287 // Checks if cononical namespace name exists for namespace
4288 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4289 // Uses canonical namespace name
4290 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4292 // Uses text of namespace
4293 $namespaceKey = $this->getSubjectNsText();
4295 // Makes namespace key lowercase
4296 $namespaceKey = $wgContLang->lc( $namespaceKey );
4298 if ( $namespaceKey == '' ) {
4299 $namespaceKey = 'main';
4301 // Changes file to image for backwards compatibility
4302 if ( $namespaceKey == 'file' ) {
4303 $namespaceKey = 'image';
4305 return $prepend . $namespaceKey;
4309 * Get all extant redirects to this Title
4311 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4312 * @return Array of Title redirects to this title
4314 public function getRedirectsHere( $ns = null ) {
4317 $dbr = wfGetDB( DB_SLAVE
);
4319 'rd_namespace' => $this->getNamespace(),
4320 'rd_title' => $this->getDBkey(),
4323 if ( !is_null( $ns ) ) {
4324 $where['page_namespace'] = $ns;
4327 $res = $dbr->select(
4328 array( 'redirect', 'page' ),
4329 array( 'page_namespace', 'page_title' ),
4334 foreach ( $res as $row ) {
4335 $redirs[] = self
::newFromRow( $row );
4341 * Check if this Title is a valid redirect target
4345 public function isValidRedirectTarget() {
4346 global $wgInvalidRedirectTargets;
4348 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4349 if ( $this->isSpecial( 'Userlogout' ) ) {
4353 foreach ( $wgInvalidRedirectTargets as $target ) {
4354 if ( $this->isSpecial( $target ) ) {
4363 * Get a backlink cache object
4365 * @return BacklinkCache
4367 function getBacklinkCache() {
4368 if ( is_null( $this->mBacklinkCache
) ) {
4369 $this->mBacklinkCache
= new BacklinkCache( $this );
4371 return $this->mBacklinkCache
;
4375 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4379 public function canUseNoindex() {
4380 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4382 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4383 ?
$wgContentNamespaces
4384 : $wgExemptFromUserRobotsControl;
4386 return !in_array( $this->mNamespace
, $bannedNamespaces );
4391 * Returns the raw sort key to be used for categories, with the specified
4392 * prefix. This will be fed to Collation::getSortKey() to get a
4393 * binary sortkey that can be used for actual sorting.
4395 * @param $prefix string The prefix to be used, specified using
4396 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4400 public function getCategorySortkey( $prefix = '' ) {
4401 $unprefixed = $this->getText();
4403 // Anything that uses this hook should only depend
4404 // on the Title object passed in, and should probably
4405 // tell the users to run updateCollations.php --force
4406 // in order to re-sort existing category relations.
4407 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4408 if ( $prefix !== '' ) {
4409 # Separate with a line feed, so the unprefixed part is only used as
4410 # a tiebreaker when two pages have the exact same prefix.
4411 # In UCA, tab is the only character that can sort above LF
4412 # so we strip both of them from the original prefix.
4413 $prefix = strtr( $prefix, "\n\t", ' ' );
4414 return "$prefix\n$unprefixed";
4420 * Get the language in which the content of this page is written.
4421 * Defaults to $wgContLang, but in certain cases it can be e.g.
4422 * $wgLang (such as special pages, which are in the user language).
4425 * @return object Language
4427 public function getPageLanguage() {
4429 if ( $this->isSpecialPage() ) {
4430 // special pages are in the user language
4432 } elseif ( $this->isCssOrJsPage() ) {
4433 // css/js should always be LTR and is, in fact, English
4434 return wfGetLangObj( 'en' );
4435 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4436 // Parse mediawiki messages with correct target language
4437 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4438 return wfGetLangObj( $lang );
4441 // If nothing special, it should be in the wiki content language
4442 $pageLang = $wgContLang;
4443 // Hook at the end because we don't want to override the above stuff
4444 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4445 return wfGetLangObj( $pageLang );