5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
67 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
68 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
69 var $mOldRestrictions = false;
70 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
71 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
72 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
73 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
74 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
75 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
76 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
77 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
78 # Don't change the following default, NS_MAIN is hardcoded in several
79 # places. See bug 696.
80 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
81 # Zero except in {{transclusion}} tags
82 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
83 var $mLength = -1; // /< The page length, 0 for special pages
84 var $mRedirect = null; // /< Is the article at this title a redirect?
85 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
86 var $mBacklinkCache = null; // /< Cache of links to this title
93 /*protected*/ function __construct() { }
96 * Create a new Title from a prefixed DB key
98 * @param $key String the database key, which has underscores
99 * instead of spaces, possibly including namespace and
101 * @return Title, or NULL on an error
103 public static function newFromDBkey( $key ) {
105 $t->mDbkeyform
= $key;
106 if ( $t->secureAndSplit() ) {
114 * Create a new Title from text, such as what one would find in a link. De-
115 * codes any HTML entities in the text.
117 * @param $text String the link text; spaces, prefixes, and an
118 * initial ':' indicating the main namespace are accepted.
119 * @param $defaultNamespace Int the namespace to use if none is speci-
120 * fied by a prefix. If you want to force a specific namespace even if
121 * $text might begin with a namespace prefix, use makeTitle() or
123 * @return Title, or null on an error.
125 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
126 if ( is_object( $text ) ) {
127 throw new MWException( 'Title::newFromText given an object' );
131 * Wiki pages often contain multiple links to the same page.
132 * Title normalization and parsing can become expensive on
133 * pages with many links, so we can save a little time by
136 * In theory these are value objects and won't get changed...
138 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
139 return Title
::$titleCache[$text];
142 # Convert things like é ā or 〗 into normalized (bug 14952) text
143 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
146 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
147 $t->mDefaultNamespace
= $defaultNamespace;
149 static $cachedcount = 0 ;
150 if ( $t->secureAndSplit() ) {
151 if ( $defaultNamespace == NS_MAIN
) {
152 if ( $cachedcount >= self
::CACHE_MAX
) {
153 # Avoid memory leaks on mass operations...
154 Title
::$titleCache = array();
158 Title
::$titleCache[$text] =& $t;
168 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
170 * Example of wrong and broken code:
171 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
173 * Example of right code:
174 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
176 * Create a new Title from URL-encoded text. Ensures that
177 * the given title's length does not exceed the maximum.
179 * @param $url String the title, as might be taken from a URL
180 * @return Title the new object, or NULL on an error
182 public static function newFromURL( $url ) {
183 global $wgLegalTitleChars;
186 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
187 # but some URLs used it as a space replacement and they still come
188 # from some external search tools.
189 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
190 $url = str_replace( '+', ' ', $url );
193 $t->mDbkeyform
= str_replace( ' ', '_', $url );
194 if ( $t->secureAndSplit() ) {
202 * Create a new Title from an article ID
204 * @param $id Int the page_id corresponding to the Title to create
205 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
206 * @return Title the new object, or NULL on an error
208 public static function newFromID( $id, $flags = 0 ) {
209 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
210 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
211 if ( $row !== false ) {
212 $title = Title
::newFromRow( $row );
220 * Make an array of titles from an array of IDs
222 * @param $ids Array of Int Array of IDs
223 * @return Array of Titles
225 public static function newFromIDs( $ids ) {
226 if ( !count( $ids ) ) {
229 $dbr = wfGetDB( DB_SLAVE
);
234 'page_namespace', 'page_title', 'page_id',
235 'page_len', 'page_is_redirect', 'page_latest',
237 array( 'page_id' => $ids ),
242 foreach ( $res as $row ) {
243 $titles[] = Title
::newFromRow( $row );
249 * Make a Title object from a DB row
251 * @param $row Object database row (needs at least page_title,page_namespace)
252 * @return Title corresponding Title
254 public static function newFromRow( $row ) {
255 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
256 $t->loadFromRow( $row );
261 * Load Title object fields from a DB row.
262 * If false is given, the title will be treated as non-existing.
264 * @param $row Object|bool database row
266 public function loadFromRow( $row ) {
267 if ( $row ) { // page found
268 if ( isset( $row->page_id
) )
269 $this->mArticleID
= (int)$row->page_id
;
270 if ( isset( $row->page_len
) )
271 $this->mLength
= (int)$row->page_len
;
272 if ( isset( $row->page_is_redirect
) )
273 $this->mRedirect
= (bool)$row->page_is_redirect
;
274 if ( isset( $row->page_latest
) )
275 $this->mLatestID
= (int)$row->page_latest
; # FIXME: whene3ver page_latest is updated, also update page_content_model
276 if ( isset( $row->page_content_model
) )
277 $this->mContentModel
= $row->page_content_model
;
279 $this->mContentModel
= null; # initialized lazily in getContentModel()
280 } else { // page not found
281 $this->mArticleID
= 0;
283 $this->mRedirect
= false;
284 $this->mLatestID
= 0;
285 $this->mContentModel
= null; # initialized lazily in getContentModel()
290 * Create a new Title from a namespace index and a DB key.
291 * It's assumed that $ns and $title are *valid*, for instance when
292 * they came directly from the database or a special page name.
293 * For convenience, spaces are converted to underscores so that
294 * eg user_text fields can be used directly.
296 * @param $ns Int the namespace of the article
297 * @param $title String the unprefixed database key form
298 * @param $fragment String the link fragment (after the "#")
299 * @param $interwiki String the interwiki prefix
300 * @return Title the new object
302 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
304 $t->mInterwiki
= $interwiki;
305 $t->mFragment
= $fragment;
306 $t->mNamespace
= $ns = intval( $ns );
307 $t->mDbkeyform
= str_replace( ' ', '_', $title );
308 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
309 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
310 $t->mTextform
= str_replace( '_', ' ', $title );
311 $t->mContentModel
= null; # initialized lazily in getContentModel()
316 * Create a new Title from a namespace index and a DB key.
317 * The parameters will be checked for validity, which is a bit slower
318 * than makeTitle() but safer for user-provided data.
320 * @param $ns Int the namespace of the article
321 * @param $title String database key form
322 * @param $fragment String the link fragment (after the "#")
323 * @param $interwiki String interwiki prefix
324 * @return Title the new object, or NULL on an error
326 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
327 if ( !MWNamespace
::exists( $ns ) ) {
332 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
333 if ( $t->secureAndSplit() ) {
341 * Create a new Title for the Main Page
343 * @return Title the new object
345 public static function newMainPage() {
346 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
347 // Don't give fatal errors if the message is broken
349 $title = Title
::newFromText( 'Main Page' );
355 * Extract a redirect destination from a string and return the
356 * Title, or null if the text doesn't contain a valid redirect
357 * This will only return the very next target, useful for
358 * the redirect table and other checks that don't need full recursion
360 * @param $text String: Text with possible redirect
361 * @return Title: The corresponding Title
363 public static function newFromRedirect( $text ) {
364 return self
::newFromRedirectInternal( $text );
368 * Extract a redirect destination from a string and return the
369 * Title, or null if the text doesn't contain a valid redirect
370 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
371 * in order to provide (hopefully) the Title of the final destination instead of another redirect
373 * @param $text String Text with possible redirect
376 public static function newFromRedirectRecurse( $text ) {
377 $titles = self
::newFromRedirectArray( $text );
378 return $titles ?
array_pop( $titles ) : null;
382 * Extract a redirect destination from a string and return an
383 * array of Titles, or null if the text doesn't contain a valid redirect
384 * The last element in the array is the final destination after all redirects
385 * have been resolved (up to $wgMaxRedirects times)
387 * @param $text String Text with possible redirect
388 * @return Array of Titles, with the destination last
390 public static function newFromRedirectArray( $text ) {
391 global $wgMaxRedirects;
392 $title = self
::newFromRedirectInternal( $text );
393 if ( is_null( $title ) ) {
396 // recursive check to follow double redirects
397 $recurse = $wgMaxRedirects;
398 $titles = array( $title );
399 while ( --$recurse > 0 ) {
400 if ( $title->isRedirect() ) {
401 $page = WikiPage
::factory( $title );
402 $newtitle = $page->getRedirectTarget();
406 // Redirects to some special pages are not permitted
407 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
408 // the new title passes the checks, so make that our current title so that further recursion can be checked
410 $titles[] = $newtitle;
419 * Really extract the redirect destination
420 * Do not call this function directly, use one of the newFromRedirect* functions above
422 * @param $text String Text with possible redirect
425 protected static function newFromRedirectInternal( $text ) {
426 global $wgMaxRedirects;
427 if ( $wgMaxRedirects < 1 ) {
428 //redirects are disabled, so quit early
431 $redir = MagicWord
::get( 'redirect' );
432 $text = trim( $text );
433 if ( $redir->matchStartAndRemove( $text ) ) {
434 // Extract the first link and see if it's usable
435 // Ensure that it really does come directly after #REDIRECT
436 // Some older redirects included a colon, so don't freak about that!
438 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
439 // Strip preceding colon used to "escape" categories, etc.
440 // and URL-decode links
441 if ( strpos( $m[1], '%' ) !== false ) {
442 // Match behavior of inline link parsing here;
443 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
445 $title = Title
::newFromText( $m[1] );
446 // If the title is a redirect to bad special pages or is invalid, return null
447 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
457 * Get the prefixed DB key associated with an ID
459 * @param $id Int the page_id of the article
460 * @return Title an object representing the article, or NULL if no such article was found
462 public static function nameOf( $id ) {
463 $dbr = wfGetDB( DB_SLAVE
);
465 $s = $dbr->selectRow(
467 array( 'page_namespace', 'page_title' ),
468 array( 'page_id' => $id ),
471 if ( $s === false ) {
475 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
480 * Get a regex character class describing the legal characters in a link
482 * @return String the list of characters, not delimited
484 public static function legalChars() {
485 global $wgLegalTitleChars;
486 return $wgLegalTitleChars;
490 * Returns a simple regex that will match on characters and sequences invalid in titles.
491 * Note that this doesn't pick up many things that could be wrong with titles, but that
492 * replacing this regex with something valid will make many titles valid.
494 * @return String regex string
496 static function getTitleInvalidRegex() {
497 static $rxTc = false;
499 # Matching titles will be held as illegal.
501 # Any character not allowed is forbidden...
502 '[^' . self
::legalChars() . ']' .
503 # URL percent encoding sequences interfere with the ability
504 # to round-trip titles -- you can't link to them consistently.
506 # XML/HTML character references produce similar issues.
507 '|&[A-Za-z0-9\x80-\xff]+;' .
509 '|&#x[0-9A-Fa-f]+;' .
517 * Get a string representation of a title suitable for
518 * including in a search index
520 * @param $ns Int a namespace index
521 * @param $title String text-form main part
522 * @return String a stripped-down title string ready for the search index
524 public static function indexTitle( $ns, $title ) {
527 $lc = SearchEngine
::legalSearchChars() . '&#;';
528 $t = $wgContLang->normalizeForSearch( $title );
529 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
530 $t = $wgContLang->lc( $t );
533 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
534 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
536 $t = preg_replace( "/\\s+/", ' ', $t );
538 if ( $ns == NS_FILE
) {
539 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
545 * Make a prefixed DB key from a DB key and a namespace index
547 * @param $ns Int numerical representation of the namespace
548 * @param $title String the DB key form the title
549 * @param $fragment String The link fragment (after the "#")
550 * @param $interwiki String The interwiki prefix
551 * @return String the prefixed form of the title
553 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
556 $namespace = $wgContLang->getNsText( $ns );
557 $name = $namespace == '' ?
$title : "$namespace:$title";
558 if ( strval( $interwiki ) != '' ) {
559 $name = "$interwiki:$name";
561 if ( strval( $fragment ) != '' ) {
562 $name .= '#' . $fragment;
568 * Escape a text fragment, say from a link, for a URL
570 * @param $fragment string containing a URL or link fragment (after the "#")
571 * @return String: escaped string
573 static function escapeFragmentForURL( $fragment ) {
574 # Note that we don't urlencode the fragment. urlencoded Unicode
575 # fragments appear not to work in IE (at least up to 7) or in at least
576 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
577 # to care if they aren't encoded.
578 return Sanitizer
::escapeId( $fragment, 'noninitial' );
582 * Callback for usort() to do title sorts by (namespace, title)
587 * @return Integer: result of string comparison, or namespace comparison
589 public static function compare( $a, $b ) {
590 if ( $a->getNamespace() == $b->getNamespace() ) {
591 return strcmp( $a->getText(), $b->getText() );
593 return $a->getNamespace() - $b->getNamespace();
598 * Determine whether the object refers to a page within
601 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
603 public function isLocal() {
604 if ( $this->mInterwiki
!= '' ) {
605 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
612 * Is this Title interwiki?
616 public function isExternal() {
617 return ( $this->mInterwiki
!= '' );
621 * Get the interwiki prefix (or null string)
623 * @return String Interwiki prefix
625 public function getInterwiki() {
626 return $this->mInterwiki
;
630 * Determine whether the object refers to a page within
631 * this project and is transcludable.
633 * @return Bool TRUE if this is transcludable
635 public function isTrans() {
636 if ( $this->mInterwiki
== '' ) {
640 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
644 * Returns the DB name of the distant wiki which owns the object.
646 * @return String the DB name
648 public function getTransWikiID() {
649 if ( $this->mInterwiki
== '' ) {
653 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
657 * Get the text form (spaces not underscores) of the main part
659 * @return String Main part of the title
661 public function getText() {
662 return $this->mTextform
;
666 * Get the URL-encoded form of the main part
668 * @return String Main part of the title, URL-encoded
670 public function getPartialURL() {
671 return $this->mUrlform
;
675 * Get the main part with underscores
677 * @return String: Main part of the title, with underscores
679 public function getDBkey() {
680 return $this->mDbkeyform
;
684 * Get the DB key with the initial letter case as specified by the user
686 * @return String DB key
688 function getUserCaseDBKey() {
689 return $this->mUserCaseDBKey
;
693 * Get the namespace index, i.e. one of the NS_xxxx constants.
695 * @return Integer: Namespace index
697 public function getNamespace() {
698 return $this->mNamespace
;
702 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
704 * @return Integer: Content model id
706 public function getContentModel() {
707 if ( empty( $this->mContentModel
) ) {
708 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
711 assert( !empty( $this->mContentModel
) );
712 return $this->mContentModel
;
716 * Conveniance method for checking a title's content model name
719 * @return true if $this->getContentModel() == $id
721 public function hasContentModel( $id ) {
722 return $this->getContentModel() == $id;
726 * Get the namespace text
728 * @return String: Namespace text
730 public function getNsText() {
733 if ( $this->mInterwiki
!= '' ) {
734 // This probably shouldn't even happen. ohh man, oh yuck.
735 // But for interwiki transclusion it sometimes does.
736 // Shit. Shit shit shit.
738 // Use the canonical namespaces if possible to try to
739 // resolve a foreign namespace.
740 if ( MWNamespace
::exists( $this->mNamespace
) ) {
741 return MWNamespace
::getCanonicalName( $this->mNamespace
);
745 if ( $wgContLang->needsGenderDistinction() &&
746 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
747 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
748 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
751 return $wgContLang->getNsText( $this->mNamespace
);
755 * Get the namespace text of the subject (rather than talk) page
757 * @return String Namespace text
759 public function getSubjectNsText() {
761 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
765 * Get the namespace text of the talk page
767 * @return String Namespace text
769 public function getTalkNsText() {
771 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
775 * Could this title have a corresponding talk page?
777 * @return Bool TRUE or FALSE
779 public function canTalk() {
780 return( MWNamespace
::canTalk( $this->mNamespace
) );
784 * Is this in a namespace that allows actual pages?
787 * @internal note -- uses hardcoded namespace index instead of constants
789 public function canExist() {
790 return $this->mNamespace
>= NS_MAIN
;
794 * Can this title be added to a user's watchlist?
796 * @return Bool TRUE or FALSE
798 public function isWatchable() {
799 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
803 * Returns true if this is a special page.
807 public function isSpecialPage() {
808 return $this->getNamespace() == NS_SPECIAL
;
812 * Returns true if this title resolves to the named special page
814 * @param $name String The special page name
817 public function isSpecial( $name ) {
818 if ( $this->isSpecialPage() ) {
819 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
820 if ( $name == $thisName ) {
828 * If the Title refers to a special page alias which is not the local default, resolve
829 * the alias, and localise the name as necessary. Otherwise, return $this
833 public function fixSpecialName() {
834 if ( $this->isSpecialPage() ) {
835 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
836 if ( $canonicalName ) {
837 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
838 if ( $localName != $this->mDbkeyform
) {
839 return Title
::makeTitle( NS_SPECIAL
, $localName );
847 * Returns true if the title is inside the specified namespace.
849 * Please make use of this instead of comparing to getNamespace()
850 * This function is much more resistant to changes we may make
851 * to namespaces than code that makes direct comparisons.
852 * @param $ns int The namespace
856 public function inNamespace( $ns ) {
857 return MWNamespace
::equals( $this->getNamespace(), $ns );
861 * Returns true if the title is inside one of the specified namespaces.
863 * @param ...$namespaces The namespaces to check for
867 public function inNamespaces( /* ... */ ) {
868 $namespaces = func_get_args();
869 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
870 $namespaces = $namespaces[0];
873 foreach ( $namespaces as $ns ) {
874 if ( $this->inNamespace( $ns ) ) {
883 * Returns true if the title has the same subject namespace as the
884 * namespace specified.
885 * For example this method will take NS_USER and return true if namespace
886 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
887 * as their subject namespace.
889 * This is MUCH simpler than individually testing for equivilance
890 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
894 public function hasSubjectNamespace( $ns ) {
895 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
899 * Is this Title in a namespace which contains content?
900 * In other words, is this a content page, for the purposes of calculating
905 public function isContentPage() {
906 return MWNamespace
::isContent( $this->getNamespace() );
910 * Would anybody with sufficient privileges be able to move this page?
911 * Some pages just aren't movable.
913 * @return Bool TRUE or FALSE
915 public function isMovable() {
916 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
917 // Interwiki title or immovable namespace. Hooks don't get to override here
922 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
927 * Is this the mainpage?
928 * @note Title::newFromText seams to be sufficiently optimized by the title
929 * cache that we don't need to over-optimize by doing direct comparisons and
930 * acidentally creating new bugs where $title->equals( Title::newFromText() )
931 * ends up reporting something differently than $title->isMainPage();
936 public function isMainPage() {
937 return $this->equals( Title
::newMainPage() );
945 public function isSubpage() {
946 return MWNamespace
::hasSubpages( $this->mNamespace
)
947 ?
strpos( $this->getText(), '/' ) !== false
952 * Is this a conversion table for the LanguageConverter?
956 public function isConversionTable() {
957 return $this->getNamespace() == NS_MEDIAWIKI
&&
958 strpos( $this->getText(), 'Conversiontable' ) !== false;
962 * Does that page contain wikitext, or it is JS, CSS or whatever?
966 public function isWikitextPage() {
967 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
971 * Could this page contain custom CSS or JavaScript for the global UI.
972 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
973 * or CONTENT_MODEL_JAVASCRIPT.
975 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
977 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
981 public function isCssOrJsPage() {
982 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
983 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
984 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
986 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
987 # hook funktions can force this method to return true even outside the mediawiki namespace.
989 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
991 return $isCssOrJsPage;
995 * Is this a .css or .js subpage of a user page?
998 public function isCssJsSubpage() {
999 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1000 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1001 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1005 * Trim down a .css or .js subpage title to get the corresponding skin name
1007 * @return string containing skin name from .css or .js subpage title
1009 public function getSkinFromCssJsSubpage() {
1010 $subpage = explode( '/', $this->mTextform
);
1011 $subpage = $subpage[ count( $subpage ) - 1 ];
1012 $lastdot = strrpos( $subpage, '.' );
1013 if ( $lastdot === false )
1014 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1015 return substr( $subpage, 0, $lastdot );
1019 * Is this a .css subpage of a user page?
1023 public function isCssSubpage() {
1024 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1025 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1029 * Is this a .js subpage of a user page?
1033 public function isJsSubpage() {
1034 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1035 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1039 * Is this a talk page of some sort?
1043 public function isTalkPage() {
1044 return MWNamespace
::isTalk( $this->getNamespace() );
1048 * Get a Title object associated with the talk page of this article
1050 * @return Title the object for the talk page
1052 public function getTalkPage() {
1053 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1057 * Get a title object associated with the subject page of this
1060 * @return Title the object for the subject page
1062 public function getSubjectPage() {
1063 // Is this the same title?
1064 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1065 if ( $this->getNamespace() == $subjectNS ) {
1068 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1072 * Get the default namespace index, for when there is no namespace
1074 * @return Int Default namespace index
1076 public function getDefaultNamespace() {
1077 return $this->mDefaultNamespace
;
1081 * Get title for search index
1083 * @return String a stripped-down title string ready for the
1086 public function getIndexTitle() {
1087 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1091 * Get the Title fragment (i.e.\ the bit after the #) in text form
1093 * @return String Title fragment
1095 public function getFragment() {
1096 return $this->mFragment
;
1100 * Get the fragment in URL form, including the "#" character if there is one
1101 * @return String Fragment in URL form
1103 public function getFragmentForURL() {
1104 if ( $this->mFragment
== '' ) {
1107 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1112 * Set the fragment for this title. Removes the first character from the
1113 * specified fragment before setting, so it assumes you're passing it with
1116 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1117 * Still in active use privately.
1119 * @param $fragment String text
1121 public function setFragment( $fragment ) {
1122 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1126 * Prefix some arbitrary text with the namespace or interwiki prefix
1129 * @param $name String the text
1130 * @return String the prefixed text
1133 private function prefix( $name ) {
1135 if ( $this->mInterwiki
!= '' ) {
1136 $p = $this->mInterwiki
. ':';
1139 if ( 0 != $this->mNamespace
) {
1140 $p .= $this->getNsText() . ':';
1146 * Get the prefixed database key form
1148 * @return String the prefixed title, with underscores and
1149 * any interwiki and namespace prefixes
1151 public function getPrefixedDBkey() {
1152 $s = $this->prefix( $this->mDbkeyform
);
1153 $s = str_replace( ' ', '_', $s );
1158 * Get the prefixed title with spaces.
1159 * This is the form usually used for display
1161 * @return String the prefixed title, with spaces
1163 public function getPrefixedText() {
1164 // @todo FIXME: Bad usage of empty() ?
1165 if ( empty( $this->mPrefixedText
) ) {
1166 $s = $this->prefix( $this->mTextform
);
1167 $s = str_replace( '_', ' ', $s );
1168 $this->mPrefixedText
= $s;
1170 return $this->mPrefixedText
;
1174 * Return a string representation of this title
1176 * @return String representation of this title
1178 public function __toString() {
1179 return $this->getPrefixedText();
1183 * Get the prefixed title with spaces, plus any fragment
1184 * (part beginning with '#')
1186 * @return String the prefixed title, with spaces and the fragment, including '#'
1188 public function getFullText() {
1189 $text = $this->getPrefixedText();
1190 if ( $this->mFragment
!= '' ) {
1191 $text .= '#' . $this->mFragment
;
1197 * Get the base page name, i.e. the leftmost part before any slashes
1199 * @return String Base name
1201 public function getBaseText() {
1202 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1203 return $this->getText();
1206 $parts = explode( '/', $this->getText() );
1207 # Don't discard the real title if there's no subpage involved
1208 if ( count( $parts ) > 1 ) {
1209 unset( $parts[count( $parts ) - 1] );
1211 return implode( '/', $parts );
1215 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1217 * @return String Subpage name
1219 public function getSubpageText() {
1220 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1221 return( $this->mTextform
);
1223 $parts = explode( '/', $this->mTextform
);
1224 return( $parts[count( $parts ) - 1] );
1228 * Get the HTML-escaped displayable text form.
1229 * Used for the title field in <a> tags.
1231 * @return String the text, including any prefixes
1233 public function getEscapedText() {
1234 wfDeprecated( __METHOD__
, '1.19' );
1235 return htmlspecialchars( $this->getPrefixedText() );
1239 * Get a URL-encoded form of the subpage text
1241 * @return String URL-encoded subpage name
1243 public function getSubpageUrlForm() {
1244 $text = $this->getSubpageText();
1245 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1250 * Get a URL-encoded title (not an actual URL) including interwiki
1252 * @return String the URL-encoded form
1254 public function getPrefixedURL() {
1255 $s = $this->prefix( $this->mDbkeyform
);
1256 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1261 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1262 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1263 * second argument named variant. This was deprecated in favor
1264 * of passing an array of option with a "variant" key
1265 * Once $query2 is removed for good, this helper can be dropped
1266 * andthe wfArrayToCGI moved to getLocalURL();
1268 * @since 1.19 (r105919)
1271 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1272 if( $query2 !== false ) {
1273 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" );
1275 if ( is_array( $query ) ) {
1276 $query = wfArrayToCGI( $query );
1279 if ( is_string( $query2 ) ) {
1280 // $query2 is a string, we will consider this to be
1281 // a deprecated $variant argument and add it to the query
1282 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1284 $query2 = wfArrayToCGI( $query2 );
1286 // If we have $query content add a & to it first
1290 // Now append the queries together
1297 * Get a real URL referring to this title, with interwiki link and
1300 * See getLocalURL for the arguments.
1302 * @see self::getLocalURL
1303 * @return String the URL
1305 public function getFullURL( $query = '', $query2 = false ) {
1306 $query = self
::fixUrlQueryArgs( $query, $query2 );
1308 # Hand off all the decisions on urls to getLocalURL
1309 $url = $this->getLocalURL( $query );
1311 # Expand the url to make it a full url. Note that getLocalURL has the
1312 # potential to output full urls for a variety of reasons, so we use
1313 # wfExpandUrl instead of simply prepending $wgServer
1314 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1316 # Finally, add the fragment.
1317 $url .= $this->getFragmentForURL();
1319 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1324 * Get a URL with no fragment or server name. If this page is generated
1325 * with action=render, $wgServer is prepended.
1328 * @param $query string|array an optional query string,
1329 * not used for interwiki links. Can be specified as an associative array as well,
1330 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1331 * Some query patterns will trigger various shorturl path replacements.
1332 * @param $query2 Mixed: An optional secondary query array. This one MUST
1333 * be an array. If a string is passed it will be interpreted as a deprecated
1334 * variant argument and urlencoded into a variant= argument.
1335 * This second query argument will be added to the $query
1336 * The second parameter is deprecated since 1.19. Pass it as a key,value
1337 * pair in the first parameter array instead.
1339 * @return String the URL
1341 public function getLocalURL( $query = '', $query2 = false ) {
1342 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1344 $query = self
::fixUrlQueryArgs( $query, $query2 );
1346 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1348 $namespace = $this->getNsText();
1349 if ( $namespace != '' ) {
1350 # Can this actually happen? Interwikis shouldn't be parsed.
1351 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1354 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1355 $url = wfAppendQuery( $url, $query );
1357 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1358 if ( $query == '' ) {
1359 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1360 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1362 global $wgVariantArticlePath, $wgActionPaths;
1366 if ( !empty( $wgActionPaths ) &&
1367 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1369 $action = urldecode( $matches[2] );
1370 if ( isset( $wgActionPaths[$action] ) ) {
1371 $query = $matches[1];
1372 if ( isset( $matches[4] ) ) {
1373 $query .= $matches[4];
1375 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1376 if ( $query != '' ) {
1377 $url = wfAppendQuery( $url, $query );
1382 if ( $url === false &&
1383 $wgVariantArticlePath &&
1384 $this->getPageLanguage()->hasVariants() &&
1385 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1387 $variant = urldecode( $matches[1] );
1388 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1389 // Only do the variant replacement if the given variant is a valid
1390 // variant for the page's language.
1391 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1392 $url = str_replace( '$1', $dbkey, $url );
1396 if ( $url === false ) {
1397 if ( $query == '-' ) {
1400 $url = "{$wgScript}?title={$dbkey}&{$query}";
1404 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1406 // @todo FIXME: This causes breakage in various places when we
1407 // actually expected a local URL and end up with dupe prefixes.
1408 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1409 $url = $wgServer . $url;
1412 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1417 * Get a URL that's the simplest URL that will be valid to link, locally,
1418 * to the current Title. It includes the fragment, but does not include
1419 * the server unless action=render is used (or the link is external). If
1420 * there's a fragment but the prefixed text is empty, we just return a link
1423 * The result obviously should not be URL-escaped, but does need to be
1424 * HTML-escaped if it's being output in HTML.
1426 * See getLocalURL for the arguments.
1428 * @see self::getLocalURL
1429 * @return String the URL
1431 public function getLinkURL( $query = '', $query2 = false ) {
1432 wfProfileIn( __METHOD__
);
1433 if ( $this->isExternal() ) {
1434 $ret = $this->getFullURL( $query, $query2 );
1435 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1436 $ret = $this->getFragmentForURL();
1438 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1440 wfProfileOut( __METHOD__
);
1445 * Get an HTML-escaped version of the URL form, suitable for
1446 * using in a link, without a server name or fragment
1448 * See getLocalURL for the arguments.
1450 * @see self::getLocalURL
1451 * @return String the URL
1453 public function escapeLocalURL( $query = '', $query2 = false ) {
1454 wfDeprecated( __METHOD__
, '1.19' );
1455 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1459 * Get an HTML-escaped version of the URL form, suitable for
1460 * using in a link, including the server name and fragment
1462 * See getLocalURL for the arguments.
1464 * @see self::getLocalURL
1465 * @return String the URL
1467 public function escapeFullURL( $query = '', $query2 = false ) {
1468 wfDeprecated( __METHOD__
, '1.19' );
1469 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1473 * Get the URL form for an internal link.
1474 * - Used in various Squid-related code, in case we have a different
1475 * internal hostname for the server from the exposed one.
1477 * This uses $wgInternalServer to qualify the path, or $wgServer
1478 * if $wgInternalServer is not set. If the server variable used is
1479 * protocol-relative, the URL will be expanded to http://
1481 * See getLocalURL for the arguments.
1483 * @see self::getLocalURL
1484 * @return String the URL
1486 public function getInternalURL( $query = '', $query2 = false ) {
1487 global $wgInternalServer, $wgServer;
1488 $query = self
::fixUrlQueryArgs( $query, $query2 );
1489 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1490 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1491 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1496 * Get the URL for a canonical link, for use in things like IRC and
1497 * e-mail notifications. Uses $wgCanonicalServer and the
1498 * GetCanonicalURL hook.
1500 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1502 * See getLocalURL for the arguments.
1504 * @see self::getLocalURL
1505 * @return string The URL
1508 public function getCanonicalURL( $query = '', $query2 = false ) {
1509 $query = self
::fixUrlQueryArgs( $query, $query2 );
1510 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1511 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1516 * HTML-escaped version of getCanonicalURL()
1518 * See getLocalURL for the arguments.
1520 * @see self::getLocalURL
1524 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1525 wfDeprecated( __METHOD__
, '1.19' );
1526 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1530 * Get the edit URL for this Title
1532 * @return String the URL, or a null string if this is an
1535 public function getEditURL() {
1536 if ( $this->mInterwiki
!= '' ) {
1539 $s = $this->getLocalURL( 'action=edit' );
1545 * Is $wgUser watching this page?
1549 public function userIsWatching() {
1552 if ( is_null( $this->mWatched
) ) {
1553 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1554 $this->mWatched
= false;
1556 $this->mWatched
= $wgUser->isWatched( $this );
1559 return $this->mWatched
;
1563 * Can $wgUser read this page?
1565 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1567 * @todo fold these checks into userCan()
1569 public function userCanRead() {
1570 wfDeprecated( __METHOD__
, '1.19' );
1571 return $this->userCan( 'read' );
1575 * Can $user perform $action on this page?
1576 * This skips potentially expensive cascading permission checks
1577 * as well as avoids expensive error formatting
1579 * Suitable for use for nonessential UI controls in common cases, but
1580 * _not_ for functional access control.
1582 * May provide false positives, but should never provide a false negative.
1584 * @param $action String action that permission needs to be checked for
1585 * @param $user User to check (since 1.19); $wgUser will be used if not
1589 public function quickUserCan( $action, $user = null ) {
1590 return $this->userCan( $action, $user, false );
1594 * Can $user perform $action on this page?
1596 * @param $action String action that permission needs to be checked for
1597 * @param $user User to check (since 1.19); $wgUser will be used if not
1599 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1600 * unnecessary queries.
1603 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1604 if ( !$user instanceof User
) {
1608 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1612 * Can $user perform $action on this page?
1614 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1616 * @param $action String action that permission needs to be checked for
1617 * @param $user User to check
1618 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1619 * queries by skipping checks for cascading protections and user blocks.
1620 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1621 * whose corresponding errors may be ignored.
1622 * @return Array of arguments to wfMsg to explain permissions problems.
1624 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1625 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1627 // Remove the errors being ignored.
1628 foreach ( $errors as $index => $error ) {
1629 $error_key = is_array( $error ) ?
$error[0] : $error;
1631 if ( in_array( $error_key, $ignoreErrors ) ) {
1632 unset( $errors[$index] );
1640 * Permissions checks that fail most often, and which are easiest to test.
1642 * @param $action String the action to check
1643 * @param $user User user to check
1644 * @param $errors Array list of current errors
1645 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1646 * @param $short Boolean short circuit on first error
1648 * @return Array list of errors
1650 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1651 if ( $action == 'create' ) {
1652 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1653 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1654 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1656 } elseif ( $action == 'move' ) {
1657 if ( !$user->isAllowed( 'move-rootuserpages' )
1658 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1659 // Show user page-specific message only if the user can move other pages
1660 $errors[] = array( 'cant-move-user-page' );
1663 // Check if user is allowed to move files if it's a file
1664 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1665 $errors[] = array( 'movenotallowedfile' );
1668 if ( !$user->isAllowed( 'move' ) ) {
1669 // User can't move anything
1670 global $wgGroupPermissions;
1671 $userCanMove = false;
1672 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1673 $userCanMove = $wgGroupPermissions['user']['move'];
1675 $autoconfirmedCanMove = false;
1676 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1677 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1679 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1680 // custom message if logged-in users without any special rights can move
1681 $errors[] = array( 'movenologintext' );
1683 $errors[] = array( 'movenotallowed' );
1686 } elseif ( $action == 'move-target' ) {
1687 if ( !$user->isAllowed( 'move' ) ) {
1688 // User can't move anything
1689 $errors[] = array( 'movenotallowed' );
1690 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1691 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1692 // Show user page-specific message only if the user can move other pages
1693 $errors[] = array( 'cant-move-to-user-page' );
1695 } elseif ( !$user->isAllowed( $action ) ) {
1696 $errors[] = $this->missingPermissionError( $action, $short );
1703 * Add the resulting error code to the errors array
1705 * @param $errors Array list of current errors
1706 * @param $result Mixed result of errors
1708 * @return Array list of errors
1710 private function resultToError( $errors, $result ) {
1711 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1712 // A single array representing an error
1713 $errors[] = $result;
1714 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1715 // A nested array representing multiple errors
1716 $errors = array_merge( $errors, $result );
1717 } elseif ( $result !== '' && is_string( $result ) ) {
1718 // A string representing a message-id
1719 $errors[] = array( $result );
1720 } elseif ( $result === false ) {
1721 // a generic "We don't want them to do that"
1722 $errors[] = array( 'badaccess-group0' );
1728 * Check various permission hooks
1730 * @param $action String the action to check
1731 * @param $user User user to check
1732 * @param $errors Array list of current errors
1733 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1734 * @param $short Boolean short circuit on first error
1736 * @return Array list of errors
1738 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1739 // Use getUserPermissionsErrors instead
1741 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1742 return $result ?
array() : array( array( 'badaccess-group0' ) );
1744 // Check getUserPermissionsErrors hook
1745 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1746 $errors = $this->resultToError( $errors, $result );
1748 // Check getUserPermissionsErrorsExpensive hook
1749 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1750 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1751 $errors = $this->resultToError( $errors, $result );
1758 * Check permissions on special pages & namespaces
1760 * @param $action String the action to check
1761 * @param $user User user to check
1762 * @param $errors Array list of current errors
1763 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1764 * @param $short Boolean short circuit on first error
1766 * @return Array list of errors
1768 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1769 # Only 'createaccount' and 'execute' can be performed on
1770 # special pages, which don't actually exist in the DB.
1771 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1772 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1773 $errors[] = array( 'ns-specialprotected' );
1776 # Check $wgNamespaceProtection for restricted namespaces
1777 if ( $this->isNamespaceProtected( $user ) ) {
1778 $ns = $this->mNamespace
== NS_MAIN ?
1779 wfMsg( 'nstab-main' ) : $this->getNsText();
1780 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1781 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1788 * Check CSS/JS sub-page permissions
1790 * @param $action String the action to check
1791 * @param $user User user to check
1792 * @param $errors Array list of current errors
1793 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1794 * @param $short Boolean short circuit on first error
1796 * @return Array list of errors
1798 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1799 # Protect css/js subpages of user pages
1800 # XXX: this might be better using restrictions
1801 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1802 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1803 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1804 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1805 $errors[] = array( 'customcssprotected' );
1806 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1807 $errors[] = array( 'customjsprotected' );
1815 * Check against page_restrictions table requirements on this
1816 * page. The user must possess all required rights for this
1819 * @param $action String the action to check
1820 * @param $user User user to check
1821 * @param $errors Array list of current errors
1822 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1823 * @param $short Boolean short circuit on first error
1825 * @return Array list of errors
1827 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1828 foreach ( $this->getRestrictions( $action ) as $right ) {
1829 // Backwards compatibility, rewrite sysop -> protect
1830 if ( $right == 'sysop' ) {
1833 if ( $right != '' && !$user->isAllowed( $right ) ) {
1834 // Users with 'editprotected' permission can edit protected pages
1835 // without cascading option turned on.
1836 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1837 ||
$this->mCascadeRestriction
)
1839 $errors[] = array( 'protectedpagetext', $right );
1848 * Check restrictions on cascading pages.
1850 * @param $action String the action to check
1851 * @param $user User to check
1852 * @param $errors Array list of current errors
1853 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1854 * @param $short Boolean short circuit on first error
1856 * @return Array list of errors
1858 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1859 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1860 # We /could/ use the protection level on the source page, but it's
1861 # fairly ugly as we have to establish a precedence hierarchy for pages
1862 # included by multiple cascade-protected pages. So just restrict
1863 # it to people with 'protect' permission, as they could remove the
1864 # protection anyway.
1865 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1866 # Cascading protection depends on more than this page...
1867 # Several cascading protected pages may include this page...
1868 # Check each cascading level
1869 # This is only for protection restrictions, not for all actions
1870 if ( isset( $restrictions[$action] ) ) {
1871 foreach ( $restrictions[$action] as $right ) {
1872 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1873 if ( $right != '' && !$user->isAllowed( $right ) ) {
1875 foreach ( $cascadingSources as $page )
1876 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1877 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1887 * Check action permissions not already checked in checkQuickPermissions
1889 * @param $action String the action to check
1890 * @param $user User to check
1891 * @param $errors Array list of current errors
1892 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1893 * @param $short Boolean short circuit on first error
1895 * @return Array list of errors
1897 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1898 global $wgDeleteRevisionsLimit, $wgLang;
1900 if ( $action == 'protect' ) {
1901 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1902 // If they can't edit, they shouldn't protect.
1903 $errors[] = array( 'protect-cantedit' );
1905 } elseif ( $action == 'create' ) {
1906 $title_protection = $this->getTitleProtection();
1907 if( $title_protection ) {
1908 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1909 $title_protection['pt_create_perm'] = 'protect'; // B/C
1911 if( $title_protection['pt_create_perm'] == '' ||
1912 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1914 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1917 } elseif ( $action == 'move' ) {
1918 // Check for immobile pages
1919 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1920 // Specific message for this case
1921 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1922 } elseif ( !$this->isMovable() ) {
1923 // Less specific message for rarer cases
1924 $errors[] = array( 'immobile-source-page' );
1926 } elseif ( $action == 'move-target' ) {
1927 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1928 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1929 } elseif ( !$this->isMovable() ) {
1930 $errors[] = array( 'immobile-target-page' );
1932 } elseif ( $action == 'delete' ) {
1933 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1934 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1936 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1943 * Check that the user isn't blocked from editting.
1945 * @param $action String the action to check
1946 * @param $user User to check
1947 * @param $errors Array list of current errors
1948 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1949 * @param $short Boolean short circuit on first error
1951 * @return Array list of errors
1953 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1954 // Account creation blocks handled at userlogin.
1955 // Unblocking handled in SpecialUnblock
1956 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1960 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1962 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1963 $errors[] = array( 'confirmedittext' );
1966 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1967 // Don't block the user from editing their own talk page unless they've been
1968 // explicitly blocked from that too.
1969 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1970 $block = $user->getBlock();
1972 // This is from OutputPage::blockedPage
1973 // Copied at r23888 by werdna
1975 $id = $user->blockedBy();
1976 $reason = $user->blockedFor();
1977 if ( $reason == '' ) {
1978 $reason = wfMsg( 'blockednoreason' );
1980 $ip = $user->getRequest()->getIP();
1982 if ( is_numeric( $id ) ) {
1983 $name = User
::whoIs( $id );
1988 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1989 $blockid = $block->getId();
1990 $blockExpiry = $block->getExpiry();
1991 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1992 if ( $blockExpiry == 'infinity' ) {
1993 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1995 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1998 $intended = strval( $block->getTarget() );
2000 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2001 $blockid, $blockExpiry, $intended, $blockTimestamp );
2008 * Check that the user is allowed to read this page.
2010 * @param $action String the action to check
2011 * @param $user User to check
2012 * @param $errors Array list of current errors
2013 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2014 * @param $short Boolean short circuit on first error
2016 * @return Array list of errors
2018 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2019 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2020 static $useShortcut = null;
2022 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2023 if ( is_null( $useShortcut ) ) {
2024 $useShortcut = true;
2025 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2026 # Not a public wiki, so no shortcut
2027 $useShortcut = false;
2028 } elseif ( !empty( $wgRevokePermissions ) ) {
2030 * Iterate through each group with permissions being revoked (key not included since we don't care
2031 * what the group name is), then check if the read permission is being revoked. If it is, then
2032 * we don't use the shortcut below since the user might not be able to read, even though anon
2033 * reading is allowed.
2035 foreach ( $wgRevokePermissions as $perms ) {
2036 if ( !empty( $perms['read'] ) ) {
2037 # We might be removing the read right from the user, so no shortcut
2038 $useShortcut = false;
2045 $whitelisted = false;
2046 if ( $useShortcut ) {
2047 # Shortcut for public wikis, allows skipping quite a bit of code
2048 $whitelisted = true;
2049 } elseif ( $user->isAllowed( 'read' ) ) {
2050 # If the user is allowed to read pages, he is allowed to read all pages
2051 $whitelisted = true;
2052 } elseif ( $this->isSpecial( 'Userlogin' )
2053 ||
$this->isSpecial( 'ChangePassword' )
2054 ||
$this->isSpecial( 'PasswordReset' )
2056 # Always grant access to the login page.
2057 # Even anons need to be able to log in.
2058 $whitelisted = true;
2059 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2060 # Time to check the whitelist
2061 # Only do these checks is there's something to check against
2062 $name = $this->getPrefixedText();
2063 $dbName = $this->getPrefixedDBKey();
2065 // Check for explicit whitelisting with and without underscores
2066 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2067 $whitelisted = true;
2068 } elseif ( $this->getNamespace() == NS_MAIN
) {
2069 # Old settings might have the title prefixed with
2070 # a colon for main-namespace pages
2071 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2072 $whitelisted = true;
2074 } elseif ( $this->isSpecialPage() ) {
2075 # If it's a special page, ditch the subpage bit and check again
2076 $name = $this->getDBkey();
2077 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2078 if ( $name !== false ) {
2079 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2080 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2081 $whitelisted = true;
2087 if ( !$whitelisted ) {
2088 # If the title is not whitelisted, give extensions a chance to do so...
2089 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2090 if ( !$whitelisted ) {
2091 $errors[] = $this->missingPermissionError( $action, $short );
2099 * Get a description array when the user doesn't have the right to perform
2100 * $action (i.e. when User::isAllowed() returns false)
2102 * @param $action String the action to check
2103 * @param $short Boolean short circuit on first error
2104 * @return Array list of errors
2106 private function missingPermissionError( $action, $short ) {
2107 // We avoid expensive display logic for quickUserCan's and such
2109 return array( 'badaccess-group0' );
2112 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2113 User
::getGroupsWithPermission( $action ) );
2115 if ( count( $groups ) ) {
2119 $wgLang->commaList( $groups ),
2123 return array( 'badaccess-group0' );
2128 * Can $user perform $action on this page? This is an internal function,
2129 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2130 * checks on wfReadOnly() and blocks)
2132 * @param $action String action that permission needs to be checked for
2133 * @param $user User to check
2134 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2135 * @param $short Bool Set this to true to stop after the first permission error.
2136 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2138 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2139 wfProfileIn( __METHOD__
);
2141 # Read has special handling
2142 if ( $action == 'read' ) {
2144 'checkPermissionHooks',
2145 'checkReadPermissions',
2149 'checkQuickPermissions',
2150 'checkPermissionHooks',
2151 'checkSpecialsAndNSPermissions',
2152 'checkCSSandJSPermissions',
2153 'checkPageRestrictions',
2154 'checkCascadingSourcesRestrictions',
2155 'checkActionPermissions',
2161 while( count( $checks ) > 0 &&
2162 !( $short && count( $errors ) > 0 ) ) {
2163 $method = array_shift( $checks );
2164 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2167 wfProfileOut( __METHOD__
);
2172 * Protect css subpages of user pages: can $wgUser edit
2175 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2178 public function userCanEditCssSubpage() {
2180 wfDeprecated( __METHOD__
, '1.19' );
2181 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2182 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2186 * Protect js subpages of user pages: can $wgUser edit
2189 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2192 public function userCanEditJsSubpage() {
2194 wfDeprecated( __METHOD__
, '1.19' );
2195 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2196 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2200 * Get a filtered list of all restriction types supported by this wiki.
2201 * @param bool $exists True to get all restriction types that apply to
2202 * titles that do exist, False for all restriction types that apply to
2203 * titles that do not exist
2206 public static function getFilteredRestrictionTypes( $exists = true ) {
2207 global $wgRestrictionTypes;
2208 $types = $wgRestrictionTypes;
2210 # Remove the create restriction for existing titles
2211 $types = array_diff( $types, array( 'create' ) );
2213 # Only the create and upload restrictions apply to non-existing titles
2214 $types = array_intersect( $types, array( 'create', 'upload' ) );
2220 * Returns restriction types for the current Title
2222 * @return array applicable restriction types
2224 public function getRestrictionTypes() {
2225 if ( $this->isSpecialPage() ) {
2229 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2231 if ( $this->getNamespace() != NS_FILE
) {
2232 # Remove the upload restriction for non-file titles
2233 $types = array_diff( $types, array( 'upload' ) );
2236 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2238 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2239 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2245 * Is this title subject to title protection?
2246 * Title protection is the one applied against creation of such title.
2248 * @return Mixed An associative array representing any existent title
2249 * protection, or false if there's none.
2251 private function getTitleProtection() {
2252 // Can't protect pages in special namespaces
2253 if ( $this->getNamespace() < 0 ) {
2257 // Can't protect pages that exist.
2258 if ( $this->exists() ) {
2262 if ( !isset( $this->mTitleProtection
) ) {
2263 $dbr = wfGetDB( DB_SLAVE
);
2264 $res = $dbr->select( 'protected_titles', '*',
2265 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2268 // fetchRow returns false if there are no rows.
2269 $this->mTitleProtection
= $dbr->fetchRow( $res );
2271 return $this->mTitleProtection
;
2275 * Update the title protection status
2277 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2278 * @param $create_perm String Permission required for creation
2279 * @param $reason String Reason for protection
2280 * @param $expiry String Expiry timestamp
2281 * @return boolean true
2283 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2284 wfDeprecated( __METHOD__
, '1.19' );
2288 $limit = array( 'create' => $create_perm );
2289 $expiry = array( 'create' => $expiry );
2291 $page = WikiPage
::factory( $this );
2292 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2294 return $status->isOK();
2298 * Remove any title protection due to page existing
2300 public function deleteTitleProtection() {
2301 $dbw = wfGetDB( DB_MASTER
);
2305 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2308 $this->mTitleProtection
= false;
2312 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2314 * @param $action String Action to check (default: edit)
2317 public function isSemiProtected( $action = 'edit' ) {
2318 if ( $this->exists() ) {
2319 $restrictions = $this->getRestrictions( $action );
2320 if ( count( $restrictions ) > 0 ) {
2321 foreach ( $restrictions as $restriction ) {
2322 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2332 # If it doesn't exist, it can't be protected
2338 * Does the title correspond to a protected article?
2340 * @param $action String the action the page is protected from,
2341 * by default checks all actions.
2344 public function isProtected( $action = '' ) {
2345 global $wgRestrictionLevels;
2347 $restrictionTypes = $this->getRestrictionTypes();
2349 # Special pages have inherent protection
2350 if( $this->isSpecialPage() ) {
2354 # Check regular protection levels
2355 foreach ( $restrictionTypes as $type ) {
2356 if ( $action == $type ||
$action == '' ) {
2357 $r = $this->getRestrictions( $type );
2358 foreach ( $wgRestrictionLevels as $level ) {
2359 if ( in_array( $level, $r ) && $level != '' ) {
2370 * Determines if $user is unable to edit this page because it has been protected
2371 * by $wgNamespaceProtection.
2373 * @param $user User object to check permissions
2376 public function isNamespaceProtected( User
$user ) {
2377 global $wgNamespaceProtection;
2379 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2380 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2381 if ( $right != '' && !$user->isAllowed( $right ) ) {
2390 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2392 * @return Bool If the page is subject to cascading restrictions.
2394 public function isCascadeProtected() {
2395 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2396 return ( $sources > 0 );
2400 * Cascading protection: Get the source of any cascading restrictions on this page.
2402 * @param $getPages Bool Whether or not to retrieve the actual pages
2403 * that the restrictions have come from.
2404 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2405 * have come, false for none, or true if such restrictions exist, but $getPages
2406 * was not set. The restriction array is an array of each type, each of which
2407 * contains a array of unique groups.
2409 public function getCascadeProtectionSources( $getPages = true ) {
2411 $pagerestrictions = array();
2413 if ( isset( $this->mCascadeSources
) && $getPages ) {
2414 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2415 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2416 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2419 wfProfileIn( __METHOD__
);
2421 $dbr = wfGetDB( DB_SLAVE
);
2423 if ( $this->getNamespace() == NS_FILE
) {
2424 $tables = array( 'imagelinks', 'page_restrictions' );
2425 $where_clauses = array(
2426 'il_to' => $this->getDBkey(),
2431 $tables = array( 'templatelinks', 'page_restrictions' );
2432 $where_clauses = array(
2433 'tl_namespace' => $this->getNamespace(),
2434 'tl_title' => $this->getDBkey(),
2441 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2442 'pr_expiry', 'pr_type', 'pr_level' );
2443 $where_clauses[] = 'page_id=pr_page';
2446 $cols = array( 'pr_expiry' );
2449 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2451 $sources = $getPages ?
array() : false;
2452 $now = wfTimestampNow();
2453 $purgeExpired = false;
2455 foreach ( $res as $row ) {
2456 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2457 if ( $expiry > $now ) {
2459 $page_id = $row->pr_page
;
2460 $page_ns = $row->page_namespace
;
2461 $page_title = $row->page_title
;
2462 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2463 # Add groups needed for each restriction type if its not already there
2464 # Make sure this restriction type still exists
2466 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2467 $pagerestrictions[$row->pr_type
] = array();
2470 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2471 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2472 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2478 // Trigger lazy purge of expired restrictions from the db
2479 $purgeExpired = true;
2482 if ( $purgeExpired ) {
2483 Title
::purgeExpiredRestrictions();
2487 $this->mCascadeSources
= $sources;
2488 $this->mCascadingRestrictions
= $pagerestrictions;
2490 $this->mHasCascadingRestrictions
= $sources;
2493 wfProfileOut( __METHOD__
);
2494 return array( $sources, $pagerestrictions );
2498 * Accessor/initialisation for mRestrictions
2500 * @param $action String action that permission needs to be checked for
2501 * @return Array of Strings the array of groups allowed to edit this article
2503 public function getRestrictions( $action ) {
2504 if ( !$this->mRestrictionsLoaded
) {
2505 $this->loadRestrictions();
2507 return isset( $this->mRestrictions
[$action] )
2508 ?
$this->mRestrictions
[$action]
2513 * Get the expiry time for the restriction against a given action
2515 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2516 * or not protected at all, or false if the action is not recognised.
2518 public function getRestrictionExpiry( $action ) {
2519 if ( !$this->mRestrictionsLoaded
) {
2520 $this->loadRestrictions();
2522 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2526 * Returns cascading restrictions for the current article
2530 function areRestrictionsCascading() {
2531 if ( !$this->mRestrictionsLoaded
) {
2532 $this->loadRestrictions();
2535 return $this->mCascadeRestriction
;
2539 * Loads a string into mRestrictions array
2541 * @param $res Resource restrictions as an SQL result.
2542 * @param $oldFashionedRestrictions String comma-separated list of page
2543 * restrictions from page table (pre 1.10)
2545 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2548 foreach ( $res as $row ) {
2552 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2556 * Compiles list of active page restrictions from both page table (pre 1.10)
2557 * and page_restrictions table for this existing page.
2558 * Public for usage by LiquidThreads.
2560 * @param $rows array of db result objects
2561 * @param $oldFashionedRestrictions string comma-separated list of page
2562 * restrictions from page table (pre 1.10)
2564 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2566 $dbr = wfGetDB( DB_SLAVE
);
2568 $restrictionTypes = $this->getRestrictionTypes();
2570 foreach ( $restrictionTypes as $type ) {
2571 $this->mRestrictions
[$type] = array();
2572 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2575 $this->mCascadeRestriction
= false;
2577 # Backwards-compatibility: also load the restrictions from the page record (old format).
2579 if ( $oldFashionedRestrictions === null ) {
2580 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2581 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2584 if ( $oldFashionedRestrictions != '' ) {
2586 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2587 $temp = explode( '=', trim( $restrict ) );
2588 if ( count( $temp ) == 1 ) {
2589 // old old format should be treated as edit/move restriction
2590 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2591 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2593 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2597 $this->mOldRestrictions
= true;
2601 if ( count( $rows ) ) {
2602 # Current system - load second to make them override.
2603 $now = wfTimestampNow();
2604 $purgeExpired = false;
2606 # Cycle through all the restrictions.
2607 foreach ( $rows as $row ) {
2609 // Don't take care of restrictions types that aren't allowed
2610 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2613 // This code should be refactored, now that it's being used more generally,
2614 // But I don't really see any harm in leaving it in Block for now -werdna
2615 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2617 // Only apply the restrictions if they haven't expired!
2618 if ( !$expiry ||
$expiry > $now ) {
2619 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2620 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2622 $this->mCascadeRestriction |
= $row->pr_cascade
;
2624 // Trigger a lazy purge of expired restrictions
2625 $purgeExpired = true;
2629 if ( $purgeExpired ) {
2630 Title
::purgeExpiredRestrictions();
2634 $this->mRestrictionsLoaded
= true;
2638 * Load restrictions from the page_restrictions table
2640 * @param $oldFashionedRestrictions String comma-separated list of page
2641 * restrictions from page table (pre 1.10)
2643 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2645 if ( !$this->mRestrictionsLoaded
) {
2646 if ( $this->exists() ) {
2647 $dbr = wfGetDB( DB_SLAVE
);
2649 $res = $dbr->select(
2650 'page_restrictions',
2652 array( 'pr_page' => $this->getArticleID() ),
2656 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2658 $title_protection = $this->getTitleProtection();
2660 if ( $title_protection ) {
2661 $now = wfTimestampNow();
2662 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2664 if ( !$expiry ||
$expiry > $now ) {
2665 // Apply the restrictions
2666 $this->mRestrictionsExpiry
['create'] = $expiry;
2667 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2668 } else { // Get rid of the old restrictions
2669 Title
::purgeExpiredRestrictions();
2670 $this->mTitleProtection
= false;
2673 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2675 $this->mRestrictionsLoaded
= true;
2681 * Flush the protection cache in this object and force reload from the database.
2682 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2684 public function flushRestrictions() {
2685 $this->mRestrictionsLoaded
= false;
2686 $this->mTitleProtection
= null;
2690 * Purge expired restrictions from the page_restrictions table
2692 static function purgeExpiredRestrictions() {
2693 $dbw = wfGetDB( DB_MASTER
);
2695 'page_restrictions',
2696 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2702 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2708 * Does this have subpages? (Warning, usually requires an extra DB query.)
2712 public function hasSubpages() {
2713 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2718 # We dynamically add a member variable for the purpose of this method
2719 # alone to cache the result. There's no point in having it hanging
2720 # around uninitialized in every Title object; therefore we only add it
2721 # if needed and don't declare it statically.
2722 if ( isset( $this->mHasSubpages
) ) {
2723 return $this->mHasSubpages
;
2726 $subpages = $this->getSubpages( 1 );
2727 if ( $subpages instanceof TitleArray
) {
2728 return $this->mHasSubpages
= (bool)$subpages->count();
2730 return $this->mHasSubpages
= false;
2734 * Get all subpages of this page.
2736 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2737 * @return mixed TitleArray, or empty array if this page's namespace
2738 * doesn't allow subpages
2740 public function getSubpages( $limit = -1 ) {
2741 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2745 $dbr = wfGetDB( DB_SLAVE
);
2746 $conds['page_namespace'] = $this->getNamespace();
2747 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2749 if ( $limit > -1 ) {
2750 $options['LIMIT'] = $limit;
2752 return $this->mSubpages
= TitleArray
::newFromResult(
2753 $dbr->select( 'page',
2754 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2763 * Is there a version of this page in the deletion archive?
2765 * @return Int the number of archived revisions
2767 public function isDeleted() {
2768 if ( $this->getNamespace() < 0 ) {
2771 $dbr = wfGetDB( DB_SLAVE
);
2773 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2774 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2777 if ( $this->getNamespace() == NS_FILE
) {
2778 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2779 array( 'fa_name' => $this->getDBkey() ),
2788 * Is there a version of this page in the deletion archive?
2792 public function isDeletedQuick() {
2793 if ( $this->getNamespace() < 0 ) {
2796 $dbr = wfGetDB( DB_SLAVE
);
2797 $deleted = (bool)$dbr->selectField( 'archive', '1',
2798 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2801 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2802 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2803 array( 'fa_name' => $this->getDBkey() ),
2811 * Get the article ID for this Title from the link cache,
2812 * adding it if necessary
2814 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2816 * @return Int the ID
2818 public function getArticleID( $flags = 0 ) {
2819 if ( $this->getNamespace() < 0 ) {
2820 return $this->mArticleID
= 0;
2822 $linkCache = LinkCache
::singleton();
2823 if ( $flags & self
::GAID_FOR_UPDATE
) {
2824 $oldUpdate = $linkCache->forUpdate( true );
2825 $linkCache->clearLink( $this );
2826 $this->mArticleID
= $linkCache->addLinkObj( $this );
2827 $linkCache->forUpdate( $oldUpdate );
2829 if ( -1 == $this->mArticleID
) {
2830 $this->mArticleID
= $linkCache->addLinkObj( $this );
2833 return $this->mArticleID
;
2837 * Is this an article that is a redirect page?
2838 * Uses link cache, adding it if necessary
2840 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2843 public function isRedirect( $flags = 0 ) {
2844 if ( !is_null( $this->mRedirect
) ) {
2845 return $this->mRedirect
;
2847 # Calling getArticleID() loads the field from cache as needed
2848 if ( !$this->getArticleID( $flags ) ) {
2849 return $this->mRedirect
= false;
2851 $linkCache = LinkCache
::singleton();
2852 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2854 return $this->mRedirect
;
2858 * What is the length of this page?
2859 * Uses link cache, adding it if necessary
2861 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2864 public function getLength( $flags = 0 ) {
2865 if ( $this->mLength
!= -1 ) {
2866 return $this->mLength
;
2868 # Calling getArticleID() loads the field from cache as needed
2869 if ( !$this->getArticleID( $flags ) ) {
2870 return $this->mLength
= 0;
2872 $linkCache = LinkCache
::singleton();
2873 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2875 return $this->mLength
;
2879 * What is the page_latest field for this page?
2881 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2882 * @return Int or 0 if the page doesn't exist
2884 public function getLatestRevID( $flags = 0 ) {
2885 if ( $this->mLatestID
!== false ) {
2886 return intval( $this->mLatestID
);
2888 # Calling getArticleID() loads the field from cache as needed
2889 if ( !$this->getArticleID( $flags ) ) {
2890 return $this->mLatestID
= 0;
2892 $linkCache = LinkCache
::singleton();
2893 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2895 return $this->mLatestID
;
2899 * This clears some fields in this object, and clears any associated
2900 * keys in the "bad links" section of the link cache.
2902 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2903 * loading of the new page_id. It's also called from
2904 * WikiPage::doDeleteArticle()
2906 * @param $newid Int the new Article ID
2908 public function resetArticleID( $newid ) {
2909 $linkCache = LinkCache
::singleton();
2910 $linkCache->clearLink( $this );
2912 if ( $newid === false ) {
2913 $this->mArticleID
= -1;
2915 $this->mArticleID
= intval( $newid );
2917 $this->mRestrictionsLoaded
= false;
2918 $this->mRestrictions
= array();
2919 $this->mRedirect
= null;
2920 $this->mLength
= -1;
2921 $this->mLatestID
= false;
2922 $this->mEstimateRevisions
= null;
2926 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2928 * @param $text String containing title to capitalize
2929 * @param $ns int namespace index, defaults to NS_MAIN
2930 * @return String containing capitalized title
2932 public static function capitalize( $text, $ns = NS_MAIN
) {
2935 if ( MWNamespace
::isCapitalized( $ns ) ) {
2936 return $wgContLang->ucfirst( $text );
2943 * Secure and split - main initialisation function for this object
2945 * Assumes that mDbkeyform has been set, and is urldecoded
2946 * and uses underscores, but not otherwise munged. This function
2947 * removes illegal characters, splits off the interwiki and
2948 * namespace prefixes, sets the other forms, and canonicalizes
2951 * @return Bool true on success
2953 private function secureAndSplit() {
2954 global $wgContLang, $wgLocalInterwiki;
2957 $this->mInterwiki
= $this->mFragment
= '';
2958 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2960 $dbkey = $this->mDbkeyform
;
2962 # Strip Unicode bidi override characters.
2963 # Sometimes they slip into cut-n-pasted page titles, where the
2964 # override chars get included in list displays.
2965 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2967 # Clean up whitespace
2968 # Note: use of the /u option on preg_replace here will cause
2969 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2970 # conveniently disabling them.
2971 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2972 $dbkey = trim( $dbkey, '_' );
2974 if ( $dbkey == '' ) {
2978 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2979 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2983 $this->mDbkeyform
= $dbkey;
2985 # Initial colon indicates main namespace rather than specified default
2986 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2987 if ( ':' == $dbkey[0] ) {
2988 $this->mNamespace
= NS_MAIN
;
2989 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2990 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2993 # Namespace or interwiki prefix
2995 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2998 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3000 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3001 # Ordinary namespace
3003 $this->mNamespace
= $ns;
3004 # For Talk:X pages, check if X has a "namespace" prefix
3005 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3006 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3007 # Disallow Talk:File:x type titles...
3009 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3010 # Disallow Talk:Interwiki:x type titles...
3014 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3015 if ( !$firstPass ) {
3016 # Can't make a local interwiki link to an interwiki link.
3017 # That's just crazy!
3023 $this->mInterwiki
= $wgContLang->lc( $p );
3025 # Redundant interwiki prefix to the local wiki
3026 if ( $wgLocalInterwiki !== false
3027 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3029 if ( $dbkey == '' ) {
3030 # Can't have an empty self-link
3033 $this->mInterwiki
= '';
3035 # Do another namespace split...
3039 # If there's an initial colon after the interwiki, that also
3040 # resets the default namespace
3041 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3042 $this->mNamespace
= NS_MAIN
;
3043 $dbkey = substr( $dbkey, 1 );
3046 # If there's no recognized interwiki or namespace,
3047 # then let the colon expression be part of the title.
3052 # We already know that some pages won't be in the database!
3053 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3054 $this->mArticleID
= 0;
3056 $fragment = strstr( $dbkey, '#' );
3057 if ( false !== $fragment ) {
3058 $this->setFragment( $fragment );
3059 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3060 # remove whitespace again: prevents "Foo_bar_#"
3061 # becoming "Foo_bar_"
3062 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3065 # Reject illegal characters.
3066 $rxTc = self
::getTitleInvalidRegex();
3067 if ( preg_match( $rxTc, $dbkey ) ) {
3071 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3072 # reachable due to the way web browsers deal with 'relative' URLs.
3073 # Also, they conflict with subpage syntax. Forbid them explicitly.
3074 if ( strpos( $dbkey, '.' ) !== false &&
3075 ( $dbkey === '.' ||
$dbkey === '..' ||
3076 strpos( $dbkey, './' ) === 0 ||
3077 strpos( $dbkey, '../' ) === 0 ||
3078 strpos( $dbkey, '/./' ) !== false ||
3079 strpos( $dbkey, '/../' ) !== false ||
3080 substr( $dbkey, -2 ) == '/.' ||
3081 substr( $dbkey, -3 ) == '/..' ) )
3086 # Magic tilde sequences? Nu-uh!
3087 if ( strpos( $dbkey, '~~~' ) !== false ) {
3091 # Limit the size of titles to 255 bytes. This is typically the size of the
3092 # underlying database field. We make an exception for special pages, which
3093 # don't need to be stored in the database, and may edge over 255 bytes due
3094 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3095 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3096 strlen( $dbkey ) > 512 )
3101 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3102 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3103 # other site might be case-sensitive.
3104 $this->mUserCaseDBKey
= $dbkey;
3105 if ( $this->mInterwiki
== '' ) {
3106 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3109 # Can't make a link to a namespace alone... "empty" local links can only be
3110 # self-links with a fragment identifier.
3111 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3115 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3116 // IP names are not allowed for accounts, and can only be referring to
3117 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3118 // there are numerous ways to present the same IP. Having sp:contribs scan
3119 // them all is silly and having some show the edits and others not is
3120 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3121 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3122 ? IP
::sanitizeIP( $dbkey )
3125 // Any remaining initial :s are illegal.
3126 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3131 $this->mDbkeyform
= $dbkey;
3132 $this->mUrlform
= wfUrlencode( $dbkey );
3134 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3140 * Get an array of Title objects linking to this Title
3141 * Also stores the IDs in the link cache.
3143 * WARNING: do not use this function on arbitrary user-supplied titles!
3144 * On heavily-used templates it will max out the memory.
3146 * @param $options Array: may be FOR UPDATE
3147 * @param $table String: table name
3148 * @param $prefix String: fields prefix
3149 * @return Array of Title objects linking here
3151 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3152 if ( count( $options ) > 0 ) {
3153 $db = wfGetDB( DB_MASTER
);
3155 $db = wfGetDB( DB_SLAVE
);
3159 array( 'page', $table ),
3160 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3162 "{$prefix}_from=page_id",
3163 "{$prefix}_namespace" => $this->getNamespace(),
3164 "{$prefix}_title" => $this->getDBkey() ),
3170 if ( $res->numRows() ) {
3171 $linkCache = LinkCache
::singleton();
3172 foreach ( $res as $row ) {
3173 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3175 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3176 $retVal[] = $titleObj;
3184 * Get an array of Title objects using this Title as a template
3185 * Also stores the IDs in the link cache.
3187 * WARNING: do not use this function on arbitrary user-supplied titles!
3188 * On heavily-used templates it will max out the memory.
3190 * @param $options Array: may be FOR UPDATE
3191 * @return Array of Title the Title objects linking here
3193 public function getTemplateLinksTo( $options = array() ) {
3194 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3198 * Get an array of Title objects linked from this Title
3199 * Also stores the IDs in the link cache.
3201 * WARNING: do not use this function on arbitrary user-supplied titles!
3202 * On heavily-used templates it will max out the memory.
3204 * @param $options Array: may be FOR UPDATE
3205 * @param $table String: table name
3206 * @param $prefix String: fields prefix
3207 * @return Array of Title objects linking here
3209 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3210 $id = $this->getArticleID();
3212 # If the page doesn't exist; there can't be any link from this page
3217 if ( count( $options ) > 0 ) {
3218 $db = wfGetDB( DB_MASTER
);
3220 $db = wfGetDB( DB_SLAVE
);
3223 $namespaceFiled = "{$prefix}_namespace";
3224 $titleField = "{$prefix}_title";
3227 array( $table, 'page' ),
3228 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3229 array( "{$prefix}_from" => $id ),
3232 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3236 if ( $res->numRows() ) {
3237 $linkCache = LinkCache
::singleton();
3238 foreach ( $res as $row ) {
3239 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3241 if ( $row->page_id
) {
3242 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3244 $linkCache->addBadLinkObj( $titleObj );
3246 $retVal[] = $titleObj;
3254 * Get an array of Title objects used on this Title as a template
3255 * Also stores the IDs in the link cache.
3257 * WARNING: do not use this function on arbitrary user-supplied titles!
3258 * On heavily-used templates it will max out the memory.
3260 * @param $options Array: may be FOR UPDATE
3261 * @return Array of Title the Title objects used here
3263 public function getTemplateLinksFrom( $options = array() ) {
3264 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3268 * Get an array of Title objects referring to non-existent articles linked from this page
3270 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3271 * @return Array of Title the Title objects
3273 public function getBrokenLinksFrom() {
3274 if ( $this->getArticleID() == 0 ) {
3275 # All links from article ID 0 are false positives
3279 $dbr = wfGetDB( DB_SLAVE
);
3280 $res = $dbr->select(
3281 array( 'page', 'pagelinks' ),
3282 array( 'pl_namespace', 'pl_title' ),
3284 'pl_from' => $this->getArticleID(),
3285 'page_namespace IS NULL'
3287 __METHOD__
, array(),
3291 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3297 foreach ( $res as $row ) {
3298 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3305 * Get a list of URLs to purge from the Squid cache when this
3308 * @return Array of String the URLs
3310 public function getSquidURLs() {
3314 $this->getInternalURL(),
3315 $this->getInternalURL( 'action=history' )
3318 // purge variant urls as well
3319 if ( $wgContLang->hasVariants() ) {
3320 $variants = $wgContLang->getVariants();
3321 foreach ( $variants as $vCode ) {
3322 $urls[] = $this->getInternalURL( '', $vCode );
3330 * Purge all applicable Squid URLs
3332 public function purgeSquid() {
3334 if ( $wgUseSquid ) {
3335 $urls = $this->getSquidURLs();
3336 $u = new SquidUpdate( $urls );
3342 * Move this page without authentication
3344 * @param $nt Title the new page Title
3345 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3347 public function moveNoAuth( &$nt ) {
3348 return $this->moveTo( $nt, false );
3352 * Check whether a given move operation would be valid.
3353 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3355 * @param $nt Title the new title
3356 * @param $auth Bool indicates whether $wgUser's permissions
3358 * @param $reason String is the log summary of the move, used for spam checking
3359 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3361 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3366 // Normally we'd add this to $errors, but we'll get
3367 // lots of syntax errors if $nt is not an object
3368 return array( array( 'badtitletext' ) );
3370 if ( $this->equals( $nt ) ) {
3371 $errors[] = array( 'selfmove' );
3373 if ( !$this->isMovable() ) {
3374 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3376 if ( $nt->getInterwiki() != '' ) {
3377 $errors[] = array( 'immobile-target-namespace-iw' );
3379 if ( !$nt->isMovable() ) {
3380 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3383 $oldid = $this->getArticleID();
3384 $newid = $nt->getArticleID();
3386 if ( strlen( $nt->getDBkey() ) < 1 ) {
3387 $errors[] = array( 'articleexists' );
3389 if ( ( $this->getDBkey() == '' ) ||
3391 ( $nt->getDBkey() == '' ) ) {
3392 $errors[] = array( 'badarticleerror' );
3395 // Image-specific checks
3396 if ( $this->getNamespace() == NS_FILE
) {
3397 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3400 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3401 $errors[] = array( 'nonfile-cannot-move-to-file' );
3405 $errors = wfMergeErrorArrays( $errors,
3406 $this->getUserPermissionsErrors( 'move', $wgUser ),
3407 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3408 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3409 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3412 $match = EditPage
::matchSummarySpamRegex( $reason );
3413 if ( $match !== false ) {
3414 // This is kind of lame, won't display nice
3415 $errors[] = array( 'spamprotectiontext' );
3419 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3420 $errors[] = array( 'hookaborted', $err );
3423 # The move is allowed only if (1) the target doesn't exist, or
3424 # (2) the target is a redirect to the source, and has no history
3425 # (so we can undo bad moves right after they're done).
3427 if ( 0 != $newid ) { # Target exists; check for validity
3428 if ( !$this->isValidMoveTarget( $nt ) ) {
3429 $errors[] = array( 'articleexists' );
3432 $tp = $nt->getTitleProtection();
3433 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3434 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3435 $errors[] = array( 'cantmove-titleprotected' );
3438 if ( empty( $errors ) ) {
3445 * Check if the requested move target is a valid file move target
3446 * @param Title $nt Target title
3447 * @return array List of errors
3449 protected function validateFileMoveOperation( $nt ) {
3454 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3456 $file = wfLocalFile( $this );
3457 if ( $file->exists() ) {
3458 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3459 $errors[] = array( 'imageinvalidfilename' );
3461 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3462 $errors[] = array( 'imagetypemismatch' );
3466 if ( $nt->getNamespace() != NS_FILE
) {
3467 $errors[] = array( 'imagenocrossnamespace' );
3468 // From here we want to do checks on a file object, so if we can't
3469 // create one, we must return.
3473 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3475 $destFile = wfLocalFile( $nt );
3476 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3477 $errors[] = array( 'file-exists-sharedrepo' );
3484 * Move a title to a new location
3486 * @param $nt Title the new title
3487 * @param $auth Bool indicates whether $wgUser's permissions
3489 * @param $reason String the reason for the move
3490 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3491 * Ignored if the user doesn't have the suppressredirect right.
3492 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3494 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3496 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3497 if ( is_array( $err ) ) {
3498 // Auto-block user's IP if the account was "hard" blocked
3499 $wgUser->spreadAnyEditBlock();
3503 // If it is a file, move it first.
3504 // It is done before all other moving stuff is done because it's hard to revert.
3505 $dbw = wfGetDB( DB_MASTER
);
3506 if ( $this->getNamespace() == NS_FILE
) {
3507 $file = wfLocalFile( $this );
3508 if ( $file->exists() ) {
3509 $status = $file->move( $nt );
3510 if ( !$status->isOk() ) {
3511 return $status->getErrorsArray();
3514 // Clear RepoGroup process cache
3515 RepoGroup
::singleton()->clearCache( $this );
3516 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3519 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3520 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3521 $protected = $this->isProtected();
3523 // Do the actual move
3524 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3525 if ( is_array( $err ) ) {
3526 # @todo FIXME: What about the File we have already moved?
3527 $dbw->rollback( __METHOD__
);
3531 // Refresh the sortkey for this row. Be careful to avoid resetting
3532 // cl_timestamp, which may disturb time-based lists on some sites.
3533 $prefixes = $dbw->select(
3535 array( 'cl_sortkey_prefix', 'cl_to' ),
3536 array( 'cl_from' => $pageid ),
3539 foreach ( $prefixes as $prefixRow ) {
3540 $prefix = $prefixRow->cl_sortkey_prefix
;
3541 $catTo = $prefixRow->cl_to
;
3542 $dbw->update( 'categorylinks',
3544 'cl_sortkey' => Collation
::singleton()->getSortKey(
3545 $nt->getCategorySortkey( $prefix ) ),
3546 'cl_timestamp=cl_timestamp' ),
3548 'cl_from' => $pageid,
3549 'cl_to' => $catTo ),
3554 $redirid = $this->getArticleID();
3557 # Protect the redirect title as the title used to be...
3558 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3560 'pr_page' => $redirid,
3561 'pr_type' => 'pr_type',
3562 'pr_level' => 'pr_level',
3563 'pr_cascade' => 'pr_cascade',
3564 'pr_user' => 'pr_user',
3565 'pr_expiry' => 'pr_expiry'
3567 array( 'pr_page' => $pageid ),
3571 # Update the protection log
3572 $log = new LogPage( 'protect' );
3573 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3575 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3577 // @todo FIXME: $params?
3578 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3582 $oldnamespace = $this->getNamespace() & ~
1;
3583 $newnamespace = $nt->getNamespace() & ~
1;
3584 $oldtitle = $this->getDBkey();
3585 $newtitle = $nt->getDBkey();
3587 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3588 WatchedItem
::duplicateEntries( $this, $nt );
3591 $dbw->commit( __METHOD__
);
3593 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3598 * Move page to a title which is either a redirect to the
3599 * source page or nonexistent
3601 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3602 * @param $reason String The reason for the move
3603 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3604 * if the user doesn't have the suppressredirect right
3606 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3607 global $wgUser, $wgContLang;
3609 if ( $nt->exists() ) {
3610 $moveOverRedirect = true;
3611 $logType = 'move_redir';
3613 $moveOverRedirect = false;
3617 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3619 $logEntry = new ManualLogEntry( 'move', $logType );
3620 $logEntry->setPerformer( $wgUser );
3621 $logEntry->setTarget( $this );
3622 $logEntry->setComment( $reason );
3623 $logEntry->setParameters( array(
3624 '4::target' => $nt->getPrefixedText(),
3625 '5::noredir' => $redirectSuppressed ?
'1': '0',
3628 $formatter = LogFormatter
::newFromEntry( $logEntry );
3629 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3630 $comment = $formatter->getPlainActionText();
3632 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3634 # Truncate for whole multibyte characters.
3635 $comment = $wgContLang->truncate( $comment, 255 );
3637 $oldid = $this->getArticleID();
3639 $dbw = wfGetDB( DB_MASTER
);
3641 $newpage = WikiPage
::factory( $nt );
3643 if ( $moveOverRedirect ) {
3644 $newid = $nt->getArticleID();
3646 # Delete the old redirect. We don't save it to history since
3647 # by definition if we've got here it's rather uninteresting.
3648 # We have to remove it so that the next step doesn't trigger
3649 # a conflict on the unique namespace+title index...
3650 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3652 $newpage->doDeleteUpdates( $newid );
3655 # Save a null revision in the page's history notifying of the move
3656 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3657 if ( !is_object( $nullRevision ) ) {
3658 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3660 $nullRevId = $nullRevision->insertOn( $dbw );
3662 # Change the name of the target page:
3663 $dbw->update( 'page',
3665 'page_namespace' => $nt->getNamespace(),
3666 'page_title' => $nt->getDBkey(),
3668 /* WHERE */ array( 'page_id' => $oldid ),
3672 $this->resetArticleID( 0 );
3673 $nt->resetArticleID( $oldid );
3675 $newpage->updateRevisionOn( $dbw, $nullRevision );
3677 wfRunHooks( 'NewRevisionFromEditComplete',
3678 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3680 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3682 if ( !$moveOverRedirect ) {
3683 WikiPage
::onArticleCreate( $nt );
3686 # Recreate the redirect, this time in the other direction.
3687 if ( $redirectSuppressed ) {
3688 WikiPage
::onArticleDelete( $this );
3690 $mwRedir = MagicWord
::get( 'redirect' );
3691 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3692 $redirectArticle = WikiPage
::factory( $this );
3693 $newid = $redirectArticle->insertOn( $dbw );
3694 if ( $newid ) { // sanity
3695 $redirectRevision = new Revision( array(
3697 'comment' => $comment,
3698 'text' => $redirectText ) );
3699 $redirectRevision->insertOn( $dbw );
3700 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3702 wfRunHooks( 'NewRevisionFromEditComplete',
3703 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3705 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3710 $logid = $logEntry->insert();
3711 $logEntry->publish( $logid );
3715 * Move this page's subpages to be subpages of $nt
3717 * @param $nt Title Move target
3718 * @param $auth bool Whether $wgUser's permissions should be checked
3719 * @param $reason string The reason for the move
3720 * @param $createRedirect bool Whether to create redirects from the old subpages to
3721 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3722 * @return mixed array with old page titles as keys, and strings (new page titles) or
3723 * arrays (errors) as values, or an error array with numeric indices if no pages
3726 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3727 global $wgMaximumMovedPages;
3728 // Check permissions
3729 if ( !$this->userCan( 'move-subpages' ) ) {
3730 return array( 'cant-move-subpages' );
3732 // Do the source and target namespaces support subpages?
3733 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3734 return array( 'namespace-nosubpages',
3735 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3737 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3738 return array( 'namespace-nosubpages',
3739 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3742 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3745 foreach ( $subpages as $oldSubpage ) {
3747 if ( $count > $wgMaximumMovedPages ) {
3748 $retval[$oldSubpage->getPrefixedTitle()] =
3749 array( 'movepage-max-pages',
3750 $wgMaximumMovedPages );
3754 // We don't know whether this function was called before
3755 // or after moving the root page, so check both
3757 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3758 $oldSubpage->getArticleID() == $nt->getArticleID() )
3760 // When moving a page to a subpage of itself,
3761 // don't move it twice
3764 $newPageName = preg_replace(
3765 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3766 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3767 $oldSubpage->getDBkey() );
3768 if ( $oldSubpage->isTalkPage() ) {
3769 $newNs = $nt->getTalkPage()->getNamespace();
3771 $newNs = $nt->getSubjectPage()->getNamespace();
3773 # Bug 14385: we need makeTitleSafe because the new page names may
3774 # be longer than 255 characters.
3775 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3777 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3778 if ( $success === true ) {
3779 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3781 $retval[$oldSubpage->getPrefixedText()] = $success;
3788 * Checks if this page is just a one-rev redirect.
3789 * Adds lock, so don't use just for light purposes.
3793 public function isSingleRevRedirect() {
3794 $dbw = wfGetDB( DB_MASTER
);
3796 $row = $dbw->selectRow( 'page',
3797 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3800 array( 'FOR UPDATE' )
3802 # Cache some fields we may want
3803 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3804 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3805 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3806 if ( !$this->mRedirect
) {
3809 # Does the article have a history?
3810 $row = $dbw->selectField( array( 'page', 'revision' ),
3812 array( 'page_namespace' => $this->getNamespace(),
3813 'page_title' => $this->getDBkey(),
3815 'page_latest != rev_id'
3818 array( 'FOR UPDATE' )
3820 # Return true if there was no history
3821 return ( $row === false );
3825 * Checks if $this can be moved to a given Title
3826 * - Selects for update, so don't call it unless you mean business
3828 * @param $nt Title the new title to check
3831 public function isValidMoveTarget( $nt ) {
3832 # Is it an existing file?
3833 if ( $nt->getNamespace() == NS_FILE
) {
3834 $file = wfLocalFile( $nt );
3835 if ( $file->exists() ) {
3836 wfDebug( __METHOD__
. ": file exists\n" );
3840 # Is it a redirect with no history?
3841 if ( !$nt->isSingleRevRedirect() ) {
3842 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3845 # Get the article text
3846 $rev = Revision
::newFromTitle( $nt );
3847 if( !is_object( $rev ) ){
3850 $text = $rev->getText();
3851 # Does the redirect point to the source?
3852 # Or is it a broken self-redirect, usually caused by namespace collisions?
3854 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3855 $redirTitle = Title
::newFromText( $m[1] );
3856 if ( !is_object( $redirTitle ) ||
3857 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3858 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3859 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3864 wfDebug( __METHOD__
. ": failsafe\n" );
3871 * Get categories to which this Title belongs and return an array of
3872 * categories' names.
3874 * @return Array of parents in the form:
3875 * $parent => $currentarticle
3877 public function getParentCategories() {
3882 $titleKey = $this->getArticleID();
3884 if ( $titleKey === 0 ) {
3888 $dbr = wfGetDB( DB_SLAVE
);
3890 $res = $dbr->select( 'categorylinks', '*',
3892 'cl_from' => $titleKey,
3898 if ( $dbr->numRows( $res ) > 0 ) {
3899 foreach ( $res as $row ) {
3900 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3901 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3908 * Get a tree of parent categories
3910 * @param $children Array with the children in the keys, to check for circular refs
3911 * @return Array Tree of parent categories
3913 public function getParentCategoryTree( $children = array() ) {
3915 $parents = $this->getParentCategories();
3918 foreach ( $parents as $parent => $current ) {
3919 if ( array_key_exists( $parent, $children ) ) {
3920 # Circular reference
3921 $stack[$parent] = array();
3923 $nt = Title
::newFromText( $parent );
3925 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3935 * Get an associative array for selecting this title from
3938 * @return Array suitable for the $where parameter of DB::select()
3940 public function pageCond() {
3941 if ( $this->mArticleID
> 0 ) {
3942 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3943 return array( 'page_id' => $this->mArticleID
);
3945 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3950 * Get the revision ID of the previous revision
3952 * @param $revId Int Revision ID. Get the revision that was before this one.
3953 * @param $flags Int Title::GAID_FOR_UPDATE
3954 * @return Int|Bool Old revision ID, or FALSE if none exists
3956 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3957 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3958 return $db->selectField( 'revision', 'rev_id',
3960 'rev_page' => $this->getArticleID( $flags ),
3961 'rev_id < ' . intval( $revId )
3964 array( 'ORDER BY' => 'rev_id DESC' )
3969 * Get the revision ID of the next revision
3971 * @param $revId Int Revision ID. Get the revision that was after this one.
3972 * @param $flags Int Title::GAID_FOR_UPDATE
3973 * @return Int|Bool Next revision ID, or FALSE if none exists
3975 public function getNextRevisionID( $revId, $flags = 0 ) {
3976 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3977 return $db->selectField( 'revision', 'rev_id',
3979 'rev_page' => $this->getArticleID( $flags ),
3980 'rev_id > ' . intval( $revId )
3983 array( 'ORDER BY' => 'rev_id' )
3988 * Get the first revision of the page
3990 * @param $flags Int Title::GAID_FOR_UPDATE
3991 * @return Revision|Null if page doesn't exist
3993 public function getFirstRevision( $flags = 0 ) {
3994 $pageId = $this->getArticleID( $flags );
3996 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3997 $row = $db->selectRow( 'revision', '*',
3998 array( 'rev_page' => $pageId ),
4000 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4003 return new Revision( $row );
4010 * Get the oldest revision timestamp of this page
4012 * @param $flags Int Title::GAID_FOR_UPDATE
4013 * @return String: MW timestamp
4015 public function getEarliestRevTime( $flags = 0 ) {
4016 $rev = $this->getFirstRevision( $flags );
4017 return $rev ?
$rev->getTimestamp() : null;
4021 * Check if this is a new page
4025 public function isNewPage() {
4026 $dbr = wfGetDB( DB_SLAVE
);
4027 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4031 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4035 public function isBigDeletion() {
4036 global $wgDeleteRevisionsLimit;
4038 if ( !$wgDeleteRevisionsLimit ) {
4042 $revCount = $this->estimateRevisionCount();
4043 return $revCount > $wgDeleteRevisionsLimit;
4047 * Get the approximate revision count of this page.
4051 public function estimateRevisionCount() {
4052 if ( !$this->exists() ) {
4056 if ( $this->mEstimateRevisions
=== null ) {
4057 $dbr = wfGetDB( DB_SLAVE
);
4058 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4059 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4062 return $this->mEstimateRevisions
;
4066 * Get the number of revisions between the given revision.
4067 * Used for diffs and other things that really need it.
4069 * @param $old int|Revision Old revision or rev ID (first before range)
4070 * @param $new int|Revision New revision or rev ID (first after range)
4071 * @return Int Number of revisions between these revisions.
4073 public function countRevisionsBetween( $old, $new ) {
4074 if ( !( $old instanceof Revision
) ) {
4075 $old = Revision
::newFromTitle( $this, (int)$old );
4077 if ( !( $new instanceof Revision
) ) {
4078 $new = Revision
::newFromTitle( $this, (int)$new );
4080 if ( !$old ||
!$new ) {
4081 return 0; // nothing to compare
4083 $dbr = wfGetDB( DB_SLAVE
);
4084 return (int)$dbr->selectField( 'revision', 'count(*)',
4086 'rev_page' => $this->getArticleID(),
4087 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4088 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4095 * Get the number of authors between the given revision IDs.
4096 * Used for diffs and other things that really need it.
4098 * @param $old int|Revision Old revision or rev ID (first before range)
4099 * @param $new int|Revision New revision or rev ID (first after range)
4100 * @param $limit Int Maximum number of authors
4101 * @return Int Number of revision authors between these revisions.
4103 public function countAuthorsBetween( $old, $new, $limit ) {
4104 if ( !( $old instanceof Revision
) ) {
4105 $old = Revision
::newFromTitle( $this, (int)$old );
4107 if ( !( $new instanceof Revision
) ) {
4108 $new = Revision
::newFromTitle( $this, (int)$new );
4110 if ( !$old ||
!$new ) {
4111 return 0; // nothing to compare
4113 $dbr = wfGetDB( DB_SLAVE
);
4114 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4116 'rev_page' => $this->getArticleID(),
4117 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4118 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4120 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4122 return (int)$dbr->numRows( $res );
4126 * Compare with another title.
4128 * @param $title Title
4131 public function equals( Title
$title ) {
4132 // Note: === is necessary for proper matching of number-like titles.
4133 return $this->getInterwiki() === $title->getInterwiki()
4134 && $this->getNamespace() == $title->getNamespace()
4135 && $this->getDBkey() === $title->getDBkey();
4139 * Check if this title is a subpage of another title
4141 * @param $title Title
4144 public function isSubpageOf( Title
$title ) {
4145 return $this->getInterwiki() === $title->getInterwiki()
4146 && $this->getNamespace() == $title->getNamespace()
4147 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4151 * Check if page exists. For historical reasons, this function simply
4152 * checks for the existence of the title in the page table, and will
4153 * thus return false for interwiki links, special pages and the like.
4154 * If you want to know if a title can be meaningfully viewed, you should
4155 * probably call the isKnown() method instead.
4159 public function exists() {
4160 return $this->getArticleID() != 0;
4164 * Should links to this title be shown as potentially viewable (i.e. as
4165 * "bluelinks"), even if there's no record by this title in the page
4168 * This function is semi-deprecated for public use, as well as somewhat
4169 * misleadingly named. You probably just want to call isKnown(), which
4170 * calls this function internally.
4172 * (ISSUE: Most of these checks are cheap, but the file existence check
4173 * can potentially be quite expensive. Including it here fixes a lot of
4174 * existing code, but we might want to add an optional parameter to skip
4175 * it and any other expensive checks.)
4179 public function isAlwaysKnown() {
4183 * Allows overriding default behaviour for determining if a page exists.
4184 * If $isKnown is kept as null, regular checks happen. If it's
4185 * a boolean, this value is returned by the isKnown method.
4189 * @param Title $title
4190 * @param boolean|null $isKnown
4192 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4194 if ( !is_null( $isKnown ) ) {
4198 if ( $this->mInterwiki
!= '' ) {
4199 return true; // any interwiki link might be viewable, for all we know
4202 switch( $this->mNamespace
) {
4205 // file exists, possibly in a foreign repo
4206 return (bool)wfFindFile( $this );
4208 // valid special page
4209 return SpecialPageFactory
::exists( $this->getDBkey() );
4211 // selflink, possibly with fragment
4212 return $this->mDbkeyform
== '';
4214 // known system message
4215 return $this->hasSourceText() !== false;
4222 * Does this title refer to a page that can (or might) be meaningfully
4223 * viewed? In particular, this function may be used to determine if
4224 * links to the title should be rendered as "bluelinks" (as opposed to
4225 * "redlinks" to non-existent pages).
4226 * Adding something else to this function will cause inconsistency
4227 * since LinkHolderArray calls isAlwaysKnown() and does its own
4228 * page existence check.
4232 public function isKnown() {
4233 return $this->isAlwaysKnown() ||
$this->exists();
4237 * Does this page have source text?
4241 public function hasSourceText() {
4242 if ( $this->exists() ) {
4246 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4247 // If the page doesn't exist but is a known system message, default
4248 // message content will be displayed, same for language subpages-
4249 // Use always content language to avoid loading hundreds of languages
4250 // to get the link color.
4252 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4253 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4254 return $message->exists();
4261 * Get the default message text or false if the message doesn't exist
4263 * @return String or false
4265 public function getDefaultMessageText() {
4268 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4272 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4273 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4275 if ( $message->exists() ) {
4276 return $message->plain();
4283 * Updates page_touched for this page; called from LinksUpdate.php
4285 * @return Bool true if the update succeded
4287 public function invalidateCache() {
4288 if ( wfReadOnly() ) {
4291 $dbw = wfGetDB( DB_MASTER
);
4292 $success = $dbw->update(
4294 array( 'page_touched' => $dbw->timestamp() ),
4298 HTMLFileCache
::clearFileCache( $this );
4303 * Update page_touched timestamps and send squid purge messages for
4304 * pages linking to this title. May be sent to the job queue depending
4305 * on the number of links. Typically called on create and delete.
4307 public function touchLinks() {
4308 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4311 if ( $this->getNamespace() == NS_CATEGORY
) {
4312 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4318 * Get the last touched timestamp
4320 * @param $db DatabaseBase: optional db
4321 * @return String last-touched timestamp
4323 public function getTouched( $db = null ) {
4324 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4325 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4330 * Get the timestamp when this page was updated since the user last saw it.
4333 * @return String|Null
4335 public function getNotificationTimestamp( $user = null ) {
4336 global $wgUser, $wgShowUpdatedMarker;
4337 // Assume current user if none given
4341 // Check cache first
4342 $uid = $user->getId();
4343 // avoid isset here, as it'll return false for null entries
4344 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4345 return $this->mNotificationTimestamp
[$uid];
4347 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4348 return $this->mNotificationTimestamp
[$uid] = false;
4350 // Don't cache too much!
4351 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4352 $this->mNotificationTimestamp
= array();
4354 $dbr = wfGetDB( DB_SLAVE
);
4355 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4356 'wl_notificationtimestamp',
4357 array( 'wl_namespace' => $this->getNamespace(),
4358 'wl_title' => $this->getDBkey(),
4359 'wl_user' => $user->getId()
4363 return $this->mNotificationTimestamp
[$uid];
4367 * Generate strings used for xml 'id' names in monobook tabs
4369 * @param $prepend string defaults to 'nstab-'
4370 * @return String XML 'id' name
4372 public function getNamespaceKey( $prepend = 'nstab-' ) {
4374 // Gets the subject namespace if this title
4375 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4376 // Checks if cononical namespace name exists for namespace
4377 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4378 // Uses canonical namespace name
4379 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4381 // Uses text of namespace
4382 $namespaceKey = $this->getSubjectNsText();
4384 // Makes namespace key lowercase
4385 $namespaceKey = $wgContLang->lc( $namespaceKey );
4387 if ( $namespaceKey == '' ) {
4388 $namespaceKey = 'main';
4390 // Changes file to image for backwards compatibility
4391 if ( $namespaceKey == 'file' ) {
4392 $namespaceKey = 'image';
4394 return $prepend . $namespaceKey;
4398 * Get all extant redirects to this Title
4400 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4401 * @return Array of Title redirects to this title
4403 public function getRedirectsHere( $ns = null ) {
4406 $dbr = wfGetDB( DB_SLAVE
);
4408 'rd_namespace' => $this->getNamespace(),
4409 'rd_title' => $this->getDBkey(),
4412 if ( !is_null( $ns ) ) {
4413 $where['page_namespace'] = $ns;
4416 $res = $dbr->select(
4417 array( 'redirect', 'page' ),
4418 array( 'page_namespace', 'page_title' ),
4423 foreach ( $res as $row ) {
4424 $redirs[] = self
::newFromRow( $row );
4430 * Check if this Title is a valid redirect target
4434 public function isValidRedirectTarget() {
4435 global $wgInvalidRedirectTargets;
4437 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4438 if ( $this->isSpecial( 'Userlogout' ) ) {
4442 foreach ( $wgInvalidRedirectTargets as $target ) {
4443 if ( $this->isSpecial( $target ) ) {
4452 * Get a backlink cache object
4454 * @return BacklinkCache
4456 function getBacklinkCache() {
4457 if ( is_null( $this->mBacklinkCache
) ) {
4458 $this->mBacklinkCache
= new BacklinkCache( $this );
4460 return $this->mBacklinkCache
;
4464 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4468 public function canUseNoindex() {
4469 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4471 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4472 ?
$wgContentNamespaces
4473 : $wgExemptFromUserRobotsControl;
4475 return !in_array( $this->mNamespace
, $bannedNamespaces );
4480 * Returns the raw sort key to be used for categories, with the specified
4481 * prefix. This will be fed to Collation::getSortKey() to get a
4482 * binary sortkey that can be used for actual sorting.
4484 * @param $prefix string The prefix to be used, specified using
4485 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4489 public function getCategorySortkey( $prefix = '' ) {
4490 $unprefixed = $this->getText();
4492 // Anything that uses this hook should only depend
4493 // on the Title object passed in, and should probably
4494 // tell the users to run updateCollations.php --force
4495 // in order to re-sort existing category relations.
4496 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4497 if ( $prefix !== '' ) {
4498 # Separate with a line feed, so the unprefixed part is only used as
4499 # a tiebreaker when two pages have the exact same prefix.
4500 # In UCA, tab is the only character that can sort above LF
4501 # so we strip both of them from the original prefix.
4502 $prefix = strtr( $prefix, "\n\t", ' ' );
4503 return "$prefix\n$unprefixed";
4509 * Get the language in which the content of this page is written.
4510 * Defaults to $wgContLang, but in certain cases it can be e.g.
4511 * $wgLang (such as special pages, which are in the user language).
4514 * @return object Language
4516 public function getPageLanguage() {
4518 if ( $this->isSpecialPage() ) {
4519 // special pages are in the user language
4521 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4522 // css/js should always be LTR and is, in fact, English
4523 return wfGetLangObj( 'en' );
4524 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4525 // Parse mediawiki messages with correct target language
4526 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4527 return wfGetLangObj( $lang );
4530 // If nothing special, it should be in the wiki content language
4531 $pageLang = $wgContLang;
4532 // Hook at the end because we don't want to override the above stuff
4533 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4534 return wfGetLangObj( $pageLang );