3 * Representation a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
31 * @internal documentation reviewed 15 Mar 2010
34 /** @name Static cache variables */
36 static private $titleCache = array();
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
83 # Zero except in {{transclusion}} tags
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mBacklinkCache = null; // /< Cache of links to this title
89 var $mHasSubpage; // /< Whether a page has any subpages
96 /*protected*/ function __construct() { }
99 * Create a new Title from a prefixed DB key
101 * @param $key String the database key, which has underscores
102 * instead of spaces, possibly including namespace and
104 * @return Title, or NULL on an error
106 public static function newFromDBkey( $key ) {
108 $t->mDbkeyform
= $key;
109 if ( $t->secureAndSplit() ) {
117 * Create a new Title from text, such as what one would find in a link. De-
118 * codes any HTML entities in the text.
120 * @param $text String the link text; spaces, prefixes, and an
121 * initial ':' indicating the main namespace are accepted.
122 * @param $defaultNamespace Int the namespace to use if none is speci-
123 * fied by a prefix. If you want to force a specific namespace even if
124 * $text might begin with a namespace prefix, use makeTitle() or
126 * @throws MWException
127 * @return Title|null - Title or null on an error.
129 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
130 if ( is_object( $text ) ) {
131 throw new MWException( 'Title::newFromText given an object' );
135 * Wiki pages often contain multiple links to the same page.
136 * Title normalization and parsing can become expensive on
137 * pages with many links, so we can save a little time by
140 * In theory these are value objects and won't get changed...
142 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
143 return Title
::$titleCache[$text];
146 # Convert things like é ā or 〗 into normalized (bug 14952) text
147 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
150 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
151 $t->mDefaultNamespace
= $defaultNamespace;
153 static $cachedcount = 0 ;
154 if ( $t->secureAndSplit() ) {
155 if ( $defaultNamespace == NS_MAIN
) {
156 if ( $cachedcount >= self
::CACHE_MAX
) {
157 # Avoid memory leaks on mass operations...
158 Title
::$titleCache = array();
162 Title
::$titleCache[$text] =& $t;
172 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
174 * Example of wrong and broken code:
175 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
177 * Example of right code:
178 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
180 * Create a new Title from URL-encoded text. Ensures that
181 * the given title's length does not exceed the maximum.
183 * @param $url String the title, as might be taken from a URL
184 * @return Title the new object, or NULL on an error
186 public static function newFromURL( $url ) {
189 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
190 # but some URLs used it as a space replacement and they still come
191 # from some external search tools.
192 if ( strpos( self
::legalChars(), '+' ) === false ) {
193 $url = str_replace( '+', ' ', $url );
196 $t->mDbkeyform
= str_replace( ' ', '_', $url );
197 if ( $t->secureAndSplit() ) {
205 * Create a new Title from an article ID
207 * @param $id Int the page_id corresponding to the Title to create
208 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
209 * @return Title the new object, or NULL on an error
211 public static function newFromID( $id, $flags = 0 ) {
212 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
213 $row = $db->selectRow(
216 'page_namespace', 'page_title', 'page_id',
217 'page_len', 'page_is_redirect', 'page_latest',
219 array( 'page_id' => $id ),
222 if ( $row !== false ) {
223 $title = Title
::newFromRow( $row );
231 * Make an array of titles from an array of IDs
233 * @param $ids Array of Int Array of IDs
234 * @return Array of Titles
236 public static function newFromIDs( $ids ) {
237 if ( !count( $ids ) ) {
240 $dbr = wfGetDB( DB_SLAVE
);
245 'page_namespace', 'page_title', 'page_id',
246 'page_len', 'page_is_redirect', 'page_latest',
248 array( 'page_id' => $ids ),
253 foreach ( $res as $row ) {
254 $titles[] = Title
::newFromRow( $row );
260 * Make a Title object from a DB row
262 * @param $row Object database row (needs at least page_title,page_namespace)
263 * @return Title corresponding Title
265 public static function newFromRow( $row ) {
266 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
267 $t->loadFromRow( $row );
272 * Load Title object fields from a DB row.
273 * If false is given, the title will be treated as non-existing.
275 * @param $row Object|bool database row
277 public function loadFromRow( $row ) {
278 if ( $row ) { // page found
279 if ( isset( $row->page_id
) )
280 $this->mArticleID
= (int)$row->page_id
;
281 if ( isset( $row->page_len
) )
282 $this->mLength
= (int)$row->page_len
;
283 if ( isset( $row->page_is_redirect
) )
284 $this->mRedirect
= (bool)$row->page_is_redirect
;
285 if ( isset( $row->page_latest
) )
286 $this->mLatestID
= (int)$row->page_latest
; # FIXME: whene3ver page_latest is updated, also update page_content_model
287 if ( isset( $row->page_content_model
) )
288 $this->mContentModel
= intval( $row->page_content_model
);
290 $this->mContentModel
= null; # initialized lazily in getContentModel()
291 } else { // page not found
292 $this->mArticleID
= 0;
294 $this->mRedirect
= false;
295 $this->mLatestID
= 0;
296 $this->mContentModel
= null; # initialized lazily in getContentModel()
301 * Create a new Title from a namespace index and a DB key.
302 * It's assumed that $ns and $title are *valid*, for instance when
303 * they came directly from the database or a special page name.
304 * For convenience, spaces are converted to underscores so that
305 * eg user_text fields can be used directly.
307 * @param $ns Int the namespace of the article
308 * @param $title String the unprefixed database key form
309 * @param $fragment String the link fragment (after the "#")
310 * @param $interwiki String the interwiki prefix
311 * @return Title the new object
313 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
315 $t->mInterwiki
= $interwiki;
316 $t->mFragment
= $fragment;
317 $t->mNamespace
= $ns = intval( $ns );
318 $t->mDbkeyform
= str_replace( ' ', '_', $title );
319 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
320 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
321 $t->mTextform
= str_replace( '_', ' ', $title );
322 $t->mContentModel
= null; # initialized lazily in getContentModel()
327 * Create a new Title from a namespace index and a DB key.
328 * The parameters will be checked for validity, which is a bit slower
329 * than makeTitle() but safer for user-provided data.
331 * @param $ns Int the namespace of the article
332 * @param $title String database key form
333 * @param $fragment String the link fragment (after the "#")
334 * @param $interwiki String interwiki prefix
335 * @return Title the new object, or NULL on an error
337 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
338 if ( !MWNamespace
::exists( $ns ) ) {
343 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
344 if ( $t->secureAndSplit() ) {
352 * Create a new Title for the Main Page
354 * @return Title the new object
356 public static function newMainPage() {
357 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
358 // Don't give fatal errors if the message is broken
360 $title = Title
::newFromText( 'Main Page' );
366 * Extract a redirect destination from a string and return the
367 * Title, or null if the text doesn't contain a valid redirect
368 * This will only return the very next target, useful for
369 * the redirect table and other checks that don't need full recursion
371 * @param $text String: Text with possible redirect
372 * @return Title: The corresponding Title
374 public static function newFromRedirect( $text ) {
375 return self
::newFromRedirectInternal( $text );
379 * Extract a redirect destination from a string and return the
380 * Title, or null if the text doesn't contain a valid redirect
381 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
382 * in order to provide (hopefully) the Title of the final destination instead of another redirect
384 * @param $text String Text with possible redirect
387 public static function newFromRedirectRecurse( $text ) {
388 $titles = self
::newFromRedirectArray( $text );
389 return $titles ?
array_pop( $titles ) : null;
393 * Extract a redirect destination from a string and return an
394 * array of Titles, or null if the text doesn't contain a valid redirect
395 * The last element in the array is the final destination after all redirects
396 * have been resolved (up to $wgMaxRedirects times)
398 * @param $text String Text with possible redirect
399 * @return Array of Titles, with the destination last
401 public static function newFromRedirectArray( $text ) {
402 global $wgMaxRedirects;
403 $title = self
::newFromRedirectInternal( $text );
404 if ( is_null( $title ) ) {
407 // recursive check to follow double redirects
408 $recurse = $wgMaxRedirects;
409 $titles = array( $title );
410 while ( --$recurse > 0 ) {
411 if ( $title->isRedirect() ) {
412 $page = WikiPage
::factory( $title );
413 $newtitle = $page->getRedirectTarget();
417 // Redirects to some special pages are not permitted
418 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
419 // the new title passes the checks, so make that our current title so that further recursion can be checked
421 $titles[] = $newtitle;
430 * Really extract the redirect destination
431 * Do not call this function directly, use one of the newFromRedirect* functions above
433 * @param $text String Text with possible redirect
436 protected static function newFromRedirectInternal( $text ) {
437 global $wgMaxRedirects;
438 if ( $wgMaxRedirects < 1 ) {
439 //redirects are disabled, so quit early
442 $redir = MagicWord
::get( 'redirect' );
443 $text = trim( $text );
444 if ( $redir->matchStartAndRemove( $text ) ) {
445 // Extract the first link and see if it's usable
446 // Ensure that it really does come directly after #REDIRECT
447 // Some older redirects included a colon, so don't freak about that!
449 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
450 // Strip preceding colon used to "escape" categories, etc.
451 // and URL-decode links
452 if ( strpos( $m[1], '%' ) !== false ) {
453 // Match behavior of inline link parsing here;
454 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
456 $title = Title
::newFromText( $m[1] );
457 // If the title is a redirect to bad special pages or is invalid, return null
458 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
468 * Get the prefixed DB key associated with an ID
470 * @param $id Int the page_id of the article
471 * @return Title an object representing the article, or NULL if no such article was found
473 public static function nameOf( $id ) {
474 $dbr = wfGetDB( DB_SLAVE
);
476 $s = $dbr->selectRow(
478 array( 'page_namespace', 'page_title' ),
479 array( 'page_id' => $id ),
482 if ( $s === false ) {
486 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
491 * Get a regex character class describing the legal characters in a link
493 * @return String the list of characters, not delimited
495 public static function legalChars() {
496 global $wgLegalTitleChars;
497 return $wgLegalTitleChars;
501 * Returns a simple regex that will match on characters and sequences invalid in titles.
502 * Note that this doesn't pick up many things that could be wrong with titles, but that
503 * replacing this regex with something valid will make many titles valid.
505 * @return String regex string
507 static function getTitleInvalidRegex() {
508 static $rxTc = false;
510 # Matching titles will be held as illegal.
512 # Any character not allowed is forbidden...
513 '[^' . self
::legalChars() . ']' .
514 # URL percent encoding sequences interfere with the ability
515 # to round-trip titles -- you can't link to them consistently.
517 # XML/HTML character references produce similar issues.
518 '|&[A-Za-z0-9\x80-\xff]+;' .
520 '|&#x[0-9A-Fa-f]+;' .
528 * Get a string representation of a title suitable for
529 * including in a search index
531 * @param $ns Int a namespace index
532 * @param $title String text-form main part
533 * @return String a stripped-down title string ready for the search index
535 public static function indexTitle( $ns, $title ) {
538 $lc = SearchEngine
::legalSearchChars() . '&#;';
539 $t = $wgContLang->normalizeForSearch( $title );
540 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
541 $t = $wgContLang->lc( $t );
544 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
545 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
547 $t = preg_replace( "/\\s+/", ' ', $t );
549 if ( $ns == NS_FILE
) {
550 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
556 * Make a prefixed DB key from a DB key and a namespace index
558 * @param $ns Int numerical representation of the namespace
559 * @param $title String the DB key form the title
560 * @param $fragment String The link fragment (after the "#")
561 * @param $interwiki String The interwiki prefix
562 * @return String the prefixed form of the title
564 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
567 $namespace = $wgContLang->getNsText( $ns );
568 $name = $namespace == '' ?
$title : "$namespace:$title";
569 if ( strval( $interwiki ) != '' ) {
570 $name = "$interwiki:$name";
572 if ( strval( $fragment ) != '' ) {
573 $name .= '#' . $fragment;
579 * Escape a text fragment, say from a link, for a URL
581 * @param $fragment string containing a URL or link fragment (after the "#")
582 * @return String: escaped string
584 static function escapeFragmentForURL( $fragment ) {
585 # Note that we don't urlencode the fragment. urlencoded Unicode
586 # fragments appear not to work in IE (at least up to 7) or in at least
587 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
588 # to care if they aren't encoded.
589 return Sanitizer
::escapeId( $fragment, 'noninitial' );
593 * Callback for usort() to do title sorts by (namespace, title)
598 * @return Integer: result of string comparison, or namespace comparison
600 public static function compare( $a, $b ) {
601 if ( $a->getNamespace() == $b->getNamespace() ) {
602 return strcmp( $a->getText(), $b->getText() );
604 return $a->getNamespace() - $b->getNamespace();
609 * Determine whether the object refers to a page within
612 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
614 public function isLocal() {
615 if ( $this->mInterwiki
!= '' ) {
616 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
623 * Is this Title interwiki?
627 public function isExternal() {
628 return ( $this->mInterwiki
!= '' );
632 * Get the interwiki prefix (or null string)
634 * @return String Interwiki prefix
636 public function getInterwiki() {
637 return $this->mInterwiki
;
641 * Determine whether the object refers to a page within
642 * this project and is transcludable.
644 * @return Bool TRUE if this is transcludable
646 public function isTrans() {
647 if ( $this->mInterwiki
== '' ) {
651 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
655 * Returns the DB name of the distant wiki which owns the object.
657 * @return String the DB name
659 public function getTransWikiID() {
660 if ( $this->mInterwiki
== '' ) {
664 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
668 * Get the text form (spaces not underscores) of the main part
670 * @return String Main part of the title
672 public function getText() {
673 return $this->mTextform
;
677 * Get the URL-encoded form of the main part
679 * @return String Main part of the title, URL-encoded
681 public function getPartialURL() {
682 return $this->mUrlform
;
686 * Get the main part with underscores
688 * @return String: Main part of the title, with underscores
690 public function getDBkey() {
691 return $this->mDbkeyform
;
695 * Get the DB key with the initial letter case as specified by the user
697 * @return String DB key
699 function getUserCaseDBKey() {
700 return $this->mUserCaseDBKey
;
704 * Get the namespace index, i.e. one of the NS_xxxx constants.
706 * @return Integer: Namespace index
708 public function getNamespace() {
709 return $this->mNamespace
;
713 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
715 * @return Integer: Content model id
717 public function getContentModel() {
718 if ( empty( $this->mContentModel
) ) {
719 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
722 assert( !empty( $this->mContentModel
) );
723 return $this->mContentModel
;
727 * Conveniance method for checking a title's content model name
730 * @return true if $this->getContentModel() == $id
732 public function hasContentModel( $id ) {
733 return $this->getContentModel() == $id;
737 * Get the namespace text
739 * @return String: Namespace text
741 public function getNsText() {
744 if ( $this->mInterwiki
!= '' ) {
745 // This probably shouldn't even happen. ohh man, oh yuck.
746 // But for interwiki transclusion it sometimes does.
747 // Shit. Shit shit shit.
749 // Use the canonical namespaces if possible to try to
750 // resolve a foreign namespace.
751 if ( MWNamespace
::exists( $this->mNamespace
) ) {
752 return MWNamespace
::getCanonicalName( $this->mNamespace
);
756 if ( $wgContLang->needsGenderDistinction() &&
757 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
758 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
759 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
762 return $wgContLang->getNsText( $this->mNamespace
);
766 * Get the namespace text of the subject (rather than talk) page
768 * @return String Namespace text
770 public function getSubjectNsText() {
772 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
776 * Get the namespace text of the talk page
778 * @return String Namespace text
780 public function getTalkNsText() {
782 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
786 * Could this title have a corresponding talk page?
788 * @return Bool TRUE or FALSE
790 public function canTalk() {
791 return( MWNamespace
::canTalk( $this->mNamespace
) );
795 * Is this in a namespace that allows actual pages?
798 * @internal note -- uses hardcoded namespace index instead of constants
800 public function canExist() {
801 return $this->mNamespace
>= NS_MAIN
;
805 * Can this title be added to a user's watchlist?
807 * @return Bool TRUE or FALSE
809 public function isWatchable() {
810 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
814 * Returns true if this is a special page.
818 public function isSpecialPage() {
819 return $this->getNamespace() == NS_SPECIAL
;
823 * Returns true if this title resolves to the named special page
825 * @param $name String The special page name
828 public function isSpecial( $name ) {
829 if ( $this->isSpecialPage() ) {
830 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
831 if ( $name == $thisName ) {
839 * If the Title refers to a special page alias which is not the local default, resolve
840 * the alias, and localise the name as necessary. Otherwise, return $this
844 public function fixSpecialName() {
845 if ( $this->isSpecialPage() ) {
846 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
847 if ( $canonicalName ) {
848 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
849 if ( $localName != $this->mDbkeyform
) {
850 return Title
::makeTitle( NS_SPECIAL
, $localName );
858 * Returns true if the title is inside the specified namespace.
860 * Please make use of this instead of comparing to getNamespace()
861 * This function is much more resistant to changes we may make
862 * to namespaces than code that makes direct comparisons.
863 * @param $ns int The namespace
867 public function inNamespace( $ns ) {
868 return MWNamespace
::equals( $this->getNamespace(), $ns );
872 * Returns true if the title is inside one of the specified namespaces.
874 * @param ...$namespaces The namespaces to check for
878 public function inNamespaces( /* ... */ ) {
879 $namespaces = func_get_args();
880 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
881 $namespaces = $namespaces[0];
884 foreach ( $namespaces as $ns ) {
885 if ( $this->inNamespace( $ns ) ) {
894 * Returns true if the title has the same subject namespace as the
895 * namespace specified.
896 * For example this method will take NS_USER and return true if namespace
897 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
898 * as their subject namespace.
900 * This is MUCH simpler than individually testing for equivilance
901 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
906 public function hasSubjectNamespace( $ns ) {
907 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
911 * Is this Title in a namespace which contains content?
912 * In other words, is this a content page, for the purposes of calculating
917 public function isContentPage() {
918 return MWNamespace
::isContent( $this->getNamespace() );
922 * Would anybody with sufficient privileges be able to move this page?
923 * Some pages just aren't movable.
925 * @return Bool TRUE or FALSE
927 public function isMovable() {
928 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
929 // Interwiki title or immovable namespace. Hooks don't get to override here
934 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
939 * Is this the mainpage?
940 * @note Title::newFromText seams to be sufficiently optimized by the title
941 * cache that we don't need to over-optimize by doing direct comparisons and
942 * acidentally creating new bugs where $title->equals( Title::newFromText() )
943 * ends up reporting something differently than $title->isMainPage();
948 public function isMainPage() {
949 return $this->equals( Title
::newMainPage() );
957 public function isSubpage() {
958 return MWNamespace
::hasSubpages( $this->mNamespace
)
959 ?
strpos( $this->getText(), '/' ) !== false
964 * Is this a conversion table for the LanguageConverter?
968 public function isConversionTable() {
969 return $this->getNamespace() == NS_MEDIAWIKI
&&
970 strpos( $this->getText(), 'Conversiontable' ) !== false;
974 * Does that page contain wikitext, or it is JS, CSS or whatever?
978 public function isWikitextPage() {
979 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
983 * Could this page contain custom CSS or JavaScript for the global UI.
984 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
985 * or CONTENT_MODEL_JAVASCRIPT.
987 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
989 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
993 public function isCssOrJsPage() {
994 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
995 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
996 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
998 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
999 # hook funktions can force this method to return true even outside the mediawiki namespace.
1001 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1003 return $isCssOrJsPage;
1007 * Is this a .css or .js subpage of a user page?
1010 public function isCssJsSubpage() {
1011 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1012 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1013 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1017 * Trim down a .css or .js subpage title to get the corresponding skin name
1019 * @return string containing skin name from .css or .js subpage title
1021 public function getSkinFromCssJsSubpage() {
1022 $subpage = explode( '/', $this->mTextform
);
1023 $subpage = $subpage[ count( $subpage ) - 1 ];
1024 $lastdot = strrpos( $subpage, '.' );
1025 if ( $lastdot === false )
1026 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1027 return substr( $subpage, 0, $lastdot );
1031 * Is this a .css subpage of a user page?
1035 public function isCssSubpage() {
1036 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1037 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1041 * Is this a .js subpage of a user page?
1045 public function isJsSubpage() {
1046 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1047 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1051 * Is this a talk page of some sort?
1055 public function isTalkPage() {
1056 return MWNamespace
::isTalk( $this->getNamespace() );
1060 * Get a Title object associated with the talk page of this article
1062 * @return Title the object for the talk page
1064 public function getTalkPage() {
1065 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1069 * Get a title object associated with the subject page of this
1072 * @return Title the object for the subject page
1074 public function getSubjectPage() {
1075 // Is this the same title?
1076 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1077 if ( $this->getNamespace() == $subjectNS ) {
1080 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1084 * Get the default namespace index, for when there is no namespace
1086 * @return Int Default namespace index
1088 public function getDefaultNamespace() {
1089 return $this->mDefaultNamespace
;
1093 * Get title for search index
1095 * @return String a stripped-down title string ready for the
1098 public function getIndexTitle() {
1099 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1103 * Get the Title fragment (i.e.\ the bit after the #) in text form
1105 * @return String Title fragment
1107 public function getFragment() {
1108 return $this->mFragment
;
1112 * Get the fragment in URL form, including the "#" character if there is one
1113 * @return String Fragment in URL form
1115 public function getFragmentForURL() {
1116 if ( $this->mFragment
== '' ) {
1119 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1124 * Set the fragment for this title. Removes the first character from the
1125 * specified fragment before setting, so it assumes you're passing it with
1128 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1129 * Still in active use privately.
1131 * @param $fragment String text
1133 public function setFragment( $fragment ) {
1134 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1138 * Prefix some arbitrary text with the namespace or interwiki prefix
1141 * @param $name String the text
1142 * @return String the prefixed text
1145 private function prefix( $name ) {
1147 if ( $this->mInterwiki
!= '' ) {
1148 $p = $this->mInterwiki
. ':';
1151 if ( 0 != $this->mNamespace
) {
1152 $p .= $this->getNsText() . ':';
1158 * Get the prefixed database key form
1160 * @return String the prefixed title, with underscores and
1161 * any interwiki and namespace prefixes
1163 public function getPrefixedDBkey() {
1164 $s = $this->prefix( $this->mDbkeyform
);
1165 $s = str_replace( ' ', '_', $s );
1170 * Get the prefixed title with spaces.
1171 * This is the form usually used for display
1173 * @return String the prefixed title, with spaces
1175 public function getPrefixedText() {
1176 // @todo FIXME: Bad usage of empty() ?
1177 if ( empty( $this->mPrefixedText
) ) {
1178 $s = $this->prefix( $this->mTextform
);
1179 $s = str_replace( '_', ' ', $s );
1180 $this->mPrefixedText
= $s;
1182 return $this->mPrefixedText
;
1186 * Return a string representation of this title
1188 * @return String representation of this title
1190 public function __toString() {
1191 return $this->getPrefixedText();
1195 * Get the prefixed title with spaces, plus any fragment
1196 * (part beginning with '#')
1198 * @return String the prefixed title, with spaces and the fragment, including '#'
1200 public function getFullText() {
1201 $text = $this->getPrefixedText();
1202 if ( $this->mFragment
!= '' ) {
1203 $text .= '#' . $this->mFragment
;
1209 * Get the base page name, i.e. the leftmost part before any slashes
1211 * @return String Base name
1213 public function getBaseText() {
1214 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1215 return $this->getText();
1218 $parts = explode( '/', $this->getText() );
1219 # Don't discard the real title if there's no subpage involved
1220 if ( count( $parts ) > 1 ) {
1221 unset( $parts[count( $parts ) - 1] );
1223 return implode( '/', $parts );
1227 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1229 * @return String Subpage name
1231 public function getSubpageText() {
1232 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1233 return( $this->mTextform
);
1235 $parts = explode( '/', $this->mTextform
);
1236 return( $parts[count( $parts ) - 1] );
1240 * Get the HTML-escaped displayable text form.
1241 * Used for the title field in <a> tags.
1243 * @return String the text, including any prefixes
1245 public function getEscapedText() {
1246 wfDeprecated( __METHOD__
, '1.19' );
1247 return htmlspecialchars( $this->getPrefixedText() );
1251 * Get a URL-encoded form of the subpage text
1253 * @return String URL-encoded subpage name
1255 public function getSubpageUrlForm() {
1256 $text = $this->getSubpageText();
1257 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1262 * Get a URL-encoded title (not an actual URL) including interwiki
1264 * @return String the URL-encoded form
1266 public function getPrefixedURL() {
1267 $s = $this->prefix( $this->mDbkeyform
);
1268 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1273 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1274 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1275 * second argument named variant. This was deprecated in favor
1276 * of passing an array of option with a "variant" key
1277 * Once $query2 is removed for good, this helper can be dropped
1278 * andthe wfArrayToCGI moved to getLocalURL();
1280 * @since 1.19 (r105919)
1282 * @param $query2 bool
1285 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1286 if( $query2 !== false ) {
1287 wfDeprecated( "Title::get{Canonical,Full,Link,Local} method called with a second parameter is deprecated. Add your parameter to an array passed as the first parameter.", "1.19" );
1289 if ( is_array( $query ) ) {
1290 $query = wfArrayToCGI( $query );
1293 if ( is_string( $query2 ) ) {
1294 // $query2 is a string, we will consider this to be
1295 // a deprecated $variant argument and add it to the query
1296 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1298 $query2 = wfArrayToCGI( $query2 );
1300 // If we have $query content add a & to it first
1304 // Now append the queries together
1311 * Get a real URL referring to this title, with interwiki link and
1314 * See getLocalURL for the arguments.
1316 * @see self::getLocalURL
1317 * @return String the URL
1319 public function getFullURL( $query = '', $query2 = false ) {
1320 $query = self
::fixUrlQueryArgs( $query, $query2 );
1322 # Hand off all the decisions on urls to getLocalURL
1323 $url = $this->getLocalURL( $query );
1325 # Expand the url to make it a full url. Note that getLocalURL has the
1326 # potential to output full urls for a variety of reasons, so we use
1327 # wfExpandUrl instead of simply prepending $wgServer
1328 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1330 # Finally, add the fragment.
1331 $url .= $this->getFragmentForURL();
1333 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1338 * Get a URL with no fragment or server name. If this page is generated
1339 * with action=render, $wgServer is prepended.
1342 * @param $query string|array an optional query string,
1343 * not used for interwiki links. Can be specified as an associative array as well,
1344 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1345 * Some query patterns will trigger various shorturl path replacements.
1346 * @param $query2 Mixed: An optional secondary query array. This one MUST
1347 * be an array. If a string is passed it will be interpreted as a deprecated
1348 * variant argument and urlencoded into a variant= argument.
1349 * This second query argument will be added to the $query
1350 * The second parameter is deprecated since 1.19. Pass it as a key,value
1351 * pair in the first parameter array instead.
1353 * @return String the URL
1355 public function getLocalURL( $query = '', $query2 = false ) {
1356 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1358 $query = self
::fixUrlQueryArgs( $query, $query2 );
1360 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1362 $namespace = $this->getNsText();
1363 if ( $namespace != '' ) {
1364 # Can this actually happen? Interwikis shouldn't be parsed.
1365 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1368 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1369 $url = wfAppendQuery( $url, $query );
1371 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1372 if ( $query == '' ) {
1373 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1374 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1376 global $wgVariantArticlePath, $wgActionPaths;
1380 if ( !empty( $wgActionPaths ) &&
1381 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1383 $action = urldecode( $matches[2] );
1384 if ( isset( $wgActionPaths[$action] ) ) {
1385 $query = $matches[1];
1386 if ( isset( $matches[4] ) ) {
1387 $query .= $matches[4];
1389 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1390 if ( $query != '' ) {
1391 $url = wfAppendQuery( $url, $query );
1396 if ( $url === false &&
1397 $wgVariantArticlePath &&
1398 $this->getPageLanguage()->hasVariants() &&
1399 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1401 $variant = urldecode( $matches[1] );
1402 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1403 // Only do the variant replacement if the given variant is a valid
1404 // variant for the page's language.
1405 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1406 $url = str_replace( '$1', $dbkey, $url );
1410 if ( $url === false ) {
1411 if ( $query == '-' ) {
1414 $url = "{$wgScript}?title={$dbkey}&{$query}";
1418 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1420 // @todo FIXME: This causes breakage in various places when we
1421 // actually expected a local URL and end up with dupe prefixes.
1422 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1423 $url = $wgServer . $url;
1426 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1431 * Get a URL that's the simplest URL that will be valid to link, locally,
1432 * to the current Title. It includes the fragment, but does not include
1433 * the server unless action=render is used (or the link is external). If
1434 * there's a fragment but the prefixed text is empty, we just return a link
1437 * The result obviously should not be URL-escaped, but does need to be
1438 * HTML-escaped if it's being output in HTML.
1440 * See getLocalURL for the arguments.
1442 * @see self::getLocalURL
1443 * @return String the URL
1445 public function getLinkURL( $query = '', $query2 = false ) {
1446 wfProfileIn( __METHOD__
);
1447 if ( $this->isExternal() ) {
1448 $ret = $this->getFullURL( $query, $query2 );
1449 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1450 $ret = $this->getFragmentForURL();
1452 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1454 wfProfileOut( __METHOD__
);
1459 * Get an HTML-escaped version of the URL form, suitable for
1460 * using in a link, without a server name or fragment
1462 * See getLocalURL for the arguments.
1464 * @see self::getLocalURL
1465 * @param $query string
1466 * @param $query2 bool|string
1467 * @return String the URL
1469 public function escapeLocalURL( $query = '', $query2 = false ) {
1470 wfDeprecated( __METHOD__
, '1.19' );
1471 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1475 * Get an HTML-escaped version of the URL form, suitable for
1476 * using in a link, including the server name and fragment
1478 * See getLocalURL for the arguments.
1480 * @see self::getLocalURL
1481 * @return String the URL
1483 public function escapeFullURL( $query = '', $query2 = false ) {
1484 wfDeprecated( __METHOD__
, '1.19' );
1485 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1489 * Get the URL form for an internal link.
1490 * - Used in various Squid-related code, in case we have a different
1491 * internal hostname for the server from the exposed one.
1493 * This uses $wgInternalServer to qualify the path, or $wgServer
1494 * if $wgInternalServer is not set. If the server variable used is
1495 * protocol-relative, the URL will be expanded to http://
1497 * See getLocalURL for the arguments.
1499 * @see self::getLocalURL
1500 * @return String the URL
1502 public function getInternalURL( $query = '', $query2 = false ) {
1503 global $wgInternalServer, $wgServer;
1504 $query = self
::fixUrlQueryArgs( $query, $query2 );
1505 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1506 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1507 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1512 * Get the URL for a canonical link, for use in things like IRC and
1513 * e-mail notifications. Uses $wgCanonicalServer and the
1514 * GetCanonicalURL hook.
1516 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1518 * See getLocalURL for the arguments.
1520 * @see self::getLocalURL
1521 * @return string The URL
1524 public function getCanonicalURL( $query = '', $query2 = false ) {
1525 $query = self
::fixUrlQueryArgs( $query, $query2 );
1526 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1527 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1532 * HTML-escaped version of getCanonicalURL()
1534 * See getLocalURL for the arguments.
1536 * @see self::getLocalURL
1540 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1541 wfDeprecated( __METHOD__
, '1.19' );
1542 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1546 * Get the edit URL for this Title
1548 * @return String the URL, or a null string if this is an
1551 public function getEditURL() {
1552 if ( $this->mInterwiki
!= '' ) {
1555 $s = $this->getLocalURL( 'action=edit' );
1561 * Is $wgUser watching this page?
1565 public function userIsWatching() {
1568 if ( is_null( $this->mWatched
) ) {
1569 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1570 $this->mWatched
= false;
1572 $this->mWatched
= $wgUser->isWatched( $this );
1575 return $this->mWatched
;
1579 * Can $wgUser read this page?
1581 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1583 * @todo fold these checks into userCan()
1585 public function userCanRead() {
1586 wfDeprecated( __METHOD__
, '1.19' );
1587 return $this->userCan( 'read' );
1591 * Can $user perform $action on this page?
1592 * This skips potentially expensive cascading permission checks
1593 * as well as avoids expensive error formatting
1595 * Suitable for use for nonessential UI controls in common cases, but
1596 * _not_ for functional access control.
1598 * May provide false positives, but should never provide a false negative.
1600 * @param $action String action that permission needs to be checked for
1601 * @param $user User to check (since 1.19); $wgUser will be used if not
1605 public function quickUserCan( $action, $user = null ) {
1606 return $this->userCan( $action, $user, false );
1610 * Can $user perform $action on this page?
1612 * @param $action String action that permission needs to be checked for
1613 * @param $user User to check (since 1.19); $wgUser will be used if not
1615 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1616 * unnecessary queries.
1619 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1620 if ( !$user instanceof User
) {
1624 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1628 * Can $user perform $action on this page?
1630 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1632 * @param $action String action that permission needs to be checked for
1633 * @param $user User to check
1634 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1635 * queries by skipping checks for cascading protections and user blocks.
1636 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1637 * whose corresponding errors may be ignored.
1638 * @return Array of arguments to wfMsg to explain permissions problems.
1640 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1641 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1643 // Remove the errors being ignored.
1644 foreach ( $errors as $index => $error ) {
1645 $error_key = is_array( $error ) ?
$error[0] : $error;
1647 if ( in_array( $error_key, $ignoreErrors ) ) {
1648 unset( $errors[$index] );
1656 * Permissions checks that fail most often, and which are easiest to test.
1658 * @param $action String the action to check
1659 * @param $user User user to check
1660 * @param $errors Array list of current errors
1661 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1662 * @param $short Boolean short circuit on first error
1664 * @return Array list of errors
1666 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1667 if ( $action == 'create' ) {
1668 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1669 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1670 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1672 } elseif ( $action == 'move' ) {
1673 if ( !$user->isAllowed( 'move-rootuserpages' )
1674 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1675 // Show user page-specific message only if the user can move other pages
1676 $errors[] = array( 'cant-move-user-page' );
1679 // Check if user is allowed to move files if it's a file
1680 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1681 $errors[] = array( 'movenotallowedfile' );
1684 if ( !$user->isAllowed( 'move' ) ) {
1685 // User can't move anything
1686 global $wgGroupPermissions;
1687 $userCanMove = false;
1688 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1689 $userCanMove = $wgGroupPermissions['user']['move'];
1691 $autoconfirmedCanMove = false;
1692 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1693 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1695 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1696 // custom message if logged-in users without any special rights can move
1697 $errors[] = array( 'movenologintext' );
1699 $errors[] = array( 'movenotallowed' );
1702 } elseif ( $action == 'move-target' ) {
1703 if ( !$user->isAllowed( 'move' ) ) {
1704 // User can't move anything
1705 $errors[] = array( 'movenotallowed' );
1706 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1707 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1708 // Show user page-specific message only if the user can move other pages
1709 $errors[] = array( 'cant-move-to-user-page' );
1711 } elseif ( !$user->isAllowed( $action ) ) {
1712 $errors[] = $this->missingPermissionError( $action, $short );
1719 * Add the resulting error code to the errors array
1721 * @param $errors Array list of current errors
1722 * @param $result Mixed result of errors
1724 * @return Array list of errors
1726 private function resultToError( $errors, $result ) {
1727 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1728 // A single array representing an error
1729 $errors[] = $result;
1730 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1731 // A nested array representing multiple errors
1732 $errors = array_merge( $errors, $result );
1733 } elseif ( $result !== '' && is_string( $result ) ) {
1734 // A string representing a message-id
1735 $errors[] = array( $result );
1736 } elseif ( $result === false ) {
1737 // a generic "We don't want them to do that"
1738 $errors[] = array( 'badaccess-group0' );
1744 * Check various permission hooks
1746 * @param $action String the action to check
1747 * @param $user User user to check
1748 * @param $errors Array list of current errors
1749 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1750 * @param $short Boolean short circuit on first error
1752 * @return Array list of errors
1754 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1755 // Use getUserPermissionsErrors instead
1757 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1758 return $result ?
array() : array( array( 'badaccess-group0' ) );
1760 // Check getUserPermissionsErrors hook
1761 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1762 $errors = $this->resultToError( $errors, $result );
1764 // Check getUserPermissionsErrorsExpensive hook
1765 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1766 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1767 $errors = $this->resultToError( $errors, $result );
1774 * Check permissions on special pages & namespaces
1776 * @param $action String the action to check
1777 * @param $user User user to check
1778 * @param $errors Array list of current errors
1779 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1780 * @param $short Boolean short circuit on first error
1782 * @return Array list of errors
1784 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1785 # Only 'createaccount' and 'execute' can be performed on
1786 # special pages, which don't actually exist in the DB.
1787 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1788 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1789 $errors[] = array( 'ns-specialprotected' );
1792 # Check $wgNamespaceProtection for restricted namespaces
1793 if ( $this->isNamespaceProtected( $user ) ) {
1794 $ns = $this->mNamespace
== NS_MAIN ?
1795 wfMsg( 'nstab-main' ) : $this->getNsText();
1796 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1797 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1804 * Check CSS/JS sub-page permissions
1806 * @param $action String the action to check
1807 * @param $user User user to check
1808 * @param $errors Array list of current errors
1809 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1810 * @param $short Boolean short circuit on first error
1812 * @return Array list of errors
1814 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1815 # Protect css/js subpages of user pages
1816 # XXX: this might be better using restrictions
1817 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1818 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1819 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1820 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1821 $errors[] = array( 'customcssprotected' );
1822 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1823 $errors[] = array( 'customjsprotected' );
1831 * Check against page_restrictions table requirements on this
1832 * page. The user must possess all required rights for this
1835 * @param $action String the action to check
1836 * @param $user User user to check
1837 * @param $errors Array list of current errors
1838 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1839 * @param $short Boolean short circuit on first error
1841 * @return Array list of errors
1843 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1844 foreach ( $this->getRestrictions( $action ) as $right ) {
1845 // Backwards compatibility, rewrite sysop -> protect
1846 if ( $right == 'sysop' ) {
1849 if ( $right != '' && !$user->isAllowed( $right ) ) {
1850 // Users with 'editprotected' permission can edit protected pages
1851 // without cascading option turned on.
1852 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1853 ||
$this->mCascadeRestriction
)
1855 $errors[] = array( 'protectedpagetext', $right );
1864 * Check restrictions on cascading pages.
1866 * @param $action String the action to check
1867 * @param $user User to check
1868 * @param $errors Array list of current errors
1869 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1870 * @param $short Boolean short circuit on first error
1872 * @return Array list of errors
1874 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1875 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1876 # We /could/ use the protection level on the source page, but it's
1877 # fairly ugly as we have to establish a precedence hierarchy for pages
1878 # included by multiple cascade-protected pages. So just restrict
1879 # it to people with 'protect' permission, as they could remove the
1880 # protection anyway.
1881 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1882 # Cascading protection depends on more than this page...
1883 # Several cascading protected pages may include this page...
1884 # Check each cascading level
1885 # This is only for protection restrictions, not for all actions
1886 if ( isset( $restrictions[$action] ) ) {
1887 foreach ( $restrictions[$action] as $right ) {
1888 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1889 if ( $right != '' && !$user->isAllowed( $right ) ) {
1891 foreach ( $cascadingSources as $page )
1892 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1893 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1903 * Check action permissions not already checked in checkQuickPermissions
1905 * @param $action String the action to check
1906 * @param $user User to check
1907 * @param $errors Array list of current errors
1908 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1909 * @param $short Boolean short circuit on first error
1911 * @return Array list of errors
1913 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1914 global $wgDeleteRevisionsLimit, $wgLang;
1916 if ( $action == 'protect' ) {
1917 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1918 // If they can't edit, they shouldn't protect.
1919 $errors[] = array( 'protect-cantedit' );
1921 } elseif ( $action == 'create' ) {
1922 $title_protection = $this->getTitleProtection();
1923 if( $title_protection ) {
1924 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1925 $title_protection['pt_create_perm'] = 'protect'; // B/C
1927 if( $title_protection['pt_create_perm'] == '' ||
1928 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1930 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1933 } elseif ( $action == 'move' ) {
1934 // Check for immobile pages
1935 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1936 // Specific message for this case
1937 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1938 } elseif ( !$this->isMovable() ) {
1939 // Less specific message for rarer cases
1940 $errors[] = array( 'immobile-source-page' );
1942 } elseif ( $action == 'move-target' ) {
1943 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1944 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1945 } elseif ( !$this->isMovable() ) {
1946 $errors[] = array( 'immobile-target-page' );
1948 } elseif ( $action == 'delete' ) {
1949 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1950 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1952 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1959 * Check that the user isn't blocked from editting.
1961 * @param $action String the action to check
1962 * @param $user User to check
1963 * @param $errors Array list of current errors
1964 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1965 * @param $short Boolean short circuit on first error
1967 * @return Array list of errors
1969 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1970 // Account creation blocks handled at userlogin.
1971 // Unblocking handled in SpecialUnblock
1972 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1976 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1978 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1979 $errors[] = array( 'confirmedittext' );
1982 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1983 // Don't block the user from editing their own talk page unless they've been
1984 // explicitly blocked from that too.
1985 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1986 $block = $user->getBlock();
1988 // This is from OutputPage::blockedPage
1989 // Copied at r23888 by werdna
1991 $id = $user->blockedBy();
1992 $reason = $user->blockedFor();
1993 if ( $reason == '' ) {
1994 $reason = wfMsg( 'blockednoreason' );
1996 $ip = $user->getRequest()->getIP();
1998 if ( is_numeric( $id ) ) {
1999 $name = User
::whoIs( $id );
2004 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
2005 $blockid = $block->getId();
2006 $blockExpiry = $block->getExpiry();
2007 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
2008 if ( $blockExpiry == 'infinity' ) {
2009 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2011 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2014 $intended = strval( $block->getTarget() );
2016 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2017 $blockid, $blockExpiry, $intended, $blockTimestamp );
2024 * Check that the user is allowed to read this page.
2026 * @param $action String the action to check
2027 * @param $user User to check
2028 * @param $errors Array list of current errors
2029 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2030 * @param $short Boolean short circuit on first error
2032 * @return Array list of errors
2034 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2035 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2036 static $useShortcut = null;
2038 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2039 if ( is_null( $useShortcut ) ) {
2040 $useShortcut = true;
2041 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2042 # Not a public wiki, so no shortcut
2043 $useShortcut = false;
2044 } elseif ( !empty( $wgRevokePermissions ) ) {
2046 * Iterate through each group with permissions being revoked (key not included since we don't care
2047 * what the group name is), then check if the read permission is being revoked. If it is, then
2048 * we don't use the shortcut below since the user might not be able to read, even though anon
2049 * reading is allowed.
2051 foreach ( $wgRevokePermissions as $perms ) {
2052 if ( !empty( $perms['read'] ) ) {
2053 # We might be removing the read right from the user, so no shortcut
2054 $useShortcut = false;
2061 $whitelisted = false;
2062 if ( $useShortcut ) {
2063 # Shortcut for public wikis, allows skipping quite a bit of code
2064 $whitelisted = true;
2065 } elseif ( $user->isAllowed( 'read' ) ) {
2066 # If the user is allowed to read pages, he is allowed to read all pages
2067 $whitelisted = true;
2068 } elseif ( $this->isSpecial( 'Userlogin' )
2069 ||
$this->isSpecial( 'ChangePassword' )
2070 ||
$this->isSpecial( 'PasswordReset' )
2072 # Always grant access to the login page.
2073 # Even anons need to be able to log in.
2074 $whitelisted = true;
2075 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2076 # Time to check the whitelist
2077 # Only do these checks is there's something to check against
2078 $name = $this->getPrefixedText();
2079 $dbName = $this->getPrefixedDBKey();
2081 // Check for explicit whitelisting with and without underscores
2082 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2083 $whitelisted = true;
2084 } elseif ( $this->getNamespace() == NS_MAIN
) {
2085 # Old settings might have the title prefixed with
2086 # a colon for main-namespace pages
2087 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2088 $whitelisted = true;
2090 } elseif ( $this->isSpecialPage() ) {
2091 # If it's a special page, ditch the subpage bit and check again
2092 $name = $this->getDBkey();
2093 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2094 if ( $name !== false ) {
2095 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2096 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2097 $whitelisted = true;
2103 if ( !$whitelisted ) {
2104 # If the title is not whitelisted, give extensions a chance to do so...
2105 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2106 if ( !$whitelisted ) {
2107 $errors[] = $this->missingPermissionError( $action, $short );
2115 * Get a description array when the user doesn't have the right to perform
2116 * $action (i.e. when User::isAllowed() returns false)
2118 * @param $action String the action to check
2119 * @param $short Boolean short circuit on first error
2120 * @return Array list of errors
2122 private function missingPermissionError( $action, $short ) {
2123 // We avoid expensive display logic for quickUserCan's and such
2125 return array( 'badaccess-group0' );
2128 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2129 User
::getGroupsWithPermission( $action ) );
2131 if ( count( $groups ) ) {
2135 $wgLang->commaList( $groups ),
2139 return array( 'badaccess-group0' );
2144 * Can $user perform $action on this page? This is an internal function,
2145 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2146 * checks on wfReadOnly() and blocks)
2148 * @param $action String action that permission needs to be checked for
2149 * @param $user User to check
2150 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2151 * @param $short Bool Set this to true to stop after the first permission error.
2152 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2154 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2155 wfProfileIn( __METHOD__
);
2157 # Read has special handling
2158 if ( $action == 'read' ) {
2160 'checkPermissionHooks',
2161 'checkReadPermissions',
2165 'checkQuickPermissions',
2166 'checkPermissionHooks',
2167 'checkSpecialsAndNSPermissions',
2168 'checkCSSandJSPermissions',
2169 'checkPageRestrictions',
2170 'checkCascadingSourcesRestrictions',
2171 'checkActionPermissions',
2177 while( count( $checks ) > 0 &&
2178 !( $short && count( $errors ) > 0 ) ) {
2179 $method = array_shift( $checks );
2180 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2183 wfProfileOut( __METHOD__
);
2188 * Protect css subpages of user pages: can $wgUser edit
2191 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2194 public function userCanEditCssSubpage() {
2196 wfDeprecated( __METHOD__
, '1.19' );
2197 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2198 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2202 * Protect js subpages of user pages: can $wgUser edit
2205 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2208 public function userCanEditJsSubpage() {
2210 wfDeprecated( __METHOD__
, '1.19' );
2211 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2212 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2216 * Get a filtered list of all restriction types supported by this wiki.
2217 * @param bool $exists True to get all restriction types that apply to
2218 * titles that do exist, False for all restriction types that apply to
2219 * titles that do not exist
2222 public static function getFilteredRestrictionTypes( $exists = true ) {
2223 global $wgRestrictionTypes;
2224 $types = $wgRestrictionTypes;
2226 # Remove the create restriction for existing titles
2227 $types = array_diff( $types, array( 'create' ) );
2229 # Only the create and upload restrictions apply to non-existing titles
2230 $types = array_intersect( $types, array( 'create', 'upload' ) );
2236 * Returns restriction types for the current Title
2238 * @return array applicable restriction types
2240 public function getRestrictionTypes() {
2241 if ( $this->isSpecialPage() ) {
2245 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2247 if ( $this->getNamespace() != NS_FILE
) {
2248 # Remove the upload restriction for non-file titles
2249 $types = array_diff( $types, array( 'upload' ) );
2252 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2254 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2255 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2261 * Is this title subject to title protection?
2262 * Title protection is the one applied against creation of such title.
2264 * @return Mixed An associative array representing any existent title
2265 * protection, or false if there's none.
2267 private function getTitleProtection() {
2268 // Can't protect pages in special namespaces
2269 if ( $this->getNamespace() < 0 ) {
2273 // Can't protect pages that exist.
2274 if ( $this->exists() ) {
2278 if ( !isset( $this->mTitleProtection
) ) {
2279 $dbr = wfGetDB( DB_SLAVE
);
2280 $res = $dbr->select( 'protected_titles', '*',
2281 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2284 // fetchRow returns false if there are no rows.
2285 $this->mTitleProtection
= $dbr->fetchRow( $res );
2287 return $this->mTitleProtection
;
2291 * Update the title protection status
2293 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2294 * @param $create_perm String Permission required for creation
2295 * @param $reason String Reason for protection
2296 * @param $expiry String Expiry timestamp
2297 * @return boolean true
2299 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2300 wfDeprecated( __METHOD__
, '1.19' );
2304 $limit = array( 'create' => $create_perm );
2305 $expiry = array( 'create' => $expiry );
2307 $page = WikiPage
::factory( $this );
2308 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2310 return $status->isOK();
2314 * Remove any title protection due to page existing
2316 public function deleteTitleProtection() {
2317 $dbw = wfGetDB( DB_MASTER
);
2321 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2324 $this->mTitleProtection
= false;
2328 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2330 * @param $action String Action to check (default: edit)
2333 public function isSemiProtected( $action = 'edit' ) {
2334 if ( $this->exists() ) {
2335 $restrictions = $this->getRestrictions( $action );
2336 if ( count( $restrictions ) > 0 ) {
2337 foreach ( $restrictions as $restriction ) {
2338 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2348 # If it doesn't exist, it can't be protected
2354 * Does the title correspond to a protected article?
2356 * @param $action String the action the page is protected from,
2357 * by default checks all actions.
2360 public function isProtected( $action = '' ) {
2361 global $wgRestrictionLevels;
2363 $restrictionTypes = $this->getRestrictionTypes();
2365 # Special pages have inherent protection
2366 if( $this->isSpecialPage() ) {
2370 # Check regular protection levels
2371 foreach ( $restrictionTypes as $type ) {
2372 if ( $action == $type ||
$action == '' ) {
2373 $r = $this->getRestrictions( $type );
2374 foreach ( $wgRestrictionLevels as $level ) {
2375 if ( in_array( $level, $r ) && $level != '' ) {
2386 * Determines if $user is unable to edit this page because it has been protected
2387 * by $wgNamespaceProtection.
2389 * @param $user User object to check permissions
2392 public function isNamespaceProtected( User
$user ) {
2393 global $wgNamespaceProtection;
2395 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2396 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2397 if ( $right != '' && !$user->isAllowed( $right ) ) {
2406 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2408 * @return Bool If the page is subject to cascading restrictions.
2410 public function isCascadeProtected() {
2411 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2412 return ( $sources > 0 );
2416 * Cascading protection: Get the source of any cascading restrictions on this page.
2418 * @param $getPages Bool Whether or not to retrieve the actual pages
2419 * that the restrictions have come from.
2420 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2421 * have come, false for none, or true if such restrictions exist, but $getPages
2422 * was not set. The restriction array is an array of each type, each of which
2423 * contains a array of unique groups.
2425 public function getCascadeProtectionSources( $getPages = true ) {
2427 $pagerestrictions = array();
2429 if ( isset( $this->mCascadeSources
) && $getPages ) {
2430 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2431 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2432 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2435 wfProfileIn( __METHOD__
);
2437 $dbr = wfGetDB( DB_SLAVE
);
2439 if ( $this->getNamespace() == NS_FILE
) {
2440 $tables = array( 'imagelinks', 'page_restrictions' );
2441 $where_clauses = array(
2442 'il_to' => $this->getDBkey(),
2447 $tables = array( 'templatelinks', 'page_restrictions' );
2448 $where_clauses = array(
2449 'tl_namespace' => $this->getNamespace(),
2450 'tl_title' => $this->getDBkey(),
2457 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2458 'pr_expiry', 'pr_type', 'pr_level' );
2459 $where_clauses[] = 'page_id=pr_page';
2462 $cols = array( 'pr_expiry' );
2465 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2467 $sources = $getPages ?
array() : false;
2468 $now = wfTimestampNow();
2469 $purgeExpired = false;
2471 foreach ( $res as $row ) {
2472 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2473 if ( $expiry > $now ) {
2475 $page_id = $row->pr_page
;
2476 $page_ns = $row->page_namespace
;
2477 $page_title = $row->page_title
;
2478 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2479 # Add groups needed for each restriction type if its not already there
2480 # Make sure this restriction type still exists
2482 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2483 $pagerestrictions[$row->pr_type
] = array();
2486 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2487 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2488 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2494 // Trigger lazy purge of expired restrictions from the db
2495 $purgeExpired = true;
2498 if ( $purgeExpired ) {
2499 Title
::purgeExpiredRestrictions();
2503 $this->mCascadeSources
= $sources;
2504 $this->mCascadingRestrictions
= $pagerestrictions;
2506 $this->mHasCascadingRestrictions
= $sources;
2509 wfProfileOut( __METHOD__
);
2510 return array( $sources, $pagerestrictions );
2514 * Accessor/initialisation for mRestrictions
2516 * @param $action String action that permission needs to be checked for
2517 * @return Array of Strings the array of groups allowed to edit this article
2519 public function getRestrictions( $action ) {
2520 if ( !$this->mRestrictionsLoaded
) {
2521 $this->loadRestrictions();
2523 return isset( $this->mRestrictions
[$action] )
2524 ?
$this->mRestrictions
[$action]
2529 * Get the expiry time for the restriction against a given action
2532 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2533 * or not protected at all, or false if the action is not recognised.
2535 public function getRestrictionExpiry( $action ) {
2536 if ( !$this->mRestrictionsLoaded
) {
2537 $this->loadRestrictions();
2539 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2543 * Returns cascading restrictions for the current article
2547 function areRestrictionsCascading() {
2548 if ( !$this->mRestrictionsLoaded
) {
2549 $this->loadRestrictions();
2552 return $this->mCascadeRestriction
;
2556 * Loads a string into mRestrictions array
2558 * @param $res Resource restrictions as an SQL result.
2559 * @param $oldFashionedRestrictions String comma-separated list of page
2560 * restrictions from page table (pre 1.10)
2562 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2565 foreach ( $res as $row ) {
2569 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2573 * Compiles list of active page restrictions from both page table (pre 1.10)
2574 * and page_restrictions table for this existing page.
2575 * Public for usage by LiquidThreads.
2577 * @param $rows array of db result objects
2578 * @param $oldFashionedRestrictions string comma-separated list of page
2579 * restrictions from page table (pre 1.10)
2581 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2583 $dbr = wfGetDB( DB_SLAVE
);
2585 $restrictionTypes = $this->getRestrictionTypes();
2587 foreach ( $restrictionTypes as $type ) {
2588 $this->mRestrictions
[$type] = array();
2589 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2592 $this->mCascadeRestriction
= false;
2594 # Backwards-compatibility: also load the restrictions from the page record (old format).
2596 if ( $oldFashionedRestrictions === null ) {
2597 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2598 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2601 if ( $oldFashionedRestrictions != '' ) {
2603 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2604 $temp = explode( '=', trim( $restrict ) );
2605 if ( count( $temp ) == 1 ) {
2606 // old old format should be treated as edit/move restriction
2607 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2608 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2610 $restriction = trim( $temp[1] );
2611 if( $restriction != '' ) { //some old entries are empty
2612 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2617 $this->mOldRestrictions
= true;
2621 if ( count( $rows ) ) {
2622 # Current system - load second to make them override.
2623 $now = wfTimestampNow();
2624 $purgeExpired = false;
2626 # Cycle through all the restrictions.
2627 foreach ( $rows as $row ) {
2629 // Don't take care of restrictions types that aren't allowed
2630 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2633 // This code should be refactored, now that it's being used more generally,
2634 // But I don't really see any harm in leaving it in Block for now -werdna
2635 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2637 // Only apply the restrictions if they haven't expired!
2638 if ( !$expiry ||
$expiry > $now ) {
2639 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2640 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2642 $this->mCascadeRestriction |
= $row->pr_cascade
;
2644 // Trigger a lazy purge of expired restrictions
2645 $purgeExpired = true;
2649 if ( $purgeExpired ) {
2650 Title
::purgeExpiredRestrictions();
2654 $this->mRestrictionsLoaded
= true;
2658 * Load restrictions from the page_restrictions table
2660 * @param $oldFashionedRestrictions String comma-separated list of page
2661 * restrictions from page table (pre 1.10)
2663 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2665 if ( !$this->mRestrictionsLoaded
) {
2666 if ( $this->exists() ) {
2667 $dbr = wfGetDB( DB_SLAVE
);
2669 $res = $dbr->select(
2670 'page_restrictions',
2672 array( 'pr_page' => $this->getArticleID() ),
2676 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2678 $title_protection = $this->getTitleProtection();
2680 if ( $title_protection ) {
2681 $now = wfTimestampNow();
2682 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2684 if ( !$expiry ||
$expiry > $now ) {
2685 // Apply the restrictions
2686 $this->mRestrictionsExpiry
['create'] = $expiry;
2687 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2688 } else { // Get rid of the old restrictions
2689 Title
::purgeExpiredRestrictions();
2690 $this->mTitleProtection
= false;
2693 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2695 $this->mRestrictionsLoaded
= true;
2701 * Flush the protection cache in this object and force reload from the database.
2702 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2704 public function flushRestrictions() {
2705 $this->mRestrictionsLoaded
= false;
2706 $this->mTitleProtection
= null;
2710 * Purge expired restrictions from the page_restrictions table
2712 static function purgeExpiredRestrictions() {
2713 $dbw = wfGetDB( DB_MASTER
);
2715 'page_restrictions',
2716 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2722 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2728 * Does this have subpages? (Warning, usually requires an extra DB query.)
2732 public function hasSubpages() {
2733 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2738 # We dynamically add a member variable for the purpose of this method
2739 # alone to cache the result. There's no point in having it hanging
2740 # around uninitialized in every Title object; therefore we only add it
2741 # if needed and don't declare it statically.
2742 if ( isset( $this->mHasSubpages
) ) {
2743 return $this->mHasSubpages
;
2746 $subpages = $this->getSubpages( 1 );
2747 if ( $subpages instanceof TitleArray
) {
2748 return $this->mHasSubpages
= (bool)$subpages->count();
2750 return $this->mHasSubpages
= false;
2754 * Get all subpages of this page.
2756 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2757 * @return mixed TitleArray, or empty array if this page's namespace
2758 * doesn't allow subpages
2760 public function getSubpages( $limit = -1 ) {
2761 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2765 $dbr = wfGetDB( DB_SLAVE
);
2766 $conds['page_namespace'] = $this->getNamespace();
2767 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2769 if ( $limit > -1 ) {
2770 $options['LIMIT'] = $limit;
2772 return $this->mSubpages
= TitleArray
::newFromResult(
2773 $dbr->select( 'page',
2774 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2783 * Is there a version of this page in the deletion archive?
2785 * @return Int the number of archived revisions
2787 public function isDeleted() {
2788 if ( $this->getNamespace() < 0 ) {
2791 $dbr = wfGetDB( DB_SLAVE
);
2793 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2794 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2797 if ( $this->getNamespace() == NS_FILE
) {
2798 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2799 array( 'fa_name' => $this->getDBkey() ),
2808 * Is there a version of this page in the deletion archive?
2812 public function isDeletedQuick() {
2813 if ( $this->getNamespace() < 0 ) {
2816 $dbr = wfGetDB( DB_SLAVE
);
2817 $deleted = (bool)$dbr->selectField( 'archive', '1',
2818 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2821 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2822 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2823 array( 'fa_name' => $this->getDBkey() ),
2831 * Get the article ID for this Title from the link cache,
2832 * adding it if necessary
2834 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2836 * @return Int the ID
2838 public function getArticleID( $flags = 0 ) {
2839 if ( $this->getNamespace() < 0 ) {
2840 return $this->mArticleID
= 0;
2842 $linkCache = LinkCache
::singleton();
2843 if ( $flags & self
::GAID_FOR_UPDATE
) {
2844 $oldUpdate = $linkCache->forUpdate( true );
2845 $linkCache->clearLink( $this );
2846 $this->mArticleID
= $linkCache->addLinkObj( $this );
2847 $linkCache->forUpdate( $oldUpdate );
2849 if ( -1 == $this->mArticleID
) {
2850 $this->mArticleID
= $linkCache->addLinkObj( $this );
2853 return $this->mArticleID
;
2857 * Is this an article that is a redirect page?
2858 * Uses link cache, adding it if necessary
2860 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2863 public function isRedirect( $flags = 0 ) {
2864 if ( !is_null( $this->mRedirect
) ) {
2865 return $this->mRedirect
;
2867 # Calling getArticleID() loads the field from cache as needed
2868 if ( !$this->getArticleID( $flags ) ) {
2869 return $this->mRedirect
= false;
2872 $linkCache = LinkCache
::singleton();
2873 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2874 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title
2876 $this->mRedirect
= (bool)$cached;
2878 return $this->mRedirect
;
2882 * What is the length of this page?
2883 * Uses link cache, adding it if necessary
2885 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2888 public function getLength( $flags = 0 ) {
2889 if ( $this->mLength
!= -1 ) {
2890 return $this->mLength
;
2892 # Calling getArticleID() loads the field from cache as needed
2893 if ( !$this->getArticleID( $flags ) ) {
2894 return $this->mLength
= 0;
2896 $linkCache = LinkCache
::singleton();
2897 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2899 return $this->mLength
;
2903 * What is the page_latest field for this page?
2905 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2906 * @return Int or 0 if the page doesn't exist
2908 public function getLatestRevID( $flags = 0 ) {
2909 if ( $this->mLatestID
!== false ) {
2910 return intval( $this->mLatestID
);
2912 # Calling getArticleID() loads the field from cache as needed
2913 if ( !$this->getArticleID( $flags ) ) {
2914 return $this->mLatestID
= 0;
2916 $linkCache = LinkCache
::singleton();
2917 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2919 return $this->mLatestID
;
2923 * This clears some fields in this object, and clears any associated
2924 * keys in the "bad links" section of the link cache.
2926 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2927 * loading of the new page_id. It's also called from
2928 * WikiPage::doDeleteArticle()
2930 * @param $newid Int the new Article ID
2932 public function resetArticleID( $newid ) {
2933 $linkCache = LinkCache
::singleton();
2934 $linkCache->clearLink( $this );
2936 if ( $newid === false ) {
2937 $this->mArticleID
= -1;
2939 $this->mArticleID
= intval( $newid );
2941 $this->mRestrictionsLoaded
= false;
2942 $this->mRestrictions
= array();
2943 $this->mRedirect
= null;
2944 $this->mLength
= -1;
2945 $this->mLatestID
= false;
2946 $this->mEstimateRevisions
= null;
2950 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2952 * @param $text String containing title to capitalize
2953 * @param $ns int namespace index, defaults to NS_MAIN
2954 * @return String containing capitalized title
2956 public static function capitalize( $text, $ns = NS_MAIN
) {
2959 if ( MWNamespace
::isCapitalized( $ns ) ) {
2960 return $wgContLang->ucfirst( $text );
2967 * Secure and split - main initialisation function for this object
2969 * Assumes that mDbkeyform has been set, and is urldecoded
2970 * and uses underscores, but not otherwise munged. This function
2971 * removes illegal characters, splits off the interwiki and
2972 * namespace prefixes, sets the other forms, and canonicalizes
2975 * @return Bool true on success
2977 private function secureAndSplit() {
2978 global $wgContLang, $wgLocalInterwiki;
2981 $this->mInterwiki
= $this->mFragment
= '';
2982 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2984 $dbkey = $this->mDbkeyform
;
2986 # Strip Unicode bidi override characters.
2987 # Sometimes they slip into cut-n-pasted page titles, where the
2988 # override chars get included in list displays.
2989 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2991 # Clean up whitespace
2992 # Note: use of the /u option on preg_replace here will cause
2993 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2994 # conveniently disabling them.
2995 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2996 $dbkey = trim( $dbkey, '_' );
2998 if ( $dbkey == '' ) {
3002 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3003 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3007 $this->mDbkeyform
= $dbkey;
3009 # Initial colon indicates main namespace rather than specified default
3010 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3011 if ( ':' == $dbkey[0] ) {
3012 $this->mNamespace
= NS_MAIN
;
3013 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3014 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3017 # Namespace or interwiki prefix
3019 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3022 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3024 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3025 # Ordinary namespace
3027 $this->mNamespace
= $ns;
3028 # For Talk:X pages, check if X has a "namespace" prefix
3029 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3030 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3031 # Disallow Talk:File:x type titles...
3033 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3034 # Disallow Talk:Interwiki:x type titles...
3038 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3039 if ( !$firstPass ) {
3040 # Can't make a local interwiki link to an interwiki link.
3041 # That's just crazy!
3047 $this->mInterwiki
= $wgContLang->lc( $p );
3049 # Redundant interwiki prefix to the local wiki
3050 if ( $wgLocalInterwiki !== false
3051 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3053 if ( $dbkey == '' ) {
3054 # Can't have an empty self-link
3057 $this->mInterwiki
= '';
3059 # Do another namespace split...
3063 # If there's an initial colon after the interwiki, that also
3064 # resets the default namespace
3065 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3066 $this->mNamespace
= NS_MAIN
;
3067 $dbkey = substr( $dbkey, 1 );
3070 # If there's no recognized interwiki or namespace,
3071 # then let the colon expression be part of the title.
3076 # We already know that some pages won't be in the database!
3077 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3078 $this->mArticleID
= 0;
3080 $fragment = strstr( $dbkey, '#' );
3081 if ( false !== $fragment ) {
3082 $this->setFragment( $fragment );
3083 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3084 # remove whitespace again: prevents "Foo_bar_#"
3085 # becoming "Foo_bar_"
3086 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3089 # Reject illegal characters.
3090 $rxTc = self
::getTitleInvalidRegex();
3091 if ( preg_match( $rxTc, $dbkey ) ) {
3095 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3096 # reachable due to the way web browsers deal with 'relative' URLs.
3097 # Also, they conflict with subpage syntax. Forbid them explicitly.
3098 if ( strpos( $dbkey, '.' ) !== false &&
3099 ( $dbkey === '.' ||
$dbkey === '..' ||
3100 strpos( $dbkey, './' ) === 0 ||
3101 strpos( $dbkey, '../' ) === 0 ||
3102 strpos( $dbkey, '/./' ) !== false ||
3103 strpos( $dbkey, '/../' ) !== false ||
3104 substr( $dbkey, -2 ) == '/.' ||
3105 substr( $dbkey, -3 ) == '/..' ) )
3110 # Magic tilde sequences? Nu-uh!
3111 if ( strpos( $dbkey, '~~~' ) !== false ) {
3115 # Limit the size of titles to 255 bytes. This is typically the size of the
3116 # underlying database field. We make an exception for special pages, which
3117 # don't need to be stored in the database, and may edge over 255 bytes due
3118 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3119 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3120 strlen( $dbkey ) > 512 )
3125 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3126 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3127 # other site might be case-sensitive.
3128 $this->mUserCaseDBKey
= $dbkey;
3129 if ( $this->mInterwiki
== '' ) {
3130 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3133 # Can't make a link to a namespace alone... "empty" local links can only be
3134 # self-links with a fragment identifier.
3135 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3139 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3140 // IP names are not allowed for accounts, and can only be referring to
3141 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3142 // there are numerous ways to present the same IP. Having sp:contribs scan
3143 // them all is silly and having some show the edits and others not is
3144 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3145 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3146 ? IP
::sanitizeIP( $dbkey )
3149 // Any remaining initial :s are illegal.
3150 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3155 $this->mDbkeyform
= $dbkey;
3156 $this->mUrlform
= wfUrlencode( $dbkey );
3158 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3164 * Get an array of Title objects linking to this Title
3165 * Also stores the IDs in the link cache.
3167 * WARNING: do not use this function on arbitrary user-supplied titles!
3168 * On heavily-used templates it will max out the memory.
3170 * @param $options Array: may be FOR UPDATE
3171 * @param $table String: table name
3172 * @param $prefix String: fields prefix
3173 * @return Array of Title objects linking here
3175 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3176 if ( count( $options ) > 0 ) {
3177 $db = wfGetDB( DB_MASTER
);
3179 $db = wfGetDB( DB_SLAVE
);
3183 array( 'page', $table ),
3184 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3186 "{$prefix}_from=page_id",
3187 "{$prefix}_namespace" => $this->getNamespace(),
3188 "{$prefix}_title" => $this->getDBkey() ),
3194 if ( $res->numRows() ) {
3195 $linkCache = LinkCache
::singleton();
3196 foreach ( $res as $row ) {
3197 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3199 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3200 $retVal[] = $titleObj;
3208 * Get an array of Title objects using this Title as a template
3209 * Also stores the IDs in the link cache.
3211 * WARNING: do not use this function on arbitrary user-supplied titles!
3212 * On heavily-used templates it will max out the memory.
3214 * @param $options Array: may be FOR UPDATE
3215 * @return Array of Title the Title objects linking here
3217 public function getTemplateLinksTo( $options = array() ) {
3218 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3222 * Get an array of Title objects linked from this Title
3223 * Also stores the IDs in the link cache.
3225 * WARNING: do not use this function on arbitrary user-supplied titles!
3226 * On heavily-used templates it will max out the memory.
3228 * @param $options Array: may be FOR UPDATE
3229 * @param $table String: table name
3230 * @param $prefix String: fields prefix
3231 * @return Array of Title objects linking here
3233 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3234 $id = $this->getArticleID();
3236 # If the page doesn't exist; there can't be any link from this page
3241 if ( count( $options ) > 0 ) {
3242 $db = wfGetDB( DB_MASTER
);
3244 $db = wfGetDB( DB_SLAVE
);
3247 $namespaceFiled = "{$prefix}_namespace";
3248 $titleField = "{$prefix}_title";
3251 array( $table, 'page' ),
3252 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3253 array( "{$prefix}_from" => $id ),
3256 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3260 if ( $res->numRows() ) {
3261 $linkCache = LinkCache
::singleton();
3262 foreach ( $res as $row ) {
3263 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3265 if ( $row->page_id
) {
3266 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3268 $linkCache->addBadLinkObj( $titleObj );
3270 $retVal[] = $titleObj;
3278 * Get an array of Title objects used on this Title as a template
3279 * Also stores the IDs in the link cache.
3281 * WARNING: do not use this function on arbitrary user-supplied titles!
3282 * On heavily-used templates it will max out the memory.
3284 * @param $options Array: may be FOR UPDATE
3285 * @return Array of Title the Title objects used here
3287 public function getTemplateLinksFrom( $options = array() ) {
3288 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3292 * Get an array of Title objects referring to non-existent articles linked from this page
3294 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3295 * @return Array of Title the Title objects
3297 public function getBrokenLinksFrom() {
3298 if ( $this->getArticleID() == 0 ) {
3299 # All links from article ID 0 are false positives
3303 $dbr = wfGetDB( DB_SLAVE
);
3304 $res = $dbr->select(
3305 array( 'page', 'pagelinks' ),
3306 array( 'pl_namespace', 'pl_title' ),
3308 'pl_from' => $this->getArticleID(),
3309 'page_namespace IS NULL'
3311 __METHOD__
, array(),
3315 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3321 foreach ( $res as $row ) {
3322 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3329 * Get a list of URLs to purge from the Squid cache when this
3332 * @return Array of String the URLs
3334 public function getSquidURLs() {
3338 $this->getInternalURL(),
3339 $this->getInternalURL( 'action=history' )
3342 // purge variant urls as well
3343 if ( $wgContLang->hasVariants() ) {
3344 $variants = $wgContLang->getVariants();
3345 foreach ( $variants as $vCode ) {
3346 $urls[] = $this->getInternalURL( '', $vCode );
3354 * Purge all applicable Squid URLs
3356 public function purgeSquid() {
3358 if ( $wgUseSquid ) {
3359 $urls = $this->getSquidURLs();
3360 $u = new SquidUpdate( $urls );
3366 * Move this page without authentication
3368 * @param $nt Title the new page Title
3369 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3371 public function moveNoAuth( &$nt ) {
3372 return $this->moveTo( $nt, false );
3376 * Check whether a given move operation would be valid.
3377 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3379 * @param $nt Title the new title
3380 * @param $auth Bool indicates whether $wgUser's permissions
3382 * @param $reason String is the log summary of the move, used for spam checking
3383 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3385 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3390 // Normally we'd add this to $errors, but we'll get
3391 // lots of syntax errors if $nt is not an object
3392 return array( array( 'badtitletext' ) );
3394 if ( $this->equals( $nt ) ) {
3395 $errors[] = array( 'selfmove' );
3397 if ( !$this->isMovable() ) {
3398 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3400 if ( $nt->getInterwiki() != '' ) {
3401 $errors[] = array( 'immobile-target-namespace-iw' );
3403 if ( !$nt->isMovable() ) {
3404 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3407 $oldid = $this->getArticleID();
3408 $newid = $nt->getArticleID();
3410 if ( strlen( $nt->getDBkey() ) < 1 ) {
3411 $errors[] = array( 'articleexists' );
3413 if ( ( $this->getDBkey() == '' ) ||
3415 ( $nt->getDBkey() == '' ) ) {
3416 $errors[] = array( 'badarticleerror' );
3419 // Image-specific checks
3420 if ( $this->getNamespace() == NS_FILE
) {
3421 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3424 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3425 $errors[] = array( 'nonfile-cannot-move-to-file' );
3429 $errors = wfMergeErrorArrays( $errors,
3430 $this->getUserPermissionsErrors( 'move', $wgUser ),
3431 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3432 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3433 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3436 $match = EditPage
::matchSummarySpamRegex( $reason );
3437 if ( $match !== false ) {
3438 // This is kind of lame, won't display nice
3439 $errors[] = array( 'spamprotectiontext' );
3443 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3444 $errors[] = array( 'hookaborted', $err );
3447 # The move is allowed only if (1) the target doesn't exist, or
3448 # (2) the target is a redirect to the source, and has no history
3449 # (so we can undo bad moves right after they're done).
3451 if ( 0 != $newid ) { # Target exists; check for validity
3452 if ( !$this->isValidMoveTarget( $nt ) ) {
3453 $errors[] = array( 'articleexists' );
3456 $tp = $nt->getTitleProtection();
3457 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3458 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3459 $errors[] = array( 'cantmove-titleprotected' );
3462 if ( empty( $errors ) ) {
3469 * Check if the requested move target is a valid file move target
3470 * @param Title $nt Target title
3471 * @return array List of errors
3473 protected function validateFileMoveOperation( $nt ) {
3478 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3480 $file = wfLocalFile( $this );
3481 if ( $file->exists() ) {
3482 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3483 $errors[] = array( 'imageinvalidfilename' );
3485 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3486 $errors[] = array( 'imagetypemismatch' );
3490 if ( $nt->getNamespace() != NS_FILE
) {
3491 $errors[] = array( 'imagenocrossnamespace' );
3492 // From here we want to do checks on a file object, so if we can't
3493 // create one, we must return.
3497 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3499 $destFile = wfLocalFile( $nt );
3500 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3501 $errors[] = array( 'file-exists-sharedrepo' );
3508 * Move a title to a new location
3510 * @param $nt Title the new title
3511 * @param $auth Bool indicates whether $wgUser's permissions
3513 * @param $reason String the reason for the move
3514 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3515 * Ignored if the user doesn't have the suppressredirect right.
3516 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3518 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3520 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3521 if ( is_array( $err ) ) {
3522 // Auto-block user's IP if the account was "hard" blocked
3523 $wgUser->spreadAnyEditBlock();
3527 // If it is a file, move it first.
3528 // It is done before all other moving stuff is done because it's hard to revert.
3529 $dbw = wfGetDB( DB_MASTER
);
3530 if ( $this->getNamespace() == NS_FILE
) {
3531 $file = wfLocalFile( $this );
3532 if ( $file->exists() ) {
3533 $status = $file->move( $nt );
3534 if ( !$status->isOk() ) {
3535 return $status->getErrorsArray();
3538 // Clear RepoGroup process cache
3539 RepoGroup
::singleton()->clearCache( $this );
3540 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3543 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3544 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3545 $protected = $this->isProtected();
3547 // Do the actual move
3548 $this->moveToInternal( $nt, $reason, $createRedirect );
3550 // Refresh the sortkey for this row. Be careful to avoid resetting
3551 // cl_timestamp, which may disturb time-based lists on some sites.
3552 $prefixes = $dbw->select(
3554 array( 'cl_sortkey_prefix', 'cl_to' ),
3555 array( 'cl_from' => $pageid ),
3558 foreach ( $prefixes as $prefixRow ) {
3559 $prefix = $prefixRow->cl_sortkey_prefix
;
3560 $catTo = $prefixRow->cl_to
;
3561 $dbw->update( 'categorylinks',
3563 'cl_sortkey' => Collation
::singleton()->getSortKey(
3564 $nt->getCategorySortkey( $prefix ) ),
3565 'cl_timestamp=cl_timestamp' ),
3567 'cl_from' => $pageid,
3568 'cl_to' => $catTo ),
3573 $redirid = $this->getArticleID();
3576 # Protect the redirect title as the title used to be...
3577 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3579 'pr_page' => $redirid,
3580 'pr_type' => 'pr_type',
3581 'pr_level' => 'pr_level',
3582 'pr_cascade' => 'pr_cascade',
3583 'pr_user' => 'pr_user',
3584 'pr_expiry' => 'pr_expiry'
3586 array( 'pr_page' => $pageid ),
3590 # Update the protection log
3591 $log = new LogPage( 'protect' );
3592 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3594 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3596 // @todo FIXME: $params?
3597 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3601 $oldnamespace = $this->getNamespace() & ~
1;
3602 $newnamespace = $nt->getNamespace() & ~
1;
3603 $oldtitle = $this->getDBkey();
3604 $newtitle = $nt->getDBkey();
3606 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3607 WatchedItem
::duplicateEntries( $this, $nt );
3610 $dbw->commit( __METHOD__
);
3612 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3617 * Move page to a title which is either a redirect to the
3618 * source page or nonexistent
3620 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3621 * @param $reason String The reason for the move
3622 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3623 * if the user doesn't have the suppressredirect right
3624 * @throws MWException
3626 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3627 global $wgUser, $wgContLang;
3629 if ( $nt->exists() ) {
3630 $moveOverRedirect = true;
3631 $logType = 'move_redir';
3633 $moveOverRedirect = false;
3637 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3639 $logEntry = new ManualLogEntry( 'move', $logType );
3640 $logEntry->setPerformer( $wgUser );
3641 $logEntry->setTarget( $this );
3642 $logEntry->setComment( $reason );
3643 $logEntry->setParameters( array(
3644 '4::target' => $nt->getPrefixedText(),
3645 '5::noredir' => $redirectSuppressed ?
'1': '0',
3648 $formatter = LogFormatter
::newFromEntry( $logEntry );
3649 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3650 $comment = $formatter->getPlainActionText();
3652 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3654 # Truncate for whole multibyte characters.
3655 $comment = $wgContLang->truncate( $comment, 255 );
3657 $oldid = $this->getArticleID();
3659 $dbw = wfGetDB( DB_MASTER
);
3661 $newpage = WikiPage
::factory( $nt );
3663 if ( $moveOverRedirect ) {
3664 $newid = $nt->getArticleID();
3666 # Delete the old redirect. We don't save it to history since
3667 # by definition if we've got here it's rather uninteresting.
3668 # We have to remove it so that the next step doesn't trigger
3669 # a conflict on the unique namespace+title index...
3670 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3672 $newpage->doDeleteUpdates( $newid );
3675 # Save a null revision in the page's history notifying of the move
3676 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3677 if ( !is_object( $nullRevision ) ) {
3678 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3680 $nullRevId = $nullRevision->insertOn( $dbw );
3682 # Change the name of the target page:
3683 $dbw->update( 'page',
3685 'page_namespace' => $nt->getNamespace(),
3686 'page_title' => $nt->getDBkey(),
3688 /* WHERE */ array( 'page_id' => $oldid ),
3692 $this->resetArticleID( 0 );
3693 $nt->resetArticleID( $oldid );
3695 $newpage->updateRevisionOn( $dbw, $nullRevision );
3697 wfRunHooks( 'NewRevisionFromEditComplete',
3698 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3700 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3702 if ( !$moveOverRedirect ) {
3703 WikiPage
::onArticleCreate( $nt );
3706 # Recreate the redirect, this time in the other direction.
3707 if ( $redirectSuppressed ) {
3708 WikiPage
::onArticleDelete( $this );
3710 $mwRedir = MagicWord
::get( 'redirect' );
3711 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3712 $redirectArticle = WikiPage
::factory( $this );
3713 $newid = $redirectArticle->insertOn( $dbw );
3714 if ( $newid ) { // sanity
3715 $redirectRevision = new Revision( array(
3717 'comment' => $comment,
3718 'text' => $redirectText ) );
3719 $redirectRevision->insertOn( $dbw );
3720 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3722 wfRunHooks( 'NewRevisionFromEditComplete',
3723 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3725 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3730 $logid = $logEntry->insert();
3731 $logEntry->publish( $logid );
3735 * Move this page's subpages to be subpages of $nt
3737 * @param $nt Title Move target
3738 * @param $auth bool Whether $wgUser's permissions should be checked
3739 * @param $reason string The reason for the move
3740 * @param $createRedirect bool Whether to create redirects from the old subpages to
3741 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3742 * @return mixed array with old page titles as keys, and strings (new page titles) or
3743 * arrays (errors) as values, or an error array with numeric indices if no pages
3746 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3747 global $wgMaximumMovedPages;
3748 // Check permissions
3749 if ( !$this->userCan( 'move-subpages' ) ) {
3750 return array( 'cant-move-subpages' );
3752 // Do the source and target namespaces support subpages?
3753 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3754 return array( 'namespace-nosubpages',
3755 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3757 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3758 return array( 'namespace-nosubpages',
3759 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3762 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3765 foreach ( $subpages as $oldSubpage ) {
3767 if ( $count > $wgMaximumMovedPages ) {
3768 $retval[$oldSubpage->getPrefixedTitle()] =
3769 array( 'movepage-max-pages',
3770 $wgMaximumMovedPages );
3774 // We don't know whether this function was called before
3775 // or after moving the root page, so check both
3777 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3778 $oldSubpage->getArticleID() == $nt->getArticleID() )
3780 // When moving a page to a subpage of itself,
3781 // don't move it twice
3784 $newPageName = preg_replace(
3785 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3786 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3787 $oldSubpage->getDBkey() );
3788 if ( $oldSubpage->isTalkPage() ) {
3789 $newNs = $nt->getTalkPage()->getNamespace();
3791 $newNs = $nt->getSubjectPage()->getNamespace();
3793 # Bug 14385: we need makeTitleSafe because the new page names may
3794 # be longer than 255 characters.
3795 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3797 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3798 if ( $success === true ) {
3799 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3801 $retval[$oldSubpage->getPrefixedText()] = $success;
3808 * Checks if this page is just a one-rev redirect.
3809 * Adds lock, so don't use just for light purposes.
3813 public function isSingleRevRedirect() {
3814 $dbw = wfGetDB( DB_MASTER
);
3816 $row = $dbw->selectRow( 'page',
3817 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3820 array( 'FOR UPDATE' )
3822 # Cache some fields we may want
3823 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3824 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3825 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3826 if ( !$this->mRedirect
) {
3829 # Does the article have a history?
3830 $row = $dbw->selectField( array( 'page', 'revision' ),
3832 array( 'page_namespace' => $this->getNamespace(),
3833 'page_title' => $this->getDBkey(),
3835 'page_latest != rev_id'
3838 array( 'FOR UPDATE' )
3840 # Return true if there was no history
3841 return ( $row === false );
3845 * Checks if $this can be moved to a given Title
3846 * - Selects for update, so don't call it unless you mean business
3848 * @param $nt Title the new title to check
3851 public function isValidMoveTarget( $nt ) {
3852 # Is it an existing file?
3853 if ( $nt->getNamespace() == NS_FILE
) {
3854 $file = wfLocalFile( $nt );
3855 if ( $file->exists() ) {
3856 wfDebug( __METHOD__
. ": file exists\n" );
3860 # Is it a redirect with no history?
3861 if ( !$nt->isSingleRevRedirect() ) {
3862 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3865 # Get the article text
3866 $rev = Revision
::newFromTitle( $nt );
3867 if( !is_object( $rev ) ){
3870 $text = $rev->getText();
3871 # Does the redirect point to the source?
3872 # Or is it a broken self-redirect, usually caused by namespace collisions?
3874 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3875 $redirTitle = Title
::newFromText( $m[1] );
3876 if ( !is_object( $redirTitle ) ||
3877 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3878 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3879 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3884 wfDebug( __METHOD__
. ": failsafe\n" );
3891 * Get categories to which this Title belongs and return an array of
3892 * categories' names.
3894 * @return Array of parents in the form:
3895 * $parent => $currentarticle
3897 public function getParentCategories() {
3902 $titleKey = $this->getArticleID();
3904 if ( $titleKey === 0 ) {
3908 $dbr = wfGetDB( DB_SLAVE
);
3910 $res = $dbr->select( 'categorylinks', '*',
3912 'cl_from' => $titleKey,
3918 if ( $dbr->numRows( $res ) > 0 ) {
3919 foreach ( $res as $row ) {
3920 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3921 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3928 * Get a tree of parent categories
3930 * @param $children Array with the children in the keys, to check for circular refs
3931 * @return Array Tree of parent categories
3933 public function getParentCategoryTree( $children = array() ) {
3935 $parents = $this->getParentCategories();
3938 foreach ( $parents as $parent => $current ) {
3939 if ( array_key_exists( $parent, $children ) ) {
3940 # Circular reference
3941 $stack[$parent] = array();
3943 $nt = Title
::newFromText( $parent );
3945 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3955 * Get an associative array for selecting this title from
3958 * @return Array suitable for the $where parameter of DB::select()
3960 public function pageCond() {
3961 if ( $this->mArticleID
> 0 ) {
3962 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3963 return array( 'page_id' => $this->mArticleID
);
3965 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3970 * Get the revision ID of the previous revision
3972 * @param $revId Int Revision ID. Get the revision that was before this one.
3973 * @param $flags Int Title::GAID_FOR_UPDATE
3974 * @return Int|Bool Old revision ID, or FALSE if none exists
3976 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3977 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3978 $revId = $db->selectField( 'revision', 'rev_id',
3980 'rev_page' => $this->getArticleID( $flags ),
3981 'rev_id < ' . intval( $revId )
3984 array( 'ORDER BY' => 'rev_id DESC' )
3987 if ( $revId === false ) {
3990 return intval( $revId );
3995 * Get the revision ID of the next revision
3997 * @param $revId Int Revision ID. Get the revision that was after this one.
3998 * @param $flags Int Title::GAID_FOR_UPDATE
3999 * @return Int|Bool Next revision ID, or FALSE if none exists
4001 public function getNextRevisionID( $revId, $flags = 0 ) {
4002 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4003 $revId = $db->selectField( 'revision', 'rev_id',
4005 'rev_page' => $this->getArticleID( $flags ),
4006 'rev_id > ' . intval( $revId )
4009 array( 'ORDER BY' => 'rev_id' )
4012 if ( $revId === false ) {
4015 return intval( $revId );
4020 * Get the first revision of the page
4022 * @param $flags Int Title::GAID_FOR_UPDATE
4023 * @return Revision|Null if page doesn't exist
4025 public function getFirstRevision( $flags = 0 ) {
4026 $pageId = $this->getArticleID( $flags );
4028 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4029 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4030 array( 'rev_page' => $pageId ),
4032 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4035 return new Revision( $row );
4042 * Get the oldest revision timestamp of this page
4044 * @param $flags Int Title::GAID_FOR_UPDATE
4045 * @return String: MW timestamp
4047 public function getEarliestRevTime( $flags = 0 ) {
4048 $rev = $this->getFirstRevision( $flags );
4049 return $rev ?
$rev->getTimestamp() : null;
4053 * Check if this is a new page
4057 public function isNewPage() {
4058 $dbr = wfGetDB( DB_SLAVE
);
4059 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4063 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4067 public function isBigDeletion() {
4068 global $wgDeleteRevisionsLimit;
4070 if ( !$wgDeleteRevisionsLimit ) {
4074 $revCount = $this->estimateRevisionCount();
4075 return $revCount > $wgDeleteRevisionsLimit;
4079 * Get the approximate revision count of this page.
4083 public function estimateRevisionCount() {
4084 if ( !$this->exists() ) {
4088 if ( $this->mEstimateRevisions
=== null ) {
4089 $dbr = wfGetDB( DB_SLAVE
);
4090 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4091 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4094 return $this->mEstimateRevisions
;
4098 * Get the number of revisions between the given revision.
4099 * Used for diffs and other things that really need it.
4101 * @param $old int|Revision Old revision or rev ID (first before range)
4102 * @param $new int|Revision New revision or rev ID (first after range)
4103 * @return Int Number of revisions between these revisions.
4105 public function countRevisionsBetween( $old, $new ) {
4106 if ( !( $old instanceof Revision
) ) {
4107 $old = Revision
::newFromTitle( $this, (int)$old );
4109 if ( !( $new instanceof Revision
) ) {
4110 $new = Revision
::newFromTitle( $this, (int)$new );
4112 if ( !$old ||
!$new ) {
4113 return 0; // nothing to compare
4115 $dbr = wfGetDB( DB_SLAVE
);
4116 return (int)$dbr->selectField( 'revision', 'count(*)',
4118 'rev_page' => $this->getArticleID(),
4119 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4120 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4127 * Get the number of authors between the given revision IDs.
4128 * Used for diffs and other things that really need it.
4130 * @param $old int|Revision Old revision or rev ID (first before range)
4131 * @param $new int|Revision New revision or rev ID (first after range)
4132 * @param $limit Int Maximum number of authors
4133 * @return Int Number of revision authors between these revisions.
4135 public function countAuthorsBetween( $old, $new, $limit ) {
4136 if ( !( $old instanceof Revision
) ) {
4137 $old = Revision
::newFromTitle( $this, (int)$old );
4139 if ( !( $new instanceof Revision
) ) {
4140 $new = Revision
::newFromTitle( $this, (int)$new );
4142 if ( !$old ||
!$new ) {
4143 return 0; // nothing to compare
4145 $dbr = wfGetDB( DB_SLAVE
);
4146 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4148 'rev_page' => $this->getArticleID(),
4149 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4150 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4152 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4154 return (int)$dbr->numRows( $res );
4158 * Compare with another title.
4160 * @param $title Title
4163 public function equals( Title
$title ) {
4164 // Note: === is necessary for proper matching of number-like titles.
4165 return $this->getInterwiki() === $title->getInterwiki()
4166 && $this->getNamespace() == $title->getNamespace()
4167 && $this->getDBkey() === $title->getDBkey();
4171 * Check if this title is a subpage of another title
4173 * @param $title Title
4176 public function isSubpageOf( Title
$title ) {
4177 return $this->getInterwiki() === $title->getInterwiki()
4178 && $this->getNamespace() == $title->getNamespace()
4179 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4183 * Check if page exists. For historical reasons, this function simply
4184 * checks for the existence of the title in the page table, and will
4185 * thus return false for interwiki links, special pages and the like.
4186 * If you want to know if a title can be meaningfully viewed, you should
4187 * probably call the isKnown() method instead.
4191 public function exists() {
4192 return $this->getArticleID() != 0;
4196 * Should links to this title be shown as potentially viewable (i.e. as
4197 * "bluelinks"), even if there's no record by this title in the page
4200 * This function is semi-deprecated for public use, as well as somewhat
4201 * misleadingly named. You probably just want to call isKnown(), which
4202 * calls this function internally.
4204 * (ISSUE: Most of these checks are cheap, but the file existence check
4205 * can potentially be quite expensive. Including it here fixes a lot of
4206 * existing code, but we might want to add an optional parameter to skip
4207 * it and any other expensive checks.)
4211 public function isAlwaysKnown() {
4215 * Allows overriding default behaviour for determining if a page exists.
4216 * If $isKnown is kept as null, regular checks happen. If it's
4217 * a boolean, this value is returned by the isKnown method.
4221 * @param Title $title
4222 * @param boolean|null $isKnown
4224 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4226 if ( !is_null( $isKnown ) ) {
4230 if ( $this->mInterwiki
!= '' ) {
4231 return true; // any interwiki link might be viewable, for all we know
4234 switch( $this->mNamespace
) {
4237 // file exists, possibly in a foreign repo
4238 return (bool)wfFindFile( $this );
4240 // valid special page
4241 return SpecialPageFactory
::exists( $this->getDBkey() );
4243 // selflink, possibly with fragment
4244 return $this->mDbkeyform
== '';
4246 // known system message
4247 return $this->hasSourceText() !== false;
4254 * Does this title refer to a page that can (or might) be meaningfully
4255 * viewed? In particular, this function may be used to determine if
4256 * links to the title should be rendered as "bluelinks" (as opposed to
4257 * "redlinks" to non-existent pages).
4258 * Adding something else to this function will cause inconsistency
4259 * since LinkHolderArray calls isAlwaysKnown() and does its own
4260 * page existence check.
4264 public function isKnown() {
4265 return $this->isAlwaysKnown() ||
$this->exists();
4269 * Does this page have source text?
4273 public function hasSourceText() {
4274 if ( $this->exists() ) {
4278 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4279 // If the page doesn't exist but is a known system message, default
4280 // message content will be displayed, same for language subpages-
4281 // Use always content language to avoid loading hundreds of languages
4282 // to get the link color.
4284 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4285 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4286 return $message->exists();
4293 * Get the default message text or false if the message doesn't exist
4295 * @return String or false
4297 public function getDefaultMessageText() {
4300 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4304 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4305 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4307 if ( $message->exists() ) {
4308 return $message->plain();
4315 * Updates page_touched for this page; called from LinksUpdate.php
4317 * @return Bool true if the update succeded
4319 public function invalidateCache() {
4320 if ( wfReadOnly() ) {
4323 $dbw = wfGetDB( DB_MASTER
);
4324 $success = $dbw->update(
4326 array( 'page_touched' => $dbw->timestamp() ),
4330 HTMLFileCache
::clearFileCache( $this );
4335 * Update page_touched timestamps and send squid purge messages for
4336 * pages linking to this title. May be sent to the job queue depending
4337 * on the number of links. Typically called on create and delete.
4339 public function touchLinks() {
4340 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4343 if ( $this->getNamespace() == NS_CATEGORY
) {
4344 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4350 * Get the last touched timestamp
4352 * @param $db DatabaseBase: optional db
4353 * @return String last-touched timestamp
4355 public function getTouched( $db = null ) {
4356 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4357 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4362 * Get the timestamp when this page was updated since the user last saw it.
4365 * @return String|Null
4367 public function getNotificationTimestamp( $user = null ) {
4368 global $wgUser, $wgShowUpdatedMarker;
4369 // Assume current user if none given
4373 // Check cache first
4374 $uid = $user->getId();
4375 // avoid isset here, as it'll return false for null entries
4376 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4377 return $this->mNotificationTimestamp
[$uid];
4379 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4380 return $this->mNotificationTimestamp
[$uid] = false;
4382 // Don't cache too much!
4383 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4384 $this->mNotificationTimestamp
= array();
4386 $dbr = wfGetDB( DB_SLAVE
);
4387 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4388 'wl_notificationtimestamp',
4390 'wl_user' => $user->getId(),
4391 'wl_namespace' => $this->getNamespace(),
4392 'wl_title' => $this->getDBkey(),
4396 return $this->mNotificationTimestamp
[$uid];
4400 * Generate strings used for xml 'id' names in monobook tabs
4402 * @param $prepend string defaults to 'nstab-'
4403 * @return String XML 'id' name
4405 public function getNamespaceKey( $prepend = 'nstab-' ) {
4407 // Gets the subject namespace if this title
4408 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4409 // Checks if cononical namespace name exists for namespace
4410 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4411 // Uses canonical namespace name
4412 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4414 // Uses text of namespace
4415 $namespaceKey = $this->getSubjectNsText();
4417 // Makes namespace key lowercase
4418 $namespaceKey = $wgContLang->lc( $namespaceKey );
4420 if ( $namespaceKey == '' ) {
4421 $namespaceKey = 'main';
4423 // Changes file to image for backwards compatibility
4424 if ( $namespaceKey == 'file' ) {
4425 $namespaceKey = 'image';
4427 return $prepend . $namespaceKey;
4431 * Get all extant redirects to this Title
4433 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4434 * @return Array of Title redirects to this title
4436 public function getRedirectsHere( $ns = null ) {
4439 $dbr = wfGetDB( DB_SLAVE
);
4441 'rd_namespace' => $this->getNamespace(),
4442 'rd_title' => $this->getDBkey(),
4445 if ( !is_null( $ns ) ) {
4446 $where['page_namespace'] = $ns;
4449 $res = $dbr->select(
4450 array( 'redirect', 'page' ),
4451 array( 'page_namespace', 'page_title' ),
4456 foreach ( $res as $row ) {
4457 $redirs[] = self
::newFromRow( $row );
4463 * Check if this Title is a valid redirect target
4467 public function isValidRedirectTarget() {
4468 global $wgInvalidRedirectTargets;
4470 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4471 if ( $this->isSpecial( 'Userlogout' ) ) {
4475 foreach ( $wgInvalidRedirectTargets as $target ) {
4476 if ( $this->isSpecial( $target ) ) {
4485 * Get a backlink cache object
4487 * @return BacklinkCache
4489 function getBacklinkCache() {
4490 if ( is_null( $this->mBacklinkCache
) ) {
4491 $this->mBacklinkCache
= new BacklinkCache( $this );
4493 return $this->mBacklinkCache
;
4497 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4501 public function canUseNoindex() {
4502 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4504 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4505 ?
$wgContentNamespaces
4506 : $wgExemptFromUserRobotsControl;
4508 return !in_array( $this->mNamespace
, $bannedNamespaces );
4513 * Returns the raw sort key to be used for categories, with the specified
4514 * prefix. This will be fed to Collation::getSortKey() to get a
4515 * binary sortkey that can be used for actual sorting.
4517 * @param $prefix string The prefix to be used, specified using
4518 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4522 public function getCategorySortkey( $prefix = '' ) {
4523 $unprefixed = $this->getText();
4525 // Anything that uses this hook should only depend
4526 // on the Title object passed in, and should probably
4527 // tell the users to run updateCollations.php --force
4528 // in order to re-sort existing category relations.
4529 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4530 if ( $prefix !== '' ) {
4531 # Separate with a line feed, so the unprefixed part is only used as
4532 # a tiebreaker when two pages have the exact same prefix.
4533 # In UCA, tab is the only character that can sort above LF
4534 # so we strip both of them from the original prefix.
4535 $prefix = strtr( $prefix, "\n\t", ' ' );
4536 return "$prefix\n$unprefixed";
4542 * Get the language in which the content of this page is written.
4543 * Defaults to $wgContLang, but in certain cases it can be e.g.
4544 * $wgLang (such as special pages, which are in the user language).
4549 public function getPageLanguage() {
4551 if ( $this->isSpecialPage() ) {
4552 // special pages are in the user language
4554 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4555 // css/js should always be LTR and is, in fact, English
4556 return wfGetLangObj( 'en' );
4557 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4558 // Parse mediawiki messages with correct target language
4559 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4560 return wfGetLangObj( $lang );
4563 // If nothing special, it should be in the wiki content language
4564 $pageLang = $wgContLang;
4565 // Hook at the end because we don't want to override the above stuff
4566 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4567 return wfGetLangObj( $pageLang );