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
373 * @deprecated since 1.WD, use Content::getRedirectTarget instead.
375 public static function newFromRedirect( $text ) {
376 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
377 return $content->getRedirectTarget();
381 * Extract a redirect destination from a string and return the
382 * Title, or null if the text doesn't contain a valid redirect
383 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
384 * in order to provide (hopefully) the Title of the final destination instead of another redirect
386 * @param $text String Text with possible redirect
388 * @deprecated since 1.WD, use Content::getUltimateRedirectTarget instead.
390 public static function newFromRedirectRecurse( $text ) {
391 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
392 return $content->getUltimateRedirectTarget();
396 * Extract a redirect destination from a string and return an
397 * array of Titles, or null if the text doesn't contain a valid redirect
398 * The last element in the array is the final destination after all redirects
399 * have been resolved (up to $wgMaxRedirects times)
401 * @param $text String Text with possible redirect
402 * @return Array of Titles, with the destination last
403 * @deprecated since 1.WD, use Content::getRedirectChain instead.
404 * @todo: migrate this logic into WikitextContent!
406 public static function newFromRedirectArray( $text ) {
407 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
408 return $content->getRedirectChain();
412 * Get the prefixed DB key associated with an ID
414 * @param $id Int the page_id of the article
415 * @return Title an object representing the article, or NULL if no such article was found
417 public static function nameOf( $id ) {
418 $dbr = wfGetDB( DB_SLAVE
);
420 $s = $dbr->selectRow(
422 array( 'page_namespace', 'page_title' ),
423 array( 'page_id' => $id ),
426 if ( $s === false ) {
430 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
435 * Get a regex character class describing the legal characters in a link
437 * @return String the list of characters, not delimited
439 public static function legalChars() {
440 global $wgLegalTitleChars;
441 return $wgLegalTitleChars;
445 * Returns a simple regex that will match on characters and sequences invalid in titles.
446 * Note that this doesn't pick up many things that could be wrong with titles, but that
447 * replacing this regex with something valid will make many titles valid.
449 * @return String regex string
451 static function getTitleInvalidRegex() {
452 static $rxTc = false;
454 # Matching titles will be held as illegal.
456 # Any character not allowed is forbidden...
457 '[^' . self
::legalChars() . ']' .
458 # URL percent encoding sequences interfere with the ability
459 # to round-trip titles -- you can't link to them consistently.
461 # XML/HTML character references produce similar issues.
462 '|&[A-Za-z0-9\x80-\xff]+;' .
464 '|&#x[0-9A-Fa-f]+;' .
472 * Get a string representation of a title suitable for
473 * including in a search index
475 * @param $ns Int a namespace index
476 * @param $title String text-form main part
477 * @return String a stripped-down title string ready for the search index
479 public static function indexTitle( $ns, $title ) {
482 $lc = SearchEngine
::legalSearchChars() . '&#;';
483 $t = $wgContLang->normalizeForSearch( $title );
484 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
485 $t = $wgContLang->lc( $t );
488 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
489 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
491 $t = preg_replace( "/\\s+/", ' ', $t );
493 if ( $ns == NS_FILE
) {
494 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
500 * Make a prefixed DB key from a DB key and a namespace index
502 * @param $ns Int numerical representation of the namespace
503 * @param $title String the DB key form the title
504 * @param $fragment String The link fragment (after the "#")
505 * @param $interwiki String The interwiki prefix
506 * @return String the prefixed form of the title
508 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
511 $namespace = $wgContLang->getNsText( $ns );
512 $name = $namespace == '' ?
$title : "$namespace:$title";
513 if ( strval( $interwiki ) != '' ) {
514 $name = "$interwiki:$name";
516 if ( strval( $fragment ) != '' ) {
517 $name .= '#' . $fragment;
523 * Escape a text fragment, say from a link, for a URL
525 * @param $fragment string containing a URL or link fragment (after the "#")
526 * @return String: escaped string
528 static function escapeFragmentForURL( $fragment ) {
529 # Note that we don't urlencode the fragment. urlencoded Unicode
530 # fragments appear not to work in IE (at least up to 7) or in at least
531 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
532 # to care if they aren't encoded.
533 return Sanitizer
::escapeId( $fragment, 'noninitial' );
537 * Callback for usort() to do title sorts by (namespace, title)
542 * @return Integer: result of string comparison, or namespace comparison
544 public static function compare( $a, $b ) {
545 if ( $a->getNamespace() == $b->getNamespace() ) {
546 return strcmp( $a->getText(), $b->getText() );
548 return $a->getNamespace() - $b->getNamespace();
553 * Determine whether the object refers to a page within
556 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
558 public function isLocal() {
559 if ( $this->mInterwiki
!= '' ) {
560 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
567 * Is this Title interwiki?
571 public function isExternal() {
572 return ( $this->mInterwiki
!= '' );
576 * Get the interwiki prefix (or null string)
578 * @return String Interwiki prefix
580 public function getInterwiki() {
581 return $this->mInterwiki
;
585 * Determine whether the object refers to a page within
586 * this project and is transcludable.
588 * @return Bool TRUE if this is transcludable
590 public function isTrans() {
591 if ( $this->mInterwiki
== '' ) {
595 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
599 * Returns the DB name of the distant wiki which owns the object.
601 * @return String the DB name
603 public function getTransWikiID() {
604 if ( $this->mInterwiki
== '' ) {
608 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
612 * Get the text form (spaces not underscores) of the main part
614 * @return String Main part of the title
616 public function getText() {
617 return $this->mTextform
;
621 * Get the URL-encoded form of the main part
623 * @return String Main part of the title, URL-encoded
625 public function getPartialURL() {
626 return $this->mUrlform
;
630 * Get the main part with underscores
632 * @return String: Main part of the title, with underscores
634 public function getDBkey() {
635 return $this->mDbkeyform
;
639 * Get the DB key with the initial letter case as specified by the user
641 * @return String DB key
643 function getUserCaseDBKey() {
644 return $this->mUserCaseDBKey
;
648 * Get the namespace index, i.e. one of the NS_xxxx constants.
650 * @return Integer: Namespace index
652 public function getNamespace() {
653 return $this->mNamespace
;
657 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
659 * @return Integer: Content model id
661 public function getContentModel() {
662 if ( empty( $this->mContentModel
) ) {
663 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
666 assert( !empty( $this->mContentModel
) );
667 return $this->mContentModel
;
671 * Convenience method for checking a title's content model name
674 * @return true if $this->getContentModel() == $id
676 public function hasContentModel( $id ) {
677 return $this->getContentModel() == $id;
681 * Get the namespace text
683 * @return String: Namespace text
685 public function getNsText() {
688 if ( $this->mInterwiki
!= '' ) {
689 // This probably shouldn't even happen. ohh man, oh yuck.
690 // But for interwiki transclusion it sometimes does.
691 // Shit. Shit shit shit.
693 // Use the canonical namespaces if possible to try to
694 // resolve a foreign namespace.
695 if ( MWNamespace
::exists( $this->mNamespace
) ) {
696 return MWNamespace
::getCanonicalName( $this->mNamespace
);
700 if ( $wgContLang->needsGenderDistinction() &&
701 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
702 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
703 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
706 return $wgContLang->getNsText( $this->mNamespace
);
710 * Get the namespace text of the subject (rather than talk) page
712 * @return String Namespace text
714 public function getSubjectNsText() {
716 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
720 * Get the namespace text of the talk page
722 * @return String Namespace text
724 public function getTalkNsText() {
726 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
730 * Could this title have a corresponding talk page?
732 * @return Bool TRUE or FALSE
734 public function canTalk() {
735 return( MWNamespace
::canTalk( $this->mNamespace
) );
739 * Is this in a namespace that allows actual pages?
742 * @internal note -- uses hardcoded namespace index instead of constants
744 public function canExist() {
745 return $this->mNamespace
>= NS_MAIN
;
749 * Can this title be added to a user's watchlist?
751 * @return Bool TRUE or FALSE
753 public function isWatchable() {
754 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
758 * Returns true if this is a special page.
762 public function isSpecialPage() {
763 return $this->getNamespace() == NS_SPECIAL
;
767 * Returns true if this title resolves to the named special page
769 * @param $name String The special page name
772 public function isSpecial( $name ) {
773 if ( $this->isSpecialPage() ) {
774 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
775 if ( $name == $thisName ) {
783 * If the Title refers to a special page alias which is not the local default, resolve
784 * the alias, and localise the name as necessary. Otherwise, return $this
788 public function fixSpecialName() {
789 if ( $this->isSpecialPage() ) {
790 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
791 if ( $canonicalName ) {
792 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
793 if ( $localName != $this->mDbkeyform
) {
794 return Title
::makeTitle( NS_SPECIAL
, $localName );
802 * Returns true if the title is inside the specified namespace.
804 * Please make use of this instead of comparing to getNamespace()
805 * This function is much more resistant to changes we may make
806 * to namespaces than code that makes direct comparisons.
807 * @param $ns int The namespace
811 public function inNamespace( $ns ) {
812 return MWNamespace
::equals( $this->getNamespace(), $ns );
816 * Returns true if the title is inside one of the specified namespaces.
818 * @param ...$namespaces The namespaces to check for
822 public function inNamespaces( /* ... */ ) {
823 $namespaces = func_get_args();
824 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
825 $namespaces = $namespaces[0];
828 foreach ( $namespaces as $ns ) {
829 if ( $this->inNamespace( $ns ) ) {
838 * Returns true if the title has the same subject namespace as the
839 * namespace specified.
840 * For example this method will take NS_USER and return true if namespace
841 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
842 * as their subject namespace.
844 * This is MUCH simpler than individually testing for equivilance
845 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
850 public function hasSubjectNamespace( $ns ) {
851 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
855 * Is this Title in a namespace which contains content?
856 * In other words, is this a content page, for the purposes of calculating
861 public function isContentPage() {
862 return MWNamespace
::isContent( $this->getNamespace() );
866 * Would anybody with sufficient privileges be able to move this page?
867 * Some pages just aren't movable.
869 * @return Bool TRUE or FALSE
871 public function isMovable() {
872 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
873 // Interwiki title or immovable namespace. Hooks don't get to override here
878 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
883 * Is this the mainpage?
884 * @note Title::newFromText seams to be sufficiently optimized by the title
885 * cache that we don't need to over-optimize by doing direct comparisons and
886 * acidentally creating new bugs where $title->equals( Title::newFromText() )
887 * ends up reporting something differently than $title->isMainPage();
892 public function isMainPage() {
893 return $this->equals( Title
::newMainPage() );
901 public function isSubpage() {
902 return MWNamespace
::hasSubpages( $this->mNamespace
)
903 ?
strpos( $this->getText(), '/' ) !== false
908 * Is this a conversion table for the LanguageConverter?
912 public function isConversionTable() {
913 return $this->getNamespace() == NS_MEDIAWIKI
&&
914 strpos( $this->getText(), 'Conversiontable' ) !== false;
918 * Does that page contain wikitext, or it is JS, CSS or whatever?
922 public function isWikitextPage() {
923 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
927 * Could this page contain custom CSS or JavaScript for the global UI.
928 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
929 * or CONTENT_MODEL_JAVASCRIPT.
931 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
933 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
937 public function isCssOrJsPage() {
938 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
939 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
940 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
942 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
943 # hook funktions can force this method to return true even outside the mediawiki namespace.
945 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
947 return $isCssOrJsPage;
951 * Is this a .css or .js subpage of a user page?
954 public function isCssJsSubpage() {
955 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
956 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
957 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
961 * Trim down a .css or .js subpage title to get the corresponding skin name
963 * @return string containing skin name from .css or .js subpage title
965 public function getSkinFromCssJsSubpage() {
966 $subpage = explode( '/', $this->mTextform
);
967 $subpage = $subpage[ count( $subpage ) - 1 ];
968 $lastdot = strrpos( $subpage, '.' );
969 if ( $lastdot === false )
970 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
971 return substr( $subpage, 0, $lastdot );
975 * Is this a .css subpage of a user page?
979 public function isCssSubpage() {
980 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
981 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
985 * Is this a .js subpage of a user page?
989 public function isJsSubpage() {
990 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
991 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
995 * Is this a talk page of some sort?
999 public function isTalkPage() {
1000 return MWNamespace
::isTalk( $this->getNamespace() );
1004 * Get a Title object associated with the talk page of this article
1006 * @return Title the object for the talk page
1008 public function getTalkPage() {
1009 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1013 * Get a title object associated with the subject page of this
1016 * @return Title the object for the subject page
1018 public function getSubjectPage() {
1019 // Is this the same title?
1020 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1021 if ( $this->getNamespace() == $subjectNS ) {
1024 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1028 * Get the default namespace index, for when there is no namespace
1030 * @return Int Default namespace index
1032 public function getDefaultNamespace() {
1033 return $this->mDefaultNamespace
;
1037 * Get title for search index
1039 * @return String a stripped-down title string ready for the
1042 public function getIndexTitle() {
1043 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1047 * Get the Title fragment (i.e.\ the bit after the #) in text form
1049 * @return String Title fragment
1051 public function getFragment() {
1052 return $this->mFragment
;
1056 * Get the fragment in URL form, including the "#" character if there is one
1057 * @return String Fragment in URL form
1059 public function getFragmentForURL() {
1060 if ( $this->mFragment
== '' ) {
1063 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1068 * Set the fragment for this title. Removes the first character from the
1069 * specified fragment before setting, so it assumes you're passing it with
1072 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1073 * Still in active use privately.
1075 * @param $fragment String text
1077 public function setFragment( $fragment ) {
1078 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1082 * Prefix some arbitrary text with the namespace or interwiki prefix
1085 * @param $name String the text
1086 * @return String the prefixed text
1089 private function prefix( $name ) {
1091 if ( $this->mInterwiki
!= '' ) {
1092 $p = $this->mInterwiki
. ':';
1095 if ( 0 != $this->mNamespace
) {
1096 $p .= $this->getNsText() . ':';
1102 * Get the prefixed database key form
1104 * @return String the prefixed title, with underscores and
1105 * any interwiki and namespace prefixes
1107 public function getPrefixedDBkey() {
1108 $s = $this->prefix( $this->mDbkeyform
);
1109 $s = str_replace( ' ', '_', $s );
1114 * Get the prefixed title with spaces.
1115 * This is the form usually used for display
1117 * @return String the prefixed title, with spaces
1119 public function getPrefixedText() {
1120 // @todo FIXME: Bad usage of empty() ?
1121 if ( empty( $this->mPrefixedText
) ) {
1122 $s = $this->prefix( $this->mTextform
);
1123 $s = str_replace( '_', ' ', $s );
1124 $this->mPrefixedText
= $s;
1126 return $this->mPrefixedText
;
1130 * Return a string representation of this title
1132 * @return String representation of this title
1134 public function __toString() {
1135 return $this->getPrefixedText();
1139 * Get the prefixed title with spaces, plus any fragment
1140 * (part beginning with '#')
1142 * @return String the prefixed title, with spaces and the fragment, including '#'
1144 public function getFullText() {
1145 $text = $this->getPrefixedText();
1146 if ( $this->mFragment
!= '' ) {
1147 $text .= '#' . $this->mFragment
;
1153 * Get the base page name, i.e. the leftmost part before any slashes
1155 * @return String Base name
1157 public function getBaseText() {
1158 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1159 return $this->getText();
1162 $parts = explode( '/', $this->getText() );
1163 # Don't discard the real title if there's no subpage involved
1164 if ( count( $parts ) > 1 ) {
1165 unset( $parts[count( $parts ) - 1] );
1167 return implode( '/', $parts );
1171 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1173 * @return String Subpage name
1175 public function getSubpageText() {
1176 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1177 return( $this->mTextform
);
1179 $parts = explode( '/', $this->mTextform
);
1180 return( $parts[count( $parts ) - 1] );
1184 * Get the HTML-escaped displayable text form.
1185 * Used for the title field in <a> tags.
1187 * @return String the text, including any prefixes
1189 public function getEscapedText() {
1190 wfDeprecated( __METHOD__
, '1.19' );
1191 return htmlspecialchars( $this->getPrefixedText() );
1195 * Get a URL-encoded form of the subpage text
1197 * @return String URL-encoded subpage name
1199 public function getSubpageUrlForm() {
1200 $text = $this->getSubpageText();
1201 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1206 * Get a URL-encoded title (not an actual URL) including interwiki
1208 * @return String the URL-encoded form
1210 public function getPrefixedURL() {
1211 $s = $this->prefix( $this->mDbkeyform
);
1212 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1217 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1218 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1219 * second argument named variant. This was deprecated in favor
1220 * of passing an array of option with a "variant" key
1221 * Once $query2 is removed for good, this helper can be dropped
1222 * andthe wfArrayToCGI moved to getLocalURL();
1224 * @since 1.19 (r105919)
1226 * @param $query2 bool
1229 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1230 if( $query2 !== false ) {
1231 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" );
1233 if ( is_array( $query ) ) {
1234 $query = wfArrayToCGI( $query );
1237 if ( is_string( $query2 ) ) {
1238 // $query2 is a string, we will consider this to be
1239 // a deprecated $variant argument and add it to the query
1240 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1242 $query2 = wfArrayToCGI( $query2 );
1244 // If we have $query content add a & to it first
1248 // Now append the queries together
1255 * Get a real URL referring to this title, with interwiki link and
1258 * See getLocalURL for the arguments.
1260 * @see self::getLocalURL
1261 * @return String the URL
1263 public function getFullURL( $query = '', $query2 = false ) {
1264 $query = self
::fixUrlQueryArgs( $query, $query2 );
1266 # Hand off all the decisions on urls to getLocalURL
1267 $url = $this->getLocalURL( $query );
1269 # Expand the url to make it a full url. Note that getLocalURL has the
1270 # potential to output full urls for a variety of reasons, so we use
1271 # wfExpandUrl instead of simply prepending $wgServer
1272 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1274 # Finally, add the fragment.
1275 $url .= $this->getFragmentForURL();
1277 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1282 * Get a URL with no fragment or server name. If this page is generated
1283 * with action=render, $wgServer is prepended.
1286 * @param $query string|array an optional query string,
1287 * not used for interwiki links. Can be specified as an associative array as well,
1288 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1289 * Some query patterns will trigger various shorturl path replacements.
1290 * @param $query2 Mixed: An optional secondary query array. This one MUST
1291 * be an array. If a string is passed it will be interpreted as a deprecated
1292 * variant argument and urlencoded into a variant= argument.
1293 * This second query argument will be added to the $query
1294 * The second parameter is deprecated since 1.19. Pass it as a key,value
1295 * pair in the first parameter array instead.
1297 * @return String the URL
1299 public function getLocalURL( $query = '', $query2 = false ) {
1300 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1302 $query = self
::fixUrlQueryArgs( $query, $query2 );
1304 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1306 $namespace = $this->getNsText();
1307 if ( $namespace != '' ) {
1308 # Can this actually happen? Interwikis shouldn't be parsed.
1309 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1312 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1313 $url = wfAppendQuery( $url, $query );
1315 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1316 if ( $query == '' ) {
1317 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1318 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1320 global $wgVariantArticlePath, $wgActionPaths;
1324 if ( !empty( $wgActionPaths ) &&
1325 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1327 $action = urldecode( $matches[2] );
1328 if ( isset( $wgActionPaths[$action] ) ) {
1329 $query = $matches[1];
1330 if ( isset( $matches[4] ) ) {
1331 $query .= $matches[4];
1333 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1334 if ( $query != '' ) {
1335 $url = wfAppendQuery( $url, $query );
1340 if ( $url === false &&
1341 $wgVariantArticlePath &&
1342 $this->getPageLanguage()->hasVariants() &&
1343 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1345 $variant = urldecode( $matches[1] );
1346 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1347 // Only do the variant replacement if the given variant is a valid
1348 // variant for the page's language.
1349 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1350 $url = str_replace( '$1', $dbkey, $url );
1354 if ( $url === false ) {
1355 if ( $query == '-' ) {
1358 $url = "{$wgScript}?title={$dbkey}&{$query}";
1362 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1364 // @todo FIXME: This causes breakage in various places when we
1365 // actually expected a local URL and end up with dupe prefixes.
1366 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1367 $url = $wgServer . $url;
1370 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1375 * Get a URL that's the simplest URL that will be valid to link, locally,
1376 * to the current Title. It includes the fragment, but does not include
1377 * the server unless action=render is used (or the link is external). If
1378 * there's a fragment but the prefixed text is empty, we just return a link
1381 * The result obviously should not be URL-escaped, but does need to be
1382 * HTML-escaped if it's being output in HTML.
1384 * See getLocalURL for the arguments.
1386 * @see self::getLocalURL
1387 * @return String the URL
1389 public function getLinkURL( $query = '', $query2 = false ) {
1390 wfProfileIn( __METHOD__
);
1391 if ( $this->isExternal() ) {
1392 $ret = $this->getFullURL( $query, $query2 );
1393 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1394 $ret = $this->getFragmentForURL();
1396 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1398 wfProfileOut( __METHOD__
);
1403 * Get an HTML-escaped version of the URL form, suitable for
1404 * using in a link, without a server name or fragment
1406 * See getLocalURL for the arguments.
1408 * @see self::getLocalURL
1409 * @param $query string
1410 * @param $query2 bool|string
1411 * @return String the URL
1413 public function escapeLocalURL( $query = '', $query2 = false ) {
1414 wfDeprecated( __METHOD__
, '1.19' );
1415 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1419 * Get an HTML-escaped version of the URL form, suitable for
1420 * using in a link, including the server name and fragment
1422 * See getLocalURL for the arguments.
1424 * @see self::getLocalURL
1425 * @return String the URL
1427 public function escapeFullURL( $query = '', $query2 = false ) {
1428 wfDeprecated( __METHOD__
, '1.19' );
1429 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1433 * Get the URL form for an internal link.
1434 * - Used in various Squid-related code, in case we have a different
1435 * internal hostname for the server from the exposed one.
1437 * This uses $wgInternalServer to qualify the path, or $wgServer
1438 * if $wgInternalServer is not set. If the server variable used is
1439 * protocol-relative, the URL will be expanded to http://
1441 * See getLocalURL for the arguments.
1443 * @see self::getLocalURL
1444 * @return String the URL
1446 public function getInternalURL( $query = '', $query2 = false ) {
1447 global $wgInternalServer, $wgServer;
1448 $query = self
::fixUrlQueryArgs( $query, $query2 );
1449 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1450 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1451 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1456 * Get the URL for a canonical link, for use in things like IRC and
1457 * e-mail notifications. Uses $wgCanonicalServer and the
1458 * GetCanonicalURL hook.
1460 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1462 * See getLocalURL for the arguments.
1464 * @see self::getLocalURL
1465 * @return string The URL
1468 public function getCanonicalURL( $query = '', $query2 = false ) {
1469 $query = self
::fixUrlQueryArgs( $query, $query2 );
1470 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1471 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1476 * HTML-escaped version of getCanonicalURL()
1478 * See getLocalURL for the arguments.
1480 * @see self::getLocalURL
1484 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1485 wfDeprecated( __METHOD__
, '1.19' );
1486 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1490 * Get the edit URL for this Title
1492 * @return String the URL, or a null string if this is an
1495 public function getEditURL() {
1496 if ( $this->mInterwiki
!= '' ) {
1499 $s = $this->getLocalURL( 'action=edit' );
1505 * Is $wgUser watching this page?
1509 public function userIsWatching() {
1512 if ( is_null( $this->mWatched
) ) {
1513 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1514 $this->mWatched
= false;
1516 $this->mWatched
= $wgUser->isWatched( $this );
1519 return $this->mWatched
;
1523 * Can $wgUser read this page?
1525 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1527 * @todo fold these checks into userCan()
1529 public function userCanRead() {
1530 wfDeprecated( __METHOD__
, '1.19' );
1531 return $this->userCan( 'read' );
1535 * Can $user perform $action on this page?
1536 * This skips potentially expensive cascading permission checks
1537 * as well as avoids expensive error formatting
1539 * Suitable for use for nonessential UI controls in common cases, but
1540 * _not_ for functional access control.
1542 * May provide false positives, but should never provide a false negative.
1544 * @param $action String action that permission needs to be checked for
1545 * @param $user User to check (since 1.19); $wgUser will be used if not
1549 public function quickUserCan( $action, $user = null ) {
1550 return $this->userCan( $action, $user, false );
1554 * Can $user perform $action on this page?
1556 * @param $action String action that permission needs to be checked for
1557 * @param $user User to check (since 1.19); $wgUser will be used if not
1559 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1560 * unnecessary queries.
1563 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1564 if ( !$user instanceof User
) {
1568 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1572 * Can $user perform $action on this page?
1574 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1576 * @param $action String action that permission needs to be checked for
1577 * @param $user User to check
1578 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1579 * queries by skipping checks for cascading protections and user blocks.
1580 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1581 * whose corresponding errors may be ignored.
1582 * @return Array of arguments to wfMsg to explain permissions problems.
1584 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1585 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1587 // Remove the errors being ignored.
1588 foreach ( $errors as $index => $error ) {
1589 $error_key = is_array( $error ) ?
$error[0] : $error;
1591 if ( in_array( $error_key, $ignoreErrors ) ) {
1592 unset( $errors[$index] );
1600 * Permissions checks that fail most often, and which are easiest to test.
1602 * @param $action String the action to check
1603 * @param $user User user to check
1604 * @param $errors Array list of current errors
1605 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1606 * @param $short Boolean short circuit on first error
1608 * @return Array list of errors
1610 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1611 if ( $action == 'create' ) {
1612 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1613 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1614 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1616 } elseif ( $action == 'move' ) {
1617 if ( !$user->isAllowed( 'move-rootuserpages' )
1618 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1619 // Show user page-specific message only if the user can move other pages
1620 $errors[] = array( 'cant-move-user-page' );
1623 // Check if user is allowed to move files if it's a file
1624 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1625 $errors[] = array( 'movenotallowedfile' );
1628 if ( !$user->isAllowed( 'move' ) ) {
1629 // User can't move anything
1630 global $wgGroupPermissions;
1631 $userCanMove = false;
1632 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1633 $userCanMove = $wgGroupPermissions['user']['move'];
1635 $autoconfirmedCanMove = false;
1636 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1637 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1639 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1640 // custom message if logged-in users without any special rights can move
1641 $errors[] = array( 'movenologintext' );
1643 $errors[] = array( 'movenotallowed' );
1646 } elseif ( $action == 'move-target' ) {
1647 if ( !$user->isAllowed( 'move' ) ) {
1648 // User can't move anything
1649 $errors[] = array( 'movenotallowed' );
1650 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1651 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1652 // Show user page-specific message only if the user can move other pages
1653 $errors[] = array( 'cant-move-to-user-page' );
1655 } elseif ( !$user->isAllowed( $action ) ) {
1656 $errors[] = $this->missingPermissionError( $action, $short );
1663 * Add the resulting error code to the errors array
1665 * @param $errors Array list of current errors
1666 * @param $result Mixed result of errors
1668 * @return Array list of errors
1670 private function resultToError( $errors, $result ) {
1671 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1672 // A single array representing an error
1673 $errors[] = $result;
1674 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1675 // A nested array representing multiple errors
1676 $errors = array_merge( $errors, $result );
1677 } elseif ( $result !== '' && is_string( $result ) ) {
1678 // A string representing a message-id
1679 $errors[] = array( $result );
1680 } elseif ( $result === false ) {
1681 // a generic "We don't want them to do that"
1682 $errors[] = array( 'badaccess-group0' );
1688 * Check various permission hooks
1690 * @param $action String the action to check
1691 * @param $user User user to check
1692 * @param $errors Array list of current errors
1693 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1694 * @param $short Boolean short circuit on first error
1696 * @return Array list of errors
1698 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1699 // Use getUserPermissionsErrors instead
1701 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1702 return $result ?
array() : array( array( 'badaccess-group0' ) );
1704 // Check getUserPermissionsErrors hook
1705 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1706 $errors = $this->resultToError( $errors, $result );
1708 // Check getUserPermissionsErrorsExpensive hook
1709 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1710 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1711 $errors = $this->resultToError( $errors, $result );
1718 * Check permissions on special pages & namespaces
1720 * @param $action String the action to check
1721 * @param $user User user to check
1722 * @param $errors Array list of current errors
1723 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1724 * @param $short Boolean short circuit on first error
1726 * @return Array list of errors
1728 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1729 # Only 'createaccount' and 'execute' can be performed on
1730 # special pages, which don't actually exist in the DB.
1731 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1732 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1733 $errors[] = array( 'ns-specialprotected' );
1736 # Check $wgNamespaceProtection for restricted namespaces
1737 if ( $this->isNamespaceProtected( $user ) ) {
1738 $ns = $this->mNamespace
== NS_MAIN ?
1739 wfMsg( 'nstab-main' ) : $this->getNsText();
1740 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1741 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1748 * Check CSS/JS sub-page permissions
1750 * @param $action String the action to check
1751 * @param $user User user to check
1752 * @param $errors Array list of current errors
1753 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1754 * @param $short Boolean short circuit on first error
1756 * @return Array list of errors
1758 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1759 # Protect css/js subpages of user pages
1760 # XXX: this might be better using restrictions
1761 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1762 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1763 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1764 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1765 $errors[] = array( 'customcssprotected' );
1766 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1767 $errors[] = array( 'customjsprotected' );
1775 * Check against page_restrictions table requirements on this
1776 * page. The user must possess all required rights for this
1779 * @param $action String the action to check
1780 * @param $user User user to check
1781 * @param $errors Array list of current errors
1782 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1783 * @param $short Boolean short circuit on first error
1785 * @return Array list of errors
1787 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1788 foreach ( $this->getRestrictions( $action ) as $right ) {
1789 // Backwards compatibility, rewrite sysop -> protect
1790 if ( $right == 'sysop' ) {
1793 if ( $right != '' && !$user->isAllowed( $right ) ) {
1794 // Users with 'editprotected' permission can edit protected pages
1795 // without cascading option turned on.
1796 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1797 ||
$this->mCascadeRestriction
)
1799 $errors[] = array( 'protectedpagetext', $right );
1808 * Check restrictions on cascading pages.
1810 * @param $action String the action to check
1811 * @param $user User to check
1812 * @param $errors Array list of current errors
1813 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1814 * @param $short Boolean short circuit on first error
1816 * @return Array list of errors
1818 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1819 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1820 # We /could/ use the protection level on the source page, but it's
1821 # fairly ugly as we have to establish a precedence hierarchy for pages
1822 # included by multiple cascade-protected pages. So just restrict
1823 # it to people with 'protect' permission, as they could remove the
1824 # protection anyway.
1825 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1826 # Cascading protection depends on more than this page...
1827 # Several cascading protected pages may include this page...
1828 # Check each cascading level
1829 # This is only for protection restrictions, not for all actions
1830 if ( isset( $restrictions[$action] ) ) {
1831 foreach ( $restrictions[$action] as $right ) {
1832 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1833 if ( $right != '' && !$user->isAllowed( $right ) ) {
1835 foreach ( $cascadingSources as $page )
1836 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1837 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1847 * Check action permissions not already checked in checkQuickPermissions
1849 * @param $action String the action to check
1850 * @param $user User to check
1851 * @param $errors Array list of current errors
1852 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1853 * @param $short Boolean short circuit on first error
1855 * @return Array list of errors
1857 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1858 global $wgDeleteRevisionsLimit, $wgLang;
1860 if ( $action == 'protect' ) {
1861 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1862 // If they can't edit, they shouldn't protect.
1863 $errors[] = array( 'protect-cantedit' );
1865 } elseif ( $action == 'create' ) {
1866 $title_protection = $this->getTitleProtection();
1867 if( $title_protection ) {
1868 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1869 $title_protection['pt_create_perm'] = 'protect'; // B/C
1871 if( $title_protection['pt_create_perm'] == '' ||
1872 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1874 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1877 } elseif ( $action == 'move' ) {
1878 // Check for immobile pages
1879 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1880 // Specific message for this case
1881 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1882 } elseif ( !$this->isMovable() ) {
1883 // Less specific message for rarer cases
1884 $errors[] = array( 'immobile-source-page' );
1886 } elseif ( $action == 'move-target' ) {
1887 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1888 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1889 } elseif ( !$this->isMovable() ) {
1890 $errors[] = array( 'immobile-target-page' );
1892 } elseif ( $action == 'delete' ) {
1893 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1894 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1896 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1903 * Check that the user isn't blocked from editting.
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 checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1914 // Account creation blocks handled at userlogin.
1915 // Unblocking handled in SpecialUnblock
1916 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1920 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1922 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1923 $errors[] = array( 'confirmedittext' );
1926 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1927 // Don't block the user from editing their own talk page unless they've been
1928 // explicitly blocked from that too.
1929 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1930 $block = $user->getBlock();
1932 // This is from OutputPage::blockedPage
1933 // Copied at r23888 by werdna
1935 $id = $user->blockedBy();
1936 $reason = $user->blockedFor();
1937 if ( $reason == '' ) {
1938 $reason = wfMsg( 'blockednoreason' );
1940 $ip = $user->getRequest()->getIP();
1942 if ( is_numeric( $id ) ) {
1943 $name = User
::whoIs( $id );
1948 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1949 $blockid = $block->getId();
1950 $blockExpiry = $block->getExpiry();
1951 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1952 if ( $blockExpiry == 'infinity' ) {
1953 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1955 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1958 $intended = strval( $block->getTarget() );
1960 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1961 $blockid, $blockExpiry, $intended, $blockTimestamp );
1968 * Check that the user is allowed to read this page.
1970 * @param $action String the action to check
1971 * @param $user User to check
1972 * @param $errors Array list of current errors
1973 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1974 * @param $short Boolean short circuit on first error
1976 * @return Array list of errors
1978 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1979 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1980 static $useShortcut = null;
1982 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1983 if ( is_null( $useShortcut ) ) {
1984 $useShortcut = true;
1985 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1986 # Not a public wiki, so no shortcut
1987 $useShortcut = false;
1988 } elseif ( !empty( $wgRevokePermissions ) ) {
1990 * Iterate through each group with permissions being revoked (key not included since we don't care
1991 * what the group name is), then check if the read permission is being revoked. If it is, then
1992 * we don't use the shortcut below since the user might not be able to read, even though anon
1993 * reading is allowed.
1995 foreach ( $wgRevokePermissions as $perms ) {
1996 if ( !empty( $perms['read'] ) ) {
1997 # We might be removing the read right from the user, so no shortcut
1998 $useShortcut = false;
2005 $whitelisted = false;
2006 if ( $useShortcut ) {
2007 # Shortcut for public wikis, allows skipping quite a bit of code
2008 $whitelisted = true;
2009 } elseif ( $user->isAllowed( 'read' ) ) {
2010 # If the user is allowed to read pages, he is allowed to read all pages
2011 $whitelisted = true;
2012 } elseif ( $this->isSpecial( 'Userlogin' )
2013 ||
$this->isSpecial( 'ChangePassword' )
2014 ||
$this->isSpecial( 'PasswordReset' )
2016 # Always grant access to the login page.
2017 # Even anons need to be able to log in.
2018 $whitelisted = true;
2019 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2020 # Time to check the whitelist
2021 # Only do these checks is there's something to check against
2022 $name = $this->getPrefixedText();
2023 $dbName = $this->getPrefixedDBKey();
2025 // Check for explicit whitelisting with and without underscores
2026 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2027 $whitelisted = true;
2028 } elseif ( $this->getNamespace() == NS_MAIN
) {
2029 # Old settings might have the title prefixed with
2030 # a colon for main-namespace pages
2031 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2032 $whitelisted = true;
2034 } elseif ( $this->isSpecialPage() ) {
2035 # If it's a special page, ditch the subpage bit and check again
2036 $name = $this->getDBkey();
2037 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2038 if ( $name !== false ) {
2039 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2040 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2041 $whitelisted = true;
2047 if ( !$whitelisted ) {
2048 # If the title is not whitelisted, give extensions a chance to do so...
2049 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2050 if ( !$whitelisted ) {
2051 $errors[] = $this->missingPermissionError( $action, $short );
2059 * Get a description array when the user doesn't have the right to perform
2060 * $action (i.e. when User::isAllowed() returns false)
2062 * @param $action String the action to check
2063 * @param $short Boolean short circuit on first error
2064 * @return Array list of errors
2066 private function missingPermissionError( $action, $short ) {
2067 // We avoid expensive display logic for quickUserCan's and such
2069 return array( 'badaccess-group0' );
2072 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2073 User
::getGroupsWithPermission( $action ) );
2075 if ( count( $groups ) ) {
2079 $wgLang->commaList( $groups ),
2083 return array( 'badaccess-group0' );
2088 * Can $user perform $action on this page? This is an internal function,
2089 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2090 * checks on wfReadOnly() and blocks)
2092 * @param $action String action that permission needs to be checked for
2093 * @param $user User to check
2094 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2095 * @param $short Bool Set this to true to stop after the first permission error.
2096 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2098 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2099 wfProfileIn( __METHOD__
);
2101 # Read has special handling
2102 if ( $action == 'read' ) {
2104 'checkPermissionHooks',
2105 'checkReadPermissions',
2109 'checkQuickPermissions',
2110 'checkPermissionHooks',
2111 'checkSpecialsAndNSPermissions',
2112 'checkCSSandJSPermissions',
2113 'checkPageRestrictions',
2114 'checkCascadingSourcesRestrictions',
2115 'checkActionPermissions',
2121 while( count( $checks ) > 0 &&
2122 !( $short && count( $errors ) > 0 ) ) {
2123 $method = array_shift( $checks );
2124 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2127 wfProfileOut( __METHOD__
);
2132 * Protect css subpages of user pages: can $wgUser edit
2135 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2138 public function userCanEditCssSubpage() {
2140 wfDeprecated( __METHOD__
, '1.19' );
2141 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2142 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2146 * Protect js subpages of user pages: can $wgUser edit
2149 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2152 public function userCanEditJsSubpage() {
2154 wfDeprecated( __METHOD__
, '1.19' );
2155 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2156 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2160 * Get a filtered list of all restriction types supported by this wiki.
2161 * @param bool $exists True to get all restriction types that apply to
2162 * titles that do exist, False for all restriction types that apply to
2163 * titles that do not exist
2166 public static function getFilteredRestrictionTypes( $exists = true ) {
2167 global $wgRestrictionTypes;
2168 $types = $wgRestrictionTypes;
2170 # Remove the create restriction for existing titles
2171 $types = array_diff( $types, array( 'create' ) );
2173 # Only the create and upload restrictions apply to non-existing titles
2174 $types = array_intersect( $types, array( 'create', 'upload' ) );
2180 * Returns restriction types for the current Title
2182 * @return array applicable restriction types
2184 public function getRestrictionTypes() {
2185 if ( $this->isSpecialPage() ) {
2189 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2191 if ( $this->getNamespace() != NS_FILE
) {
2192 # Remove the upload restriction for non-file titles
2193 $types = array_diff( $types, array( 'upload' ) );
2196 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2198 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2199 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2205 * Is this title subject to title protection?
2206 * Title protection is the one applied against creation of such title.
2208 * @return Mixed An associative array representing any existent title
2209 * protection, or false if there's none.
2211 private function getTitleProtection() {
2212 // Can't protect pages in special namespaces
2213 if ( $this->getNamespace() < 0 ) {
2217 // Can't protect pages that exist.
2218 if ( $this->exists() ) {
2222 if ( !isset( $this->mTitleProtection
) ) {
2223 $dbr = wfGetDB( DB_SLAVE
);
2224 $res = $dbr->select( 'protected_titles', '*',
2225 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2228 // fetchRow returns false if there are no rows.
2229 $this->mTitleProtection
= $dbr->fetchRow( $res );
2231 return $this->mTitleProtection
;
2235 * Update the title protection status
2237 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2238 * @param $create_perm String Permission required for creation
2239 * @param $reason String Reason for protection
2240 * @param $expiry String Expiry timestamp
2241 * @return boolean true
2243 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2244 wfDeprecated( __METHOD__
, '1.19' );
2248 $limit = array( 'create' => $create_perm );
2249 $expiry = array( 'create' => $expiry );
2251 $page = WikiPage
::factory( $this );
2252 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2254 return $status->isOK();
2258 * Remove any title protection due to page existing
2260 public function deleteTitleProtection() {
2261 $dbw = wfGetDB( DB_MASTER
);
2265 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2268 $this->mTitleProtection
= false;
2272 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2274 * @param $action String Action to check (default: edit)
2277 public function isSemiProtected( $action = 'edit' ) {
2278 if ( $this->exists() ) {
2279 $restrictions = $this->getRestrictions( $action );
2280 if ( count( $restrictions ) > 0 ) {
2281 foreach ( $restrictions as $restriction ) {
2282 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2292 # If it doesn't exist, it can't be protected
2298 * Does the title correspond to a protected article?
2300 * @param $action String the action the page is protected from,
2301 * by default checks all actions.
2304 public function isProtected( $action = '' ) {
2305 global $wgRestrictionLevels;
2307 $restrictionTypes = $this->getRestrictionTypes();
2309 # Special pages have inherent protection
2310 if( $this->isSpecialPage() ) {
2314 # Check regular protection levels
2315 foreach ( $restrictionTypes as $type ) {
2316 if ( $action == $type ||
$action == '' ) {
2317 $r = $this->getRestrictions( $type );
2318 foreach ( $wgRestrictionLevels as $level ) {
2319 if ( in_array( $level, $r ) && $level != '' ) {
2330 * Determines if $user is unable to edit this page because it has been protected
2331 * by $wgNamespaceProtection.
2333 * @param $user User object to check permissions
2336 public function isNamespaceProtected( User
$user ) {
2337 global $wgNamespaceProtection;
2339 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2340 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2341 if ( $right != '' && !$user->isAllowed( $right ) ) {
2350 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2352 * @return Bool If the page is subject to cascading restrictions.
2354 public function isCascadeProtected() {
2355 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2356 return ( $sources > 0 );
2360 * Cascading protection: Get the source of any cascading restrictions on this page.
2362 * @param $getPages Bool Whether or not to retrieve the actual pages
2363 * that the restrictions have come from.
2364 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2365 * have come, false for none, or true if such restrictions exist, but $getPages
2366 * was not set. The restriction array is an array of each type, each of which
2367 * contains a array of unique groups.
2369 public function getCascadeProtectionSources( $getPages = true ) {
2371 $pagerestrictions = array();
2373 if ( isset( $this->mCascadeSources
) && $getPages ) {
2374 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2375 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2376 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2379 wfProfileIn( __METHOD__
);
2381 $dbr = wfGetDB( DB_SLAVE
);
2383 if ( $this->getNamespace() == NS_FILE
) {
2384 $tables = array( 'imagelinks', 'page_restrictions' );
2385 $where_clauses = array(
2386 'il_to' => $this->getDBkey(),
2391 $tables = array( 'templatelinks', 'page_restrictions' );
2392 $where_clauses = array(
2393 'tl_namespace' => $this->getNamespace(),
2394 'tl_title' => $this->getDBkey(),
2401 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2402 'pr_expiry', 'pr_type', 'pr_level' );
2403 $where_clauses[] = 'page_id=pr_page';
2406 $cols = array( 'pr_expiry' );
2409 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2411 $sources = $getPages ?
array() : false;
2412 $now = wfTimestampNow();
2413 $purgeExpired = false;
2415 foreach ( $res as $row ) {
2416 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2417 if ( $expiry > $now ) {
2419 $page_id = $row->pr_page
;
2420 $page_ns = $row->page_namespace
;
2421 $page_title = $row->page_title
;
2422 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2423 # Add groups needed for each restriction type if its not already there
2424 # Make sure this restriction type still exists
2426 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2427 $pagerestrictions[$row->pr_type
] = array();
2430 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2431 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2432 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2438 // Trigger lazy purge of expired restrictions from the db
2439 $purgeExpired = true;
2442 if ( $purgeExpired ) {
2443 Title
::purgeExpiredRestrictions();
2447 $this->mCascadeSources
= $sources;
2448 $this->mCascadingRestrictions
= $pagerestrictions;
2450 $this->mHasCascadingRestrictions
= $sources;
2453 wfProfileOut( __METHOD__
);
2454 return array( $sources, $pagerestrictions );
2458 * Accessor/initialisation for mRestrictions
2460 * @param $action String action that permission needs to be checked for
2461 * @return Array of Strings the array of groups allowed to edit this article
2463 public function getRestrictions( $action ) {
2464 if ( !$this->mRestrictionsLoaded
) {
2465 $this->loadRestrictions();
2467 return isset( $this->mRestrictions
[$action] )
2468 ?
$this->mRestrictions
[$action]
2473 * Get the expiry time for the restriction against a given action
2476 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2477 * or not protected at all, or false if the action is not recognised.
2479 public function getRestrictionExpiry( $action ) {
2480 if ( !$this->mRestrictionsLoaded
) {
2481 $this->loadRestrictions();
2483 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2487 * Returns cascading restrictions for the current article
2491 function areRestrictionsCascading() {
2492 if ( !$this->mRestrictionsLoaded
) {
2493 $this->loadRestrictions();
2496 return $this->mCascadeRestriction
;
2500 * Loads a string into mRestrictions array
2502 * @param $res Resource restrictions as an SQL result.
2503 * @param $oldFashionedRestrictions String comma-separated list of page
2504 * restrictions from page table (pre 1.10)
2506 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2509 foreach ( $res as $row ) {
2513 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2517 * Compiles list of active page restrictions from both page table (pre 1.10)
2518 * and page_restrictions table for this existing page.
2519 * Public for usage by LiquidThreads.
2521 * @param $rows array of db result objects
2522 * @param $oldFashionedRestrictions string comma-separated list of page
2523 * restrictions from page table (pre 1.10)
2525 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2527 $dbr = wfGetDB( DB_SLAVE
);
2529 $restrictionTypes = $this->getRestrictionTypes();
2531 foreach ( $restrictionTypes as $type ) {
2532 $this->mRestrictions
[$type] = array();
2533 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2536 $this->mCascadeRestriction
= false;
2538 # Backwards-compatibility: also load the restrictions from the page record (old format).
2540 if ( $oldFashionedRestrictions === null ) {
2541 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2542 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2545 if ( $oldFashionedRestrictions != '' ) {
2547 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2548 $temp = explode( '=', trim( $restrict ) );
2549 if ( count( $temp ) == 1 ) {
2550 // old old format should be treated as edit/move restriction
2551 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2552 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2554 $restriction = trim( $temp[1] );
2555 if( $restriction != '' ) { //some old entries are empty
2556 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2561 $this->mOldRestrictions
= true;
2565 if ( count( $rows ) ) {
2566 # Current system - load second to make them override.
2567 $now = wfTimestampNow();
2568 $purgeExpired = false;
2570 # Cycle through all the restrictions.
2571 foreach ( $rows as $row ) {
2573 // Don't take care of restrictions types that aren't allowed
2574 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2577 // This code should be refactored, now that it's being used more generally,
2578 // But I don't really see any harm in leaving it in Block for now -werdna
2579 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2581 // Only apply the restrictions if they haven't expired!
2582 if ( !$expiry ||
$expiry > $now ) {
2583 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2584 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2586 $this->mCascadeRestriction |
= $row->pr_cascade
;
2588 // Trigger a lazy purge of expired restrictions
2589 $purgeExpired = true;
2593 if ( $purgeExpired ) {
2594 Title
::purgeExpiredRestrictions();
2598 $this->mRestrictionsLoaded
= true;
2602 * Load restrictions from the page_restrictions table
2604 * @param $oldFashionedRestrictions String comma-separated list of page
2605 * restrictions from page table (pre 1.10)
2607 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2609 if ( !$this->mRestrictionsLoaded
) {
2610 if ( $this->exists() ) {
2611 $dbr = wfGetDB( DB_SLAVE
);
2613 $res = $dbr->select(
2614 'page_restrictions',
2616 array( 'pr_page' => $this->getArticleID() ),
2620 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2622 $title_protection = $this->getTitleProtection();
2624 if ( $title_protection ) {
2625 $now = wfTimestampNow();
2626 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2628 if ( !$expiry ||
$expiry > $now ) {
2629 // Apply the restrictions
2630 $this->mRestrictionsExpiry
['create'] = $expiry;
2631 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2632 } else { // Get rid of the old restrictions
2633 Title
::purgeExpiredRestrictions();
2634 $this->mTitleProtection
= false;
2637 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2639 $this->mRestrictionsLoaded
= true;
2645 * Flush the protection cache in this object and force reload from the database.
2646 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2648 public function flushRestrictions() {
2649 $this->mRestrictionsLoaded
= false;
2650 $this->mTitleProtection
= null;
2654 * Purge expired restrictions from the page_restrictions table
2656 static function purgeExpiredRestrictions() {
2657 $dbw = wfGetDB( DB_MASTER
);
2659 'page_restrictions',
2660 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2666 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2672 * Does this have subpages? (Warning, usually requires an extra DB query.)
2676 public function hasSubpages() {
2677 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2682 # We dynamically add a member variable for the purpose of this method
2683 # alone to cache the result. There's no point in having it hanging
2684 # around uninitialized in every Title object; therefore we only add it
2685 # if needed and don't declare it statically.
2686 if ( isset( $this->mHasSubpages
) ) {
2687 return $this->mHasSubpages
;
2690 $subpages = $this->getSubpages( 1 );
2691 if ( $subpages instanceof TitleArray
) {
2692 return $this->mHasSubpages
= (bool)$subpages->count();
2694 return $this->mHasSubpages
= false;
2698 * Get all subpages of this page.
2700 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2701 * @return mixed TitleArray, or empty array if this page's namespace
2702 * doesn't allow subpages
2704 public function getSubpages( $limit = -1 ) {
2705 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2709 $dbr = wfGetDB( DB_SLAVE
);
2710 $conds['page_namespace'] = $this->getNamespace();
2711 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2713 if ( $limit > -1 ) {
2714 $options['LIMIT'] = $limit;
2716 return $this->mSubpages
= TitleArray
::newFromResult(
2717 $dbr->select( 'page',
2718 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2727 * Is there a version of this page in the deletion archive?
2729 * @return Int the number of archived revisions
2731 public function isDeleted() {
2732 if ( $this->getNamespace() < 0 ) {
2735 $dbr = wfGetDB( DB_SLAVE
);
2737 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2738 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2741 if ( $this->getNamespace() == NS_FILE
) {
2742 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2743 array( 'fa_name' => $this->getDBkey() ),
2752 * Is there a version of this page in the deletion archive?
2756 public function isDeletedQuick() {
2757 if ( $this->getNamespace() < 0 ) {
2760 $dbr = wfGetDB( DB_SLAVE
);
2761 $deleted = (bool)$dbr->selectField( 'archive', '1',
2762 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2765 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2766 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2767 array( 'fa_name' => $this->getDBkey() ),
2775 * Get the article ID for this Title from the link cache,
2776 * adding it if necessary
2778 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2780 * @return Int the ID
2782 public function getArticleID( $flags = 0 ) {
2783 if ( $this->getNamespace() < 0 ) {
2784 return $this->mArticleID
= 0;
2786 $linkCache = LinkCache
::singleton();
2787 if ( $flags & self
::GAID_FOR_UPDATE
) {
2788 $oldUpdate = $linkCache->forUpdate( true );
2789 $linkCache->clearLink( $this );
2790 $this->mArticleID
= $linkCache->addLinkObj( $this );
2791 $linkCache->forUpdate( $oldUpdate );
2793 if ( -1 == $this->mArticleID
) {
2794 $this->mArticleID
= $linkCache->addLinkObj( $this );
2797 return $this->mArticleID
;
2801 * Is this an article that is a redirect page?
2802 * Uses link cache, adding it if necessary
2804 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2807 public function isRedirect( $flags = 0 ) {
2808 if ( !is_null( $this->mRedirect
) ) {
2809 return $this->mRedirect
;
2811 # Calling getArticleID() loads the field from cache as needed
2812 if ( !$this->getArticleID( $flags ) ) {
2813 return $this->mRedirect
= false;
2816 $linkCache = LinkCache
::singleton();
2817 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2818 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #XXX breaks stuff #TODO: use exception
2820 $this->mRedirect
= (bool)$cached;
2822 return $this->mRedirect
;
2826 * What is the length of this page?
2827 * Uses link cache, adding it if necessary
2829 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2832 public function getLength( $flags = 0 ) {
2833 if ( $this->mLength
!= -1 ) {
2834 return $this->mLength
;
2836 # Calling getArticleID() loads the field from cache as needed
2837 if ( !$this->getArticleID( $flags ) ) {
2838 return $this->mLength
= 0;
2840 $linkCache = LinkCache
::singleton();
2841 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2842 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2844 $this->mLength
= intval( $cached );
2846 return $this->mLength
;
2850 * What is the page_latest field for this page?
2852 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2853 * @return Int or 0 if the page doesn't exist
2855 public function getLatestRevID( $flags = 0 ) {
2856 if ( $this->mLatestID
!== false ) {
2857 return intval( $this->mLatestID
);
2859 # Calling getArticleID() loads the field from cache as needed
2860 if ( !$this->getArticleID( $flags ) ) {
2861 return $this->mLatestID
= 0;
2863 $linkCache = LinkCache
::singleton();
2864 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2865 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2867 $this->mLatestID
= intval( $cached );
2869 return $this->mLatestID
;
2873 * This clears some fields in this object, and clears any associated
2874 * keys in the "bad links" section of the link cache.
2876 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2877 * loading of the new page_id. It's also called from
2878 * WikiPage::doDeleteArticle()
2880 * @param $newid Int the new Article ID
2882 public function resetArticleID( $newid ) {
2883 $linkCache = LinkCache
::singleton();
2884 $linkCache->clearLink( $this );
2886 if ( $newid === false ) {
2887 $this->mArticleID
= -1;
2889 $this->mArticleID
= intval( $newid );
2891 $this->mRestrictionsLoaded
= false;
2892 $this->mRestrictions
= array();
2893 $this->mRedirect
= null;
2894 $this->mLength
= -1;
2895 $this->mLatestID
= false;
2896 $this->mEstimateRevisions
= null;
2900 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2902 * @param $text String containing title to capitalize
2903 * @param $ns int namespace index, defaults to NS_MAIN
2904 * @return String containing capitalized title
2906 public static function capitalize( $text, $ns = NS_MAIN
) {
2909 if ( MWNamespace
::isCapitalized( $ns ) ) {
2910 return $wgContLang->ucfirst( $text );
2917 * Secure and split - main initialisation function for this object
2919 * Assumes that mDbkeyform has been set, and is urldecoded
2920 * and uses underscores, but not otherwise munged. This function
2921 * removes illegal characters, splits off the interwiki and
2922 * namespace prefixes, sets the other forms, and canonicalizes
2925 * @return Bool true on success
2927 private function secureAndSplit() {
2928 global $wgContLang, $wgLocalInterwiki;
2931 $this->mInterwiki
= $this->mFragment
= '';
2932 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2934 $dbkey = $this->mDbkeyform
;
2936 # Strip Unicode bidi override characters.
2937 # Sometimes they slip into cut-n-pasted page titles, where the
2938 # override chars get included in list displays.
2939 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2941 # Clean up whitespace
2942 # Note: use of the /u option on preg_replace here will cause
2943 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2944 # conveniently disabling them.
2945 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2946 $dbkey = trim( $dbkey, '_' );
2948 if ( $dbkey == '' ) {
2952 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2953 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2957 $this->mDbkeyform
= $dbkey;
2959 # Initial colon indicates main namespace rather than specified default
2960 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2961 if ( ':' == $dbkey[0] ) {
2962 $this->mNamespace
= NS_MAIN
;
2963 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2964 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2967 # Namespace or interwiki prefix
2969 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2972 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2974 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2975 # Ordinary namespace
2977 $this->mNamespace
= $ns;
2978 # For Talk:X pages, check if X has a "namespace" prefix
2979 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2980 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2981 # Disallow Talk:File:x type titles...
2983 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2984 # Disallow Talk:Interwiki:x type titles...
2988 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2989 if ( !$firstPass ) {
2990 # Can't make a local interwiki link to an interwiki link.
2991 # That's just crazy!
2997 $this->mInterwiki
= $wgContLang->lc( $p );
2999 # Redundant interwiki prefix to the local wiki
3000 if ( $wgLocalInterwiki !== false
3001 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3003 if ( $dbkey == '' ) {
3004 # Can't have an empty self-link
3007 $this->mInterwiki
= '';
3009 # Do another namespace split...
3013 # If there's an initial colon after the interwiki, that also
3014 # resets the default namespace
3015 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3016 $this->mNamespace
= NS_MAIN
;
3017 $dbkey = substr( $dbkey, 1 );
3020 # If there's no recognized interwiki or namespace,
3021 # then let the colon expression be part of the title.
3026 # We already know that some pages won't be in the database!
3027 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3028 $this->mArticleID
= 0;
3030 $fragment = strstr( $dbkey, '#' );
3031 if ( false !== $fragment ) {
3032 $this->setFragment( $fragment );
3033 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3034 # remove whitespace again: prevents "Foo_bar_#"
3035 # becoming "Foo_bar_"
3036 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3039 # Reject illegal characters.
3040 $rxTc = self
::getTitleInvalidRegex();
3041 if ( preg_match( $rxTc, $dbkey ) ) {
3045 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3046 # reachable due to the way web browsers deal with 'relative' URLs.
3047 # Also, they conflict with subpage syntax. Forbid them explicitly.
3048 if ( strpos( $dbkey, '.' ) !== false &&
3049 ( $dbkey === '.' ||
$dbkey === '..' ||
3050 strpos( $dbkey, './' ) === 0 ||
3051 strpos( $dbkey, '../' ) === 0 ||
3052 strpos( $dbkey, '/./' ) !== false ||
3053 strpos( $dbkey, '/../' ) !== false ||
3054 substr( $dbkey, -2 ) == '/.' ||
3055 substr( $dbkey, -3 ) == '/..' ) )
3060 # Magic tilde sequences? Nu-uh!
3061 if ( strpos( $dbkey, '~~~' ) !== false ) {
3065 # Limit the size of titles to 255 bytes. This is typically the size of the
3066 # underlying database field. We make an exception for special pages, which
3067 # don't need to be stored in the database, and may edge over 255 bytes due
3068 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3069 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3070 strlen( $dbkey ) > 512 )
3075 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3076 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3077 # other site might be case-sensitive.
3078 $this->mUserCaseDBKey
= $dbkey;
3079 if ( $this->mInterwiki
== '' ) {
3080 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3083 # Can't make a link to a namespace alone... "empty" local links can only be
3084 # self-links with a fragment identifier.
3085 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3089 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3090 // IP names are not allowed for accounts, and can only be referring to
3091 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3092 // there are numerous ways to present the same IP. Having sp:contribs scan
3093 // them all is silly and having some show the edits and others not is
3094 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3095 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3096 ? IP
::sanitizeIP( $dbkey )
3099 // Any remaining initial :s are illegal.
3100 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3105 $this->mDbkeyform
= $dbkey;
3106 $this->mUrlform
= wfUrlencode( $dbkey );
3108 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3114 * Get an array of Title objects linking to this Title
3115 * Also stores the IDs in the link cache.
3117 * WARNING: do not use this function on arbitrary user-supplied titles!
3118 * On heavily-used templates it will max out the memory.
3120 * @param $options Array: may be FOR UPDATE
3121 * @param $table String: table name
3122 * @param $prefix String: fields prefix
3123 * @return Array of Title objects linking here
3125 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3126 if ( count( $options ) > 0 ) {
3127 $db = wfGetDB( DB_MASTER
);
3129 $db = wfGetDB( DB_SLAVE
);
3133 array( 'page', $table ),
3134 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3136 "{$prefix}_from=page_id",
3137 "{$prefix}_namespace" => $this->getNamespace(),
3138 "{$prefix}_title" => $this->getDBkey() ),
3144 if ( $res->numRows() ) {
3145 $linkCache = LinkCache
::singleton();
3146 foreach ( $res as $row ) {
3147 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3149 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3150 $retVal[] = $titleObj;
3158 * Get an array of Title objects using this Title as a template
3159 * Also stores the IDs in the link cache.
3161 * WARNING: do not use this function on arbitrary user-supplied titles!
3162 * On heavily-used templates it will max out the memory.
3164 * @param $options Array: may be FOR UPDATE
3165 * @return Array of Title the Title objects linking here
3167 public function getTemplateLinksTo( $options = array() ) {
3168 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3172 * Get an array of Title objects linked from this Title
3173 * Also stores the IDs in the link cache.
3175 * WARNING: do not use this function on arbitrary user-supplied titles!
3176 * On heavily-used templates it will max out the memory.
3178 * @param $options Array: may be FOR UPDATE
3179 * @param $table String: table name
3180 * @param $prefix String: fields prefix
3181 * @return Array of Title objects linking here
3183 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3184 $id = $this->getArticleID();
3186 # If the page doesn't exist; there can't be any link from this page
3191 if ( count( $options ) > 0 ) {
3192 $db = wfGetDB( DB_MASTER
);
3194 $db = wfGetDB( DB_SLAVE
);
3197 $namespaceFiled = "{$prefix}_namespace";
3198 $titleField = "{$prefix}_title";
3201 array( $table, 'page' ),
3202 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3203 array( "{$prefix}_from" => $id ),
3206 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3210 if ( $res->numRows() ) {
3211 $linkCache = LinkCache
::singleton();
3212 foreach ( $res as $row ) {
3213 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3215 if ( $row->page_id
) {
3216 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3218 $linkCache->addBadLinkObj( $titleObj );
3220 $retVal[] = $titleObj;
3228 * Get an array of Title objects used on this Title as a template
3229 * Also stores the IDs in the link cache.
3231 * WARNING: do not use this function on arbitrary user-supplied titles!
3232 * On heavily-used templates it will max out the memory.
3234 * @param $options Array: may be FOR UPDATE
3235 * @return Array of Title the Title objects used here
3237 public function getTemplateLinksFrom( $options = array() ) {
3238 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3242 * Get an array of Title objects referring to non-existent articles linked from this page
3244 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3245 * @return Array of Title the Title objects
3247 public function getBrokenLinksFrom() {
3248 if ( $this->getArticleID() == 0 ) {
3249 # All links from article ID 0 are false positives
3253 $dbr = wfGetDB( DB_SLAVE
);
3254 $res = $dbr->select(
3255 array( 'page', 'pagelinks' ),
3256 array( 'pl_namespace', 'pl_title' ),
3258 'pl_from' => $this->getArticleID(),
3259 'page_namespace IS NULL'
3261 __METHOD__
, array(),
3265 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3271 foreach ( $res as $row ) {
3272 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3279 * Get a list of URLs to purge from the Squid cache when this
3282 * @return Array of String the URLs
3284 public function getSquidURLs() {
3288 $this->getInternalURL(),
3289 $this->getInternalURL( 'action=history' )
3292 // purge variant urls as well
3293 if ( $wgContLang->hasVariants() ) {
3294 $variants = $wgContLang->getVariants();
3295 foreach ( $variants as $vCode ) {
3296 $urls[] = $this->getInternalURL( '', $vCode );
3304 * Purge all applicable Squid URLs
3306 public function purgeSquid() {
3308 if ( $wgUseSquid ) {
3309 $urls = $this->getSquidURLs();
3310 $u = new SquidUpdate( $urls );
3316 * Move this page without authentication
3318 * @param $nt Title the new page Title
3319 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3321 public function moveNoAuth( &$nt ) {
3322 return $this->moveTo( $nt, false );
3326 * Check whether a given move operation would be valid.
3327 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3329 * @param $nt Title the new title
3330 * @param $auth Bool indicates whether $wgUser's permissions
3332 * @param $reason String is the log summary of the move, used for spam checking
3333 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3335 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3340 // Normally we'd add this to $errors, but we'll get
3341 // lots of syntax errors if $nt is not an object
3342 return array( array( 'badtitletext' ) );
3344 if ( $this->equals( $nt ) ) {
3345 $errors[] = array( 'selfmove' );
3347 if ( !$this->isMovable() ) {
3348 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3350 if ( $nt->getInterwiki() != '' ) {
3351 $errors[] = array( 'immobile-target-namespace-iw' );
3353 if ( !$nt->isMovable() ) {
3354 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3357 $oldid = $this->getArticleID();
3358 $newid = $nt->getArticleID();
3360 if ( strlen( $nt->getDBkey() ) < 1 ) {
3361 $errors[] = array( 'articleexists' );
3363 if ( ( $this->getDBkey() == '' ) ||
3365 ( $nt->getDBkey() == '' ) ) {
3366 $errors[] = array( 'badarticleerror' );
3369 // Image-specific checks
3370 if ( $this->getNamespace() == NS_FILE
) {
3371 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3374 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3375 $errors[] = array( 'nonfile-cannot-move-to-file' );
3379 $errors = wfMergeErrorArrays( $errors,
3380 $this->getUserPermissionsErrors( 'move', $wgUser ),
3381 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3382 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3383 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3386 $match = EditPage
::matchSummarySpamRegex( $reason );
3387 if ( $match !== false ) {
3388 // This is kind of lame, won't display nice
3389 $errors[] = array( 'spamprotectiontext' );
3393 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3394 $errors[] = array( 'hookaborted', $err );
3397 # The move is allowed only if (1) the target doesn't exist, or
3398 # (2) the target is a redirect to the source, and has no history
3399 # (so we can undo bad moves right after they're done).
3401 if ( 0 != $newid ) { # Target exists; check for validity
3402 if ( !$this->isValidMoveTarget( $nt ) ) {
3403 $errors[] = array( 'articleexists' );
3406 $tp = $nt->getTitleProtection();
3407 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3408 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3409 $errors[] = array( 'cantmove-titleprotected' );
3412 if ( empty( $errors ) ) {
3419 * Check if the requested move target is a valid file move target
3420 * @param Title $nt Target title
3421 * @return array List of errors
3423 protected function validateFileMoveOperation( $nt ) {
3428 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3430 $file = wfLocalFile( $this );
3431 if ( $file->exists() ) {
3432 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3433 $errors[] = array( 'imageinvalidfilename' );
3435 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3436 $errors[] = array( 'imagetypemismatch' );
3440 if ( $nt->getNamespace() != NS_FILE
) {
3441 $errors[] = array( 'imagenocrossnamespace' );
3442 // From here we want to do checks on a file object, so if we can't
3443 // create one, we must return.
3447 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3449 $destFile = wfLocalFile( $nt );
3450 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3451 $errors[] = array( 'file-exists-sharedrepo' );
3458 * Move a title to a new location
3460 * @param $nt Title the new title
3461 * @param $auth Bool indicates whether $wgUser's permissions
3463 * @param $reason String the reason for the move
3464 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3465 * Ignored if the user doesn't have the suppressredirect right.
3466 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3468 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3470 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3471 if ( is_array( $err ) ) {
3472 // Auto-block user's IP if the account was "hard" blocked
3473 $wgUser->spreadAnyEditBlock();
3477 // If it is a file, move it first.
3478 // It is done before all other moving stuff is done because it's hard to revert.
3479 $dbw = wfGetDB( DB_MASTER
);
3480 if ( $this->getNamespace() == NS_FILE
) {
3481 $file = wfLocalFile( $this );
3482 if ( $file->exists() ) {
3483 $status = $file->move( $nt );
3484 if ( !$status->isOk() ) {
3485 return $status->getErrorsArray();
3488 // Clear RepoGroup process cache
3489 RepoGroup
::singleton()->clearCache( $this );
3490 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3493 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3494 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3495 $protected = $this->isProtected();
3497 // Do the actual move
3498 $this->moveToInternal( $nt, $reason, $createRedirect );
3500 // Refresh the sortkey for this row. Be careful to avoid resetting
3501 // cl_timestamp, which may disturb time-based lists on some sites.
3502 $prefixes = $dbw->select(
3504 array( 'cl_sortkey_prefix', 'cl_to' ),
3505 array( 'cl_from' => $pageid ),
3508 foreach ( $prefixes as $prefixRow ) {
3509 $prefix = $prefixRow->cl_sortkey_prefix
;
3510 $catTo = $prefixRow->cl_to
;
3511 $dbw->update( 'categorylinks',
3513 'cl_sortkey' => Collation
::singleton()->getSortKey(
3514 $nt->getCategorySortkey( $prefix ) ),
3515 'cl_timestamp=cl_timestamp' ),
3517 'cl_from' => $pageid,
3518 'cl_to' => $catTo ),
3523 $redirid = $this->getArticleID();
3526 # Protect the redirect title as the title used to be...
3527 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3529 'pr_page' => $redirid,
3530 'pr_type' => 'pr_type',
3531 'pr_level' => 'pr_level',
3532 'pr_cascade' => 'pr_cascade',
3533 'pr_user' => 'pr_user',
3534 'pr_expiry' => 'pr_expiry'
3536 array( 'pr_page' => $pageid ),
3540 # Update the protection log
3541 $log = new LogPage( 'protect' );
3542 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3544 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3546 // @todo FIXME: $params?
3547 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3551 $oldnamespace = $this->getNamespace() & ~
1;
3552 $newnamespace = $nt->getNamespace() & ~
1;
3553 $oldtitle = $this->getDBkey();
3554 $newtitle = $nt->getDBkey();
3556 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3557 WatchedItem
::duplicateEntries( $this, $nt );
3560 $dbw->commit( __METHOD__
);
3562 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3567 * Move page to a title which is either a redirect to the
3568 * source page or nonexistent
3570 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3571 * @param $reason String The reason for the move
3572 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3573 * if the user doesn't have the suppressredirect right
3574 * @throws MWException
3576 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3577 global $wgUser, $wgContLang;
3579 if ( $nt->exists() ) {
3580 $moveOverRedirect = true;
3581 $logType = 'move_redir';
3583 $moveOverRedirect = false;
3587 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3589 $logEntry = new ManualLogEntry( 'move', $logType );
3590 $logEntry->setPerformer( $wgUser );
3591 $logEntry->setTarget( $this );
3592 $logEntry->setComment( $reason );
3593 $logEntry->setParameters( array(
3594 '4::target' => $nt->getPrefixedText(),
3595 '5::noredir' => $redirectSuppressed ?
'1': '0',
3598 $formatter = LogFormatter
::newFromEntry( $logEntry );
3599 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3600 $comment = $formatter->getPlainActionText();
3602 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3604 # Truncate for whole multibyte characters.
3605 $comment = $wgContLang->truncate( $comment, 255 );
3607 $oldid = $this->getArticleID();
3609 $dbw = wfGetDB( DB_MASTER
);
3611 $newpage = WikiPage
::factory( $nt );
3613 if ( $moveOverRedirect ) {
3614 $newid = $nt->getArticleID();
3616 # Delete the old redirect. We don't save it to history since
3617 # by definition if we've got here it's rather uninteresting.
3618 # We have to remove it so that the next step doesn't trigger
3619 # a conflict on the unique namespace+title index...
3620 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3622 $newpage->doDeleteUpdates( $newid );
3625 # Save a null revision in the page's history notifying of the move
3626 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3627 if ( !is_object( $nullRevision ) ) {
3628 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3630 $nullRevId = $nullRevision->insertOn( $dbw );
3632 # Change the name of the target page:
3633 $dbw->update( 'page',
3635 'page_namespace' => $nt->getNamespace(),
3636 'page_title' => $nt->getDBkey(),
3638 /* WHERE */ array( 'page_id' => $oldid ),
3642 $this->resetArticleID( 0 );
3643 $nt->resetArticleID( $oldid );
3645 $newpage->updateRevisionOn( $dbw, $nullRevision );
3647 wfRunHooks( 'NewRevisionFromEditComplete',
3648 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3650 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3652 if ( !$moveOverRedirect ) {
3653 WikiPage
::onArticleCreate( $nt );
3656 # Recreate the redirect, this time in the other direction.
3657 if ( $redirectSuppressed ) {
3658 WikiPage
::onArticleDelete( $this );
3660 $mwRedir = MagicWord
::get( 'redirect' );
3661 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3662 $redirectArticle = WikiPage
::factory( $this );
3663 $newid = $redirectArticle->insertOn( $dbw );
3664 if ( $newid ) { // sanity
3665 $redirectRevision = new Revision( array(
3667 'comment' => $comment,
3668 'text' => $redirectText ) );
3669 $redirectRevision->insertOn( $dbw );
3670 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3672 wfRunHooks( 'NewRevisionFromEditComplete',
3673 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3675 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3680 $logid = $logEntry->insert();
3681 $logEntry->publish( $logid );
3685 * Move this page's subpages to be subpages of $nt
3687 * @param $nt Title Move target
3688 * @param $auth bool Whether $wgUser's permissions should be checked
3689 * @param $reason string The reason for the move
3690 * @param $createRedirect bool Whether to create redirects from the old subpages to
3691 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3692 * @return mixed array with old page titles as keys, and strings (new page titles) or
3693 * arrays (errors) as values, or an error array with numeric indices if no pages
3696 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3697 global $wgMaximumMovedPages;
3698 // Check permissions
3699 if ( !$this->userCan( 'move-subpages' ) ) {
3700 return array( 'cant-move-subpages' );
3702 // Do the source and target namespaces support subpages?
3703 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3704 return array( 'namespace-nosubpages',
3705 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3707 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3708 return array( 'namespace-nosubpages',
3709 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3712 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3715 foreach ( $subpages as $oldSubpage ) {
3717 if ( $count > $wgMaximumMovedPages ) {
3718 $retval[$oldSubpage->getPrefixedTitle()] =
3719 array( 'movepage-max-pages',
3720 $wgMaximumMovedPages );
3724 // We don't know whether this function was called before
3725 // or after moving the root page, so check both
3727 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3728 $oldSubpage->getArticleID() == $nt->getArticleID() )
3730 // When moving a page to a subpage of itself,
3731 // don't move it twice
3734 $newPageName = preg_replace(
3735 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3736 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3737 $oldSubpage->getDBkey() );
3738 if ( $oldSubpage->isTalkPage() ) {
3739 $newNs = $nt->getTalkPage()->getNamespace();
3741 $newNs = $nt->getSubjectPage()->getNamespace();
3743 # Bug 14385: we need makeTitleSafe because the new page names may
3744 # be longer than 255 characters.
3745 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3747 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3748 if ( $success === true ) {
3749 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3751 $retval[$oldSubpage->getPrefixedText()] = $success;
3758 * Checks if this page is just a one-rev redirect.
3759 * Adds lock, so don't use just for light purposes.
3763 public function isSingleRevRedirect() {
3764 $dbw = wfGetDB( DB_MASTER
);
3766 $row = $dbw->selectRow( 'page',
3767 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3770 array( 'FOR UPDATE' )
3772 # Cache some fields we may want
3773 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3774 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3775 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3776 if ( !$this->mRedirect
) {
3779 # Does the article have a history?
3780 $row = $dbw->selectField( array( 'page', 'revision' ),
3782 array( 'page_namespace' => $this->getNamespace(),
3783 'page_title' => $this->getDBkey(),
3785 'page_latest != rev_id'
3788 array( 'FOR UPDATE' )
3790 # Return true if there was no history
3791 return ( $row === false );
3795 * Checks if $this can be moved to a given Title
3796 * - Selects for update, so don't call it unless you mean business
3798 * @param $nt Title the new title to check
3801 public function isValidMoveTarget( $nt ) {
3802 # Is it an existing file?
3803 if ( $nt->getNamespace() == NS_FILE
) {
3804 $file = wfLocalFile( $nt );
3805 if ( $file->exists() ) {
3806 wfDebug( __METHOD__
. ": file exists\n" );
3810 # Is it a redirect with no history?
3811 if ( !$nt->isSingleRevRedirect() ) {
3812 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3815 # Get the article text
3816 $rev = Revision
::newFromTitle( $nt );
3817 if( !is_object( $rev ) ){
3820 $content = $rev->getContent();
3821 # Does the redirect point to the source?
3822 # Or is it a broken self-redirect, usually caused by namespace collisions?
3823 $redirTitle = $content->getRedirectTarget();
3825 if ( $redirTitle ) {
3826 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3827 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3828 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3834 # Fail safe (not a redirect after all. strange.)
3835 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() . " is a redirect, but it doesn't contain a valid redirect.\n" );
3841 * Get categories to which this Title belongs and return an array of
3842 * categories' names.
3844 * @return Array of parents in the form:
3845 * $parent => $currentarticle
3847 public function getParentCategories() {
3852 $titleKey = $this->getArticleID();
3854 if ( $titleKey === 0 ) {
3858 $dbr = wfGetDB( DB_SLAVE
);
3860 $res = $dbr->select( 'categorylinks', '*',
3862 'cl_from' => $titleKey,
3868 if ( $dbr->numRows( $res ) > 0 ) {
3869 foreach ( $res as $row ) {
3870 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3871 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3878 * Get a tree of parent categories
3880 * @param $children Array with the children in the keys, to check for circular refs
3881 * @return Array Tree of parent categories
3883 public function getParentCategoryTree( $children = array() ) {
3885 $parents = $this->getParentCategories();
3888 foreach ( $parents as $parent => $current ) {
3889 if ( array_key_exists( $parent, $children ) ) {
3890 # Circular reference
3891 $stack[$parent] = array();
3893 $nt = Title
::newFromText( $parent );
3895 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3905 * Get an associative array for selecting this title from
3908 * @return Array suitable for the $where parameter of DB::select()
3910 public function pageCond() {
3911 if ( $this->mArticleID
> 0 ) {
3912 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3913 return array( 'page_id' => $this->mArticleID
);
3915 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3920 * Get the revision ID of the previous revision
3922 * @param $revId Int Revision ID. Get the revision that was before this one.
3923 * @param $flags Int Title::GAID_FOR_UPDATE
3924 * @return Int|Bool Old revision ID, or FALSE if none exists
3926 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3927 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3928 $revId = $db->selectField( 'revision', 'rev_id',
3930 'rev_page' => $this->getArticleID( $flags ),
3931 'rev_id < ' . intval( $revId )
3934 array( 'ORDER BY' => 'rev_id DESC' )
3937 if ( $revId === false ) {
3940 return intval( $revId );
3945 * Get the revision ID of the next revision
3947 * @param $revId Int Revision ID. Get the revision that was after this one.
3948 * @param $flags Int Title::GAID_FOR_UPDATE
3949 * @return Int|Bool Next revision ID, or FALSE if none exists
3951 public function getNextRevisionID( $revId, $flags = 0 ) {
3952 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3953 $revId = $db->selectField( 'revision', 'rev_id',
3955 'rev_page' => $this->getArticleID( $flags ),
3956 'rev_id > ' . intval( $revId )
3959 array( 'ORDER BY' => 'rev_id' )
3962 if ( $revId === false ) {
3965 return intval( $revId );
3970 * Get the first revision of the page
3972 * @param $flags Int Title::GAID_FOR_UPDATE
3973 * @return Revision|Null if page doesn't exist
3975 public function getFirstRevision( $flags = 0 ) {
3976 $pageId = $this->getArticleID( $flags );
3978 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3979 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3980 array( 'rev_page' => $pageId ),
3982 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3985 return new Revision( $row );
3992 * Get the oldest revision timestamp of this page
3994 * @param $flags Int Title::GAID_FOR_UPDATE
3995 * @return String: MW timestamp
3997 public function getEarliestRevTime( $flags = 0 ) {
3998 $rev = $this->getFirstRevision( $flags );
3999 return $rev ?
$rev->getTimestamp() : null;
4003 * Check if this is a new page
4007 public function isNewPage() {
4008 $dbr = wfGetDB( DB_SLAVE
);
4009 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4013 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4017 public function isBigDeletion() {
4018 global $wgDeleteRevisionsLimit;
4020 if ( !$wgDeleteRevisionsLimit ) {
4024 $revCount = $this->estimateRevisionCount();
4025 return $revCount > $wgDeleteRevisionsLimit;
4029 * Get the approximate revision count of this page.
4033 public function estimateRevisionCount() {
4034 if ( !$this->exists() ) {
4038 if ( $this->mEstimateRevisions
=== null ) {
4039 $dbr = wfGetDB( DB_SLAVE
);
4040 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4041 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4044 return $this->mEstimateRevisions
;
4048 * Get the number of revisions between the given revision.
4049 * Used for diffs and other things that really need it.
4051 * @param $old int|Revision Old revision or rev ID (first before range)
4052 * @param $new int|Revision New revision or rev ID (first after range)
4053 * @return Int Number of revisions between these revisions.
4055 public function countRevisionsBetween( $old, $new ) {
4056 if ( !( $old instanceof Revision
) ) {
4057 $old = Revision
::newFromTitle( $this, (int)$old );
4059 if ( !( $new instanceof Revision
) ) {
4060 $new = Revision
::newFromTitle( $this, (int)$new );
4062 if ( !$old ||
!$new ) {
4063 return 0; // nothing to compare
4065 $dbr = wfGetDB( DB_SLAVE
);
4066 return (int)$dbr->selectField( 'revision', 'count(*)',
4068 'rev_page' => $this->getArticleID(),
4069 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4070 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4077 * Get the number of authors between the given revision IDs.
4078 * Used for diffs and other things that really need it.
4080 * @param $old int|Revision Old revision or rev ID (first before range)
4081 * @param $new int|Revision New revision or rev ID (first after range)
4082 * @param $limit Int Maximum number of authors
4083 * @return Int Number of revision authors between these revisions.
4085 public function countAuthorsBetween( $old, $new, $limit ) {
4086 if ( !( $old instanceof Revision
) ) {
4087 $old = Revision
::newFromTitle( $this, (int)$old );
4089 if ( !( $new instanceof Revision
) ) {
4090 $new = Revision
::newFromTitle( $this, (int)$new );
4092 if ( !$old ||
!$new ) {
4093 return 0; // nothing to compare
4095 $dbr = wfGetDB( DB_SLAVE
);
4096 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4098 'rev_page' => $this->getArticleID(),
4099 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4100 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4102 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4104 return (int)$dbr->numRows( $res );
4108 * Compare with another title.
4110 * @param $title Title
4113 public function equals( Title
$title ) {
4114 // Note: === is necessary for proper matching of number-like titles.
4115 return $this->getInterwiki() === $title->getInterwiki()
4116 && $this->getNamespace() == $title->getNamespace()
4117 && $this->getDBkey() === $title->getDBkey();
4121 * Check if this title is a subpage of another title
4123 * @param $title Title
4126 public function isSubpageOf( Title
$title ) {
4127 return $this->getInterwiki() === $title->getInterwiki()
4128 && $this->getNamespace() == $title->getNamespace()
4129 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4133 * Check if page exists. For historical reasons, this function simply
4134 * checks for the existence of the title in the page table, and will
4135 * thus return false for interwiki links, special pages and the like.
4136 * If you want to know if a title can be meaningfully viewed, you should
4137 * probably call the isKnown() method instead.
4141 public function exists() {
4142 return $this->getArticleID() != 0;
4146 * Should links to this title be shown as potentially viewable (i.e. as
4147 * "bluelinks"), even if there's no record by this title in the page
4150 * This function is semi-deprecated for public use, as well as somewhat
4151 * misleadingly named. You probably just want to call isKnown(), which
4152 * calls this function internally.
4154 * (ISSUE: Most of these checks are cheap, but the file existence check
4155 * can potentially be quite expensive. Including it here fixes a lot of
4156 * existing code, but we might want to add an optional parameter to skip
4157 * it and any other expensive checks.)
4161 public function isAlwaysKnown() {
4165 * Allows overriding default behaviour for determining if a page exists.
4166 * If $isKnown is kept as null, regular checks happen. If it's
4167 * a boolean, this value is returned by the isKnown method.
4171 * @param Title $title
4172 * @param boolean|null $isKnown
4174 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4176 if ( !is_null( $isKnown ) ) {
4180 if ( $this->mInterwiki
!= '' ) {
4181 return true; // any interwiki link might be viewable, for all we know
4184 switch( $this->mNamespace
) {
4187 // file exists, possibly in a foreign repo
4188 return (bool)wfFindFile( $this );
4190 // valid special page
4191 return SpecialPageFactory
::exists( $this->getDBkey() );
4193 // selflink, possibly with fragment
4194 return $this->mDbkeyform
== '';
4196 // known system message
4197 return $this->hasSourceText() !== false;
4204 * Does this title refer to a page that can (or might) be meaningfully
4205 * viewed? In particular, this function may be used to determine if
4206 * links to the title should be rendered as "bluelinks" (as opposed to
4207 * "redlinks" to non-existent pages).
4208 * Adding something else to this function will cause inconsistency
4209 * since LinkHolderArray calls isAlwaysKnown() and does its own
4210 * page existence check.
4214 public function isKnown() {
4215 return $this->isAlwaysKnown() ||
$this->exists();
4219 * Does this page have source text?
4223 public function hasSourceText() {
4224 if ( $this->exists() ) {
4228 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4229 // If the page doesn't exist but is a known system message, default
4230 // message content will be displayed, same for language subpages-
4231 // Use always content language to avoid loading hundreds of languages
4232 // to get the link color.
4234 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4235 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4236 return $message->exists();
4243 * Get the default message text or false if the message doesn't exist
4245 * @return String or false
4247 public function getDefaultMessageText() {
4250 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4254 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4255 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4257 if ( $message->exists() ) {
4258 return $message->plain();
4265 * Updates page_touched for this page; called from LinksUpdate.php
4267 * @return Bool true if the update succeded
4269 public function invalidateCache() {
4270 if ( wfReadOnly() ) {
4273 $dbw = wfGetDB( DB_MASTER
);
4274 $success = $dbw->update(
4276 array( 'page_touched' => $dbw->timestamp() ),
4280 HTMLFileCache
::clearFileCache( $this );
4285 * Update page_touched timestamps and send squid purge messages for
4286 * pages linking to this title. May be sent to the job queue depending
4287 * on the number of links. Typically called on create and delete.
4289 public function touchLinks() {
4290 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4293 if ( $this->getNamespace() == NS_CATEGORY
) {
4294 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4300 * Get the last touched timestamp
4302 * @param $db DatabaseBase: optional db
4303 * @return String last-touched timestamp
4305 public function getTouched( $db = null ) {
4306 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4307 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4312 * Get the timestamp when this page was updated since the user last saw it.
4315 * @return String|Null
4317 public function getNotificationTimestamp( $user = null ) {
4318 global $wgUser, $wgShowUpdatedMarker;
4319 // Assume current user if none given
4323 // Check cache first
4324 $uid = $user->getId();
4325 // avoid isset here, as it'll return false for null entries
4326 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4327 return $this->mNotificationTimestamp
[$uid];
4329 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4330 return $this->mNotificationTimestamp
[$uid] = false;
4332 // Don't cache too much!
4333 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4334 $this->mNotificationTimestamp
= array();
4336 $dbr = wfGetDB( DB_SLAVE
);
4337 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4338 'wl_notificationtimestamp',
4340 'wl_user' => $user->getId(),
4341 'wl_namespace' => $this->getNamespace(),
4342 'wl_title' => $this->getDBkey(),
4346 return $this->mNotificationTimestamp
[$uid];
4350 * Generate strings used for xml 'id' names in monobook tabs
4352 * @param $prepend string defaults to 'nstab-'
4353 * @return String XML 'id' name
4355 public function getNamespaceKey( $prepend = 'nstab-' ) {
4357 // Gets the subject namespace if this title
4358 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4359 // Checks if cononical namespace name exists for namespace
4360 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4361 // Uses canonical namespace name
4362 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4364 // Uses text of namespace
4365 $namespaceKey = $this->getSubjectNsText();
4367 // Makes namespace key lowercase
4368 $namespaceKey = $wgContLang->lc( $namespaceKey );
4370 if ( $namespaceKey == '' ) {
4371 $namespaceKey = 'main';
4373 // Changes file to image for backwards compatibility
4374 if ( $namespaceKey == 'file' ) {
4375 $namespaceKey = 'image';
4377 return $prepend . $namespaceKey;
4381 * Get all extant redirects to this Title
4383 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4384 * @return Array of Title redirects to this title
4386 public function getRedirectsHere( $ns = null ) {
4389 $dbr = wfGetDB( DB_SLAVE
);
4391 'rd_namespace' => $this->getNamespace(),
4392 'rd_title' => $this->getDBkey(),
4395 if ( !is_null( $ns ) ) {
4396 $where['page_namespace'] = $ns;
4399 $res = $dbr->select(
4400 array( 'redirect', 'page' ),
4401 array( 'page_namespace', 'page_title' ),
4406 foreach ( $res as $row ) {
4407 $redirs[] = self
::newFromRow( $row );
4413 * Check if this Title is a valid redirect target
4417 public function isValidRedirectTarget() {
4418 global $wgInvalidRedirectTargets;
4420 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4421 if ( $this->isSpecial( 'Userlogout' ) ) {
4425 foreach ( $wgInvalidRedirectTargets as $target ) {
4426 if ( $this->isSpecial( $target ) ) {
4435 * Get a backlink cache object
4437 * @return BacklinkCache
4439 function getBacklinkCache() {
4440 if ( is_null( $this->mBacklinkCache
) ) {
4441 $this->mBacklinkCache
= new BacklinkCache( $this );
4443 return $this->mBacklinkCache
;
4447 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4451 public function canUseNoindex() {
4452 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4454 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4455 ?
$wgContentNamespaces
4456 : $wgExemptFromUserRobotsControl;
4458 return !in_array( $this->mNamespace
, $bannedNamespaces );
4463 * Returns the raw sort key to be used for categories, with the specified
4464 * prefix. This will be fed to Collation::getSortKey() to get a
4465 * binary sortkey that can be used for actual sorting.
4467 * @param $prefix string The prefix to be used, specified using
4468 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4472 public function getCategorySortkey( $prefix = '' ) {
4473 $unprefixed = $this->getText();
4475 // Anything that uses this hook should only depend
4476 // on the Title object passed in, and should probably
4477 // tell the users to run updateCollations.php --force
4478 // in order to re-sort existing category relations.
4479 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4480 if ( $prefix !== '' ) {
4481 # Separate with a line feed, so the unprefixed part is only used as
4482 # a tiebreaker when two pages have the exact same prefix.
4483 # In UCA, tab is the only character that can sort above LF
4484 # so we strip both of them from the original prefix.
4485 $prefix = strtr( $prefix, "\n\t", ' ' );
4486 return "$prefix\n$unprefixed";
4492 * Get the language in which the content of this page is written.
4493 * Defaults to $wgContLang, but in certain cases it can be e.g.
4494 * $wgLang (such as special pages, which are in the user language).
4499 public function getPageLanguage() {
4501 if ( $this->isSpecialPage() ) {
4502 // special pages are in the user language
4504 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4505 // css/js should always be LTR and is, in fact, English
4506 return wfGetLangObj( 'en' );
4507 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4508 // Parse mediawiki messages with correct target language
4509 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4510 return wfGetLangObj( $lang );
4513 // If nothing special, it should be in the wiki content language
4514 $pageLang = $wgContLang;
4515 // Hook at the end because we don't want to override the above stuff
4516 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4517 return wfGetLangObj( $pageLang );