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 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
92 /*protected*/ function __construct() { }
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
104 $t->mDbkeyform
= $key;
105 if ( $t->secureAndSplit() ) {
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
138 return Title
::$titleCache[$text];
141 # Convert things like é ā or 〗 into normalized (bug 14952) text
142 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
145 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace
= $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN
) {
151 if ( $cachedcount >= self
::CACHE_MAX
) {
152 # Avoid memory leaks on mass operations...
153 Title
::$titleCache = array();
157 Title
::$titleCache[$text] =& $t;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform
= str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
210 if ( $row !== false ) {
211 $title = Title
::newFromRow( $row );
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
228 $dbr = wfGetDB( DB_SLAVE
);
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
241 foreach ( $res as $row ) {
242 $titles[] = Title
::newFromRow( $row );
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
255 $t->loadFromRow( $row );
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|bool database row
265 public function loadFromRow( $row ) {
266 if ( $row ) { // page found
267 if ( isset( $row->page_id
) )
268 $this->mArticleID
= (int)$row->page_id
;
269 if ( isset( $row->page_len
) )
270 $this->mLength
= (int)$row->page_len
;
271 if ( isset( $row->page_is_redirect
) )
272 $this->mRedirect
= (bool)$row->page_is_redirect
;
273 if ( isset( $row->page_latest
) )
274 $this->mLatestID
= (int)$row->page_latest
; # FIXME: whene3ver page_latest is updated, also update page_content_model
275 if ( isset( $row->page_content_model
) )
276 $this->mContentModelName
= $row->page_content_model
;
278 $this->mContentModelName
= null; # initialized lazily in getContentModelName()
279 } else { // page not found
280 $this->mArticleID
= 0;
282 $this->mRedirect
= false;
283 $this->mLatestID
= 0;
284 $this->mContentModelName
= null; # initialized lazily in getContentModelName()
289 * Create a new Title from a namespace index and a DB key.
290 * It's assumed that $ns and $title are *valid*, for instance when
291 * they came directly from the database or a special page name.
292 * For convenience, spaces are converted to underscores so that
293 * eg user_text fields can be used directly.
295 * @param $ns Int the namespace of the article
296 * @param $title String the unprefixed database key form
297 * @param $fragment String the link fragment (after the "#")
298 * @param $interwiki String the interwiki prefix
299 * @return Title the new object
301 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
303 $t->mInterwiki
= $interwiki;
304 $t->mFragment
= $fragment;
305 $t->mNamespace
= $ns = intval( $ns );
306 $t->mDbkeyform
= str_replace( ' ', '_', $title );
307 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
308 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
309 $t->mTextform
= str_replace( '_', ' ', $title );
310 $t->mContentModelName
= null; # initialized lazily in getContentModelName()
315 * Create a new Title from a namespace index and a DB key.
316 * The parameters will be checked for validity, which is a bit slower
317 * than makeTitle() but safer for user-provided data.
319 * @param $ns Int the namespace of the article
320 * @param $title String database key form
321 * @param $fragment String the link fragment (after the "#")
322 * @param $interwiki String interwiki prefix
323 * @return Title the new object, or NULL on an error
325 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
326 if ( !MWNamespace
::exists( $ns ) ) {
331 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
332 if ( $t->secureAndSplit() ) {
340 * Create a new Title for the Main Page
342 * @return Title the new object
344 public static function newMainPage() {
345 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
346 // Don't give fatal errors if the message is broken
348 $title = Title
::newFromText( 'Main Page' );
354 * Extract a redirect destination from a string and return the
355 * Title, or null if the text doesn't contain a valid redirect
356 * This will only return the very next target, useful for
357 * the redirect table and other checks that don't need full recursion
359 * @param $text String: Text with possible redirect
360 * @return Title: The corresponding Title
362 public static function newFromRedirect( $text ) {
363 return self
::newFromRedirectInternal( $text );
367 * Extract a redirect destination from a string and return the
368 * Title, or null if the text doesn't contain a valid redirect
369 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
370 * in order to provide (hopefully) the Title of the final destination instead of another redirect
372 * @param $text String Text with possible redirect
375 public static function newFromRedirectRecurse( $text ) {
376 $titles = self
::newFromRedirectArray( $text );
377 return $titles ?
array_pop( $titles ) : null;
381 * Extract a redirect destination from a string and return an
382 * array of Titles, or null if the text doesn't contain a valid redirect
383 * The last element in the array is the final destination after all redirects
384 * have been resolved (up to $wgMaxRedirects times)
386 * @param $text String Text with possible redirect
387 * @return Array of Titles, with the destination last
389 public static function newFromRedirectArray( $text ) {
390 global $wgMaxRedirects;
391 $title = self
::newFromRedirectInternal( $text );
392 if ( is_null( $title ) ) {
395 // recursive check to follow double redirects
396 $recurse = $wgMaxRedirects;
397 $titles = array( $title );
398 while ( --$recurse > 0 ) {
399 if ( $title->isRedirect() ) {
400 $page = WikiPage
::factory( $title );
401 $newtitle = $page->getRedirectTarget();
405 // Redirects to some special pages are not permitted
406 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
407 // the new title passes the checks, so make that our current title so that further recursion can be checked
409 $titles[] = $newtitle;
418 * Really extract the redirect destination
419 * Do not call this function directly, use one of the newFromRedirect* functions above
421 * @param $text String Text with possible redirect
424 protected static function newFromRedirectInternal( $text ) {
425 global $wgMaxRedirects;
426 if ( $wgMaxRedirects < 1 ) {
427 //redirects are disabled, so quit early
430 $redir = MagicWord
::get( 'redirect' );
431 $text = trim( $text );
432 if ( $redir->matchStartAndRemove( $text ) ) {
433 // Extract the first link and see if it's usable
434 // Ensure that it really does come directly after #REDIRECT
435 // Some older redirects included a colon, so don't freak about that!
437 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
438 // Strip preceding colon used to "escape" categories, etc.
439 // and URL-decode links
440 if ( strpos( $m[1], '%' ) !== false ) {
441 // Match behavior of inline link parsing here;
442 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
444 $title = Title
::newFromText( $m[1] );
445 // If the title is a redirect to bad special pages or is invalid, return null
446 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
456 * Get the prefixed DB key associated with an ID
458 * @param $id Int the page_id of the article
459 * @return Title an object representing the article, or NULL if no such article was found
461 public static function nameOf( $id ) {
462 $dbr = wfGetDB( DB_SLAVE
);
464 $s = $dbr->selectRow(
466 array( 'page_namespace', 'page_title' ),
467 array( 'page_id' => $id ),
470 if ( $s === false ) {
474 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
479 * Get a regex character class describing the legal characters in a link
481 * @return String the list of characters, not delimited
483 public static function legalChars() {
484 global $wgLegalTitleChars;
485 return $wgLegalTitleChars;
489 * Returns a simple regex that will match on characters and sequences invalid in titles.
490 * Note that this doesn't pick up many things that could be wrong with titles, but that
491 * replacing this regex with something valid will make many titles valid.
493 * @return String regex string
495 static function getTitleInvalidRegex() {
496 static $rxTc = false;
498 # Matching titles will be held as illegal.
500 # Any character not allowed is forbidden...
501 '[^' . self
::legalChars() . ']' .
502 # URL percent encoding sequences interfere with the ability
503 # to round-trip titles -- you can't link to them consistently.
505 # XML/HTML character references produce similar issues.
506 '|&[A-Za-z0-9\x80-\xff]+;' .
508 '|&#x[0-9A-Fa-f]+;' .
516 * Get a string representation of a title suitable for
517 * including in a search index
519 * @param $ns Int a namespace index
520 * @param $title String text-form main part
521 * @return String a stripped-down title string ready for the search index
523 public static function indexTitle( $ns, $title ) {
526 $lc = SearchEngine
::legalSearchChars() . '&#;';
527 $t = $wgContLang->normalizeForSearch( $title );
528 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
529 $t = $wgContLang->lc( $t );
532 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
533 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
535 $t = preg_replace( "/\\s+/", ' ', $t );
537 if ( $ns == NS_FILE
) {
538 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
544 * Make a prefixed DB key from a DB key and a namespace index
546 * @param $ns Int numerical representation of the namespace
547 * @param $title String the DB key form the title
548 * @param $fragment String The link fragment (after the "#")
549 * @param $interwiki String The interwiki prefix
550 * @return String the prefixed form of the title
552 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
555 $namespace = $wgContLang->getNsText( $ns );
556 $name = $namespace == '' ?
$title : "$namespace:$title";
557 if ( strval( $interwiki ) != '' ) {
558 $name = "$interwiki:$name";
560 if ( strval( $fragment ) != '' ) {
561 $name .= '#' . $fragment;
567 * Escape a text fragment, say from a link, for a URL
569 * @param $fragment string containing a URL or link fragment (after the "#")
570 * @return String: escaped string
572 static function escapeFragmentForURL( $fragment ) {
573 # Note that we don't urlencode the fragment. urlencoded Unicode
574 # fragments appear not to work in IE (at least up to 7) or in at least
575 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
576 # to care if they aren't encoded.
577 return Sanitizer
::escapeId( $fragment, 'noninitial' );
581 * Callback for usort() to do title sorts by (namespace, title)
586 * @return Integer: result of string comparison, or namespace comparison
588 public static function compare( $a, $b ) {
589 if ( $a->getNamespace() == $b->getNamespace() ) {
590 return strcmp( $a->getText(), $b->getText() );
592 return $a->getNamespace() - $b->getNamespace();
597 * Determine whether the object refers to a page within
600 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
602 public function isLocal() {
603 if ( $this->mInterwiki
!= '' ) {
604 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
611 * Is this Title interwiki?
615 public function isExternal() {
616 return ( $this->mInterwiki
!= '' );
620 * Get the interwiki prefix (or null string)
622 * @return String Interwiki prefix
624 public function getInterwiki() {
625 return $this->mInterwiki
;
629 * Determine whether the object refers to a page within
630 * this project and is transcludable.
632 * @return Bool TRUE if this is transcludable
634 public function isTrans() {
635 if ( $this->mInterwiki
== '' ) {
639 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
643 * Returns the DB name of the distant wiki which owns the object.
645 * @return String the DB name
647 public function getTransWikiID() {
648 if ( $this->mInterwiki
== '' ) {
652 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
656 * Get the text form (spaces not underscores) of the main part
658 * @return String Main part of the title
660 public function getText() {
661 return $this->mTextform
;
665 * Get the URL-encoded form of the main part
667 * @return String Main part of the title, URL-encoded
669 public function getPartialURL() {
670 return $this->mUrlform
;
674 * Get the main part with underscores
676 * @return String: Main part of the title, with underscores
678 public function getDBkey() {
679 return $this->mDbkeyform
;
683 * Get the DB key with the initial letter case as specified by the user
685 * @return String DB key
687 function getUserCaseDBKey() {
688 return $this->mUserCaseDBKey
;
692 * Get the namespace index, i.e. one of the NS_xxxx constants.
694 * @return Integer: Namespace index
696 public function getNamespace() {
697 return $this->mNamespace
;
701 * Get the page's content model name
703 * @return Integer: Namespace index
705 public function getContentModelName() {
706 if ( empty( $this->mContentModelName
) ) {
707 $this->mContentModelName
= ContentHandler
::getDefaultModelFor( $this );
710 return $this->mContentModelName
;
714 * Conveniance method for checking a title's content model name
717 * @return true if $this->getContentModelName() == $name
719 public function hasContentModel( $name ) {
720 return $this->getContentModelName() == $name;
724 * Get the namespace text
726 * @return String: Namespace text
728 public function getNsText() {
731 if ( $this->mInterwiki
!= '' ) {
732 // This probably shouldn't even happen. ohh man, oh yuck.
733 // But for interwiki transclusion it sometimes does.
734 // Shit. Shit shit shit.
736 // Use the canonical namespaces if possible to try to
737 // resolve a foreign namespace.
738 if ( MWNamespace
::exists( $this->mNamespace
) ) {
739 return MWNamespace
::getCanonicalName( $this->mNamespace
);
743 // Strip off subpages
744 $pagename = $this->getText();
745 if ( strpos( $pagename, '/' ) !== false ) {
746 list( $username , ) = explode( '/', $pagename, 2 );
748 $username = $pagename;
751 if ( $wgContLang->needsGenderDistinction() &&
752 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
753 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
754 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
757 return $wgContLang->getNsText( $this->mNamespace
);
761 * Get the namespace text of the subject (rather than talk) page
763 * @return String Namespace text
765 public function getSubjectNsText() {
767 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
771 * Get the namespace text of the talk page
773 * @return String Namespace text
775 public function getTalkNsText() {
777 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
781 * Could this title have a corresponding talk page?
783 * @return Bool TRUE or FALSE
785 public function canTalk() {
786 return( MWNamespace
::canTalk( $this->mNamespace
) );
790 * Is this in a namespace that allows actual pages?
793 * @internal note -- uses hardcoded namespace index instead of constants
795 public function canExist() {
796 return $this->mNamespace
>= NS_MAIN
;
800 * Can this title be added to a user's watchlist?
802 * @return Bool TRUE or FALSE
804 public function isWatchable() {
805 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
809 * Returns true if this is a special page.
813 public function isSpecialPage() {
814 return $this->getNamespace() == NS_SPECIAL
;
818 * Returns true if this title resolves to the named special page
820 * @param $name String The special page name
823 public function isSpecial( $name ) {
824 if ( $this->isSpecialPage() ) {
825 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
826 if ( $name == $thisName ) {
834 * If the Title refers to a special page alias which is not the local default, resolve
835 * the alias, and localise the name as necessary. Otherwise, return $this
839 public function fixSpecialName() {
840 if ( $this->isSpecialPage() ) {
841 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
842 if ( $canonicalName ) {
843 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
844 if ( $localName != $this->mDbkeyform
) {
845 return Title
::makeTitle( NS_SPECIAL
, $localName );
853 * Returns true if the title is inside the specified namespace.
855 * Please make use of this instead of comparing to getNamespace()
856 * This function is much more resistant to changes we may make
857 * to namespaces than code that makes direct comparisons.
858 * @param $ns int The namespace
862 public function inNamespace( $ns ) {
863 return MWNamespace
::equals( $this->getNamespace(), $ns );
867 * Returns true if the title is inside one of the specified namespaces.
869 * @param ...$namespaces The namespaces to check for
873 public function inNamespaces( /* ... */ ) {
874 $namespaces = func_get_args();
875 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
876 $namespaces = $namespaces[0];
879 foreach ( $namespaces as $ns ) {
880 if ( $this->inNamespace( $ns ) ) {
889 * Returns true if the title has the same subject namespace as the
890 * namespace specified.
891 * For example this method will take NS_USER and return true if namespace
892 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
893 * as their subject namespace.
895 * This is MUCH simpler than individually testing for equivilance
896 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
900 public function hasSubjectNamespace( $ns ) {
901 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
905 * Is this Title in a namespace which contains content?
906 * In other words, is this a content page, for the purposes of calculating
911 public function isContentPage() {
912 return MWNamespace
::isContent( $this->getNamespace() );
916 * Would anybody with sufficient privileges be able to move this page?
917 * Some pages just aren't movable.
919 * @return Bool TRUE or FALSE
921 public function isMovable() {
922 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
923 // Interwiki title or immovable namespace. Hooks don't get to override here
928 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
933 * Is this the mainpage?
934 * @note Title::newFromText seams to be sufficiently optimized by the title
935 * cache that we don't need to over-optimize by doing direct comparisons and
936 * acidentally creating new bugs where $title->equals( Title::newFromText() )
937 * ends up reporting something differently than $title->isMainPage();
942 public function isMainPage() {
943 return $this->equals( Title
::newMainPage() );
951 public function isSubpage() {
952 return MWNamespace
::hasSubpages( $this->mNamespace
)
953 ?
strpos( $this->getText(), '/' ) !== false
958 * Is this a conversion table for the LanguageConverter?
962 public function isConversionTable() {
963 return $this->getNamespace() == NS_MEDIAWIKI
&&
964 strpos( $this->getText(), 'Conversiontable' ) !== false;
968 * Does that page contain wikitext, or it is JS, CSS or whatever?
972 public function isWikitextPage() {
973 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
977 * Could this page contain custom CSS or JavaScript for the global UI.
978 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
979 * or CONTENT_MODEL_JAVASCRIPT.
981 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
983 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
987 public function isCssOrJsPage() {
988 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
989 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
990 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
992 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
993 # hook funktions can force this method to return true even outside the mediawiki namespace.
995 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
997 return $isCssOrJsPage;
1001 * Is this a .css or .js subpage of a user page?
1004 public function isCssJsSubpage() {
1005 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1006 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1007 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1011 * Trim down a .css or .js subpage title to get the corresponding skin name
1013 * @return string containing skin name from .css or .js subpage title
1015 public function getSkinFromCssJsSubpage() {
1016 $subpage = explode( '/', $this->mTextform
);
1017 $subpage = $subpage[ count( $subpage ) - 1 ];
1018 $lastdot = strrpos( $subpage, '.' );
1019 if ( $lastdot === false )
1020 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1021 return substr( $subpage, 0, $lastdot );
1025 * Is this a .css subpage of a user page?
1029 public function isCssSubpage() {
1030 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1031 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1035 * Is this a .js subpage of a user page?
1039 public function isJsSubpage() {
1040 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1041 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1045 * Is this a talk page of some sort?
1049 public function isTalkPage() {
1050 return MWNamespace
::isTalk( $this->getNamespace() );
1054 * Get a Title object associated with the talk page of this article
1056 * @return Title the object for the talk page
1058 public function getTalkPage() {
1059 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1063 * Get a title object associated with the subject page of this
1066 * @return Title the object for the subject page
1068 public function getSubjectPage() {
1069 // Is this the same title?
1070 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1071 if ( $this->getNamespace() == $subjectNS ) {
1074 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1078 * Get the default namespace index, for when there is no namespace
1080 * @return Int Default namespace index
1082 public function getDefaultNamespace() {
1083 return $this->mDefaultNamespace
;
1087 * Get title for search index
1089 * @return String a stripped-down title string ready for the
1092 public function getIndexTitle() {
1093 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1097 * Get the Title fragment (i.e.\ the bit after the #) in text form
1099 * @return String Title fragment
1101 public function getFragment() {
1102 return $this->mFragment
;
1106 * Get the fragment in URL form, including the "#" character if there is one
1107 * @return String Fragment in URL form
1109 public function getFragmentForURL() {
1110 if ( $this->mFragment
== '' ) {
1113 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1118 * Set the fragment for this title. Removes the first character from the
1119 * specified fragment before setting, so it assumes you're passing it with
1122 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1123 * Still in active use privately.
1125 * @param $fragment String text
1127 public function setFragment( $fragment ) {
1128 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1132 * Prefix some arbitrary text with the namespace or interwiki prefix
1135 * @param $name String the text
1136 * @return String the prefixed text
1139 private function prefix( $name ) {
1141 if ( $this->mInterwiki
!= '' ) {
1142 $p = $this->mInterwiki
. ':';
1145 if ( 0 != $this->mNamespace
) {
1146 $p .= $this->getNsText() . ':';
1152 * Get the prefixed database key form
1154 * @return String the prefixed title, with underscores and
1155 * any interwiki and namespace prefixes
1157 public function getPrefixedDBkey() {
1158 $s = $this->prefix( $this->mDbkeyform
);
1159 $s = str_replace( ' ', '_', $s );
1164 * Get the prefixed title with spaces.
1165 * This is the form usually used for display
1167 * @return String the prefixed title, with spaces
1169 public function getPrefixedText() {
1170 // @todo FIXME: Bad usage of empty() ?
1171 if ( empty( $this->mPrefixedText
) ) {
1172 $s = $this->prefix( $this->mTextform
);
1173 $s = str_replace( '_', ' ', $s );
1174 $this->mPrefixedText
= $s;
1176 return $this->mPrefixedText
;
1180 * Return a string representation of this title
1182 * @return String representation of this title
1184 public function __toString() {
1185 return $this->getPrefixedText();
1189 * Get the prefixed title with spaces, plus any fragment
1190 * (part beginning with '#')
1192 * @return String the prefixed title, with spaces and the fragment, including '#'
1194 public function getFullText() {
1195 $text = $this->getPrefixedText();
1196 if ( $this->mFragment
!= '' ) {
1197 $text .= '#' . $this->mFragment
;
1203 * Get the base page name, i.e. the leftmost part before any slashes
1205 * @return String Base name
1207 public function getBaseText() {
1208 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1209 return $this->getText();
1212 $parts = explode( '/', $this->getText() );
1213 # Don't discard the real title if there's no subpage involved
1214 if ( count( $parts ) > 1 ) {
1215 unset( $parts[count( $parts ) - 1] );
1217 return implode( '/', $parts );
1221 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1223 * @return String Subpage name
1225 public function getSubpageText() {
1226 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1227 return( $this->mTextform
);
1229 $parts = explode( '/', $this->mTextform
);
1230 return( $parts[count( $parts ) - 1] );
1234 * Get the HTML-escaped displayable text form.
1235 * Used for the title field in <a> tags.
1237 * @return String the text, including any prefixes
1239 public function getEscapedText() {
1240 wfDeprecated( __METHOD__
, '1.19' );
1241 return htmlspecialchars( $this->getPrefixedText() );
1245 * Get a URL-encoded form of the subpage text
1247 * @return String URL-encoded subpage name
1249 public function getSubpageUrlForm() {
1250 $text = $this->getSubpageText();
1251 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1256 * Get a URL-encoded title (not an actual URL) including interwiki
1258 * @return String the URL-encoded form
1260 public function getPrefixedURL() {
1261 $s = $this->prefix( $this->mDbkeyform
);
1262 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1267 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1268 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1269 * second argument named variant. This was deprecated in favor
1270 * of passing an array of option with a "variant" key
1271 * Once $query2 is removed for good, this helper can be dropped
1272 * andthe wfArrayToCGI moved to getLocalURL();
1274 * @since 1.19 (r105919)
1277 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1278 if( $query2 !== false ) {
1279 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" );
1281 if ( is_array( $query ) ) {
1282 $query = wfArrayToCGI( $query );
1285 if ( is_string( $query2 ) ) {
1286 // $query2 is a string, we will consider this to be
1287 // a deprecated $variant argument and add it to the query
1288 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1290 $query2 = wfArrayToCGI( $query2 );
1292 // If we have $query content add a & to it first
1296 // Now append the queries together
1303 * Get a real URL referring to this title, with interwiki link and
1306 * See getLocalURL for the arguments.
1308 * @see self::getLocalURL
1309 * @return String the URL
1311 public function getFullURL( $query = '', $query2 = false ) {
1312 $query = self
::fixUrlQueryArgs( $query, $query2 );
1314 # Hand off all the decisions on urls to getLocalURL
1315 $url = $this->getLocalURL( $query );
1317 # Expand the url to make it a full url. Note that getLocalURL has the
1318 # potential to output full urls for a variety of reasons, so we use
1319 # wfExpandUrl instead of simply prepending $wgServer
1320 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1322 # Finally, add the fragment.
1323 $url .= $this->getFragmentForURL();
1325 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1330 * Get a URL with no fragment or server name. If this page is generated
1331 * with action=render, $wgServer is prepended.
1334 * @param $query string|array an optional query string,
1335 * not used for interwiki links. Can be specified as an associative array as well,
1336 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1337 * Some query patterns will trigger various shorturl path replacements.
1338 * @param $query2 Mixed: An optional secondary query array. This one MUST
1339 * be an array. If a string is passed it will be interpreted as a deprecated
1340 * variant argument and urlencoded into a variant= argument.
1341 * This second query argument will be added to the $query
1342 * The second parameter is deprecated since 1.19. Pass it as a key,value
1343 * pair in the first parameter array instead.
1345 * @return String the URL
1347 public function getLocalURL( $query = '', $query2 = false ) {
1348 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1350 $query = self
::fixUrlQueryArgs( $query, $query2 );
1352 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1354 $namespace = $this->getNsText();
1355 if ( $namespace != '' ) {
1356 # Can this actually happen? Interwikis shouldn't be parsed.
1357 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1360 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1361 $url = wfAppendQuery( $url, $query );
1363 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1364 if ( $query == '' ) {
1365 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1366 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1368 global $wgVariantArticlePath, $wgActionPaths;
1372 if ( !empty( $wgActionPaths ) &&
1373 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1375 $action = urldecode( $matches[2] );
1376 if ( isset( $wgActionPaths[$action] ) ) {
1377 $query = $matches[1];
1378 if ( isset( $matches[4] ) ) {
1379 $query .= $matches[4];
1381 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1382 if ( $query != '' ) {
1383 $url = wfAppendQuery( $url, $query );
1388 if ( $url === false &&
1389 $wgVariantArticlePath &&
1390 $this->getPageLanguage()->hasVariants() &&
1391 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1393 $variant = urldecode( $matches[1] );
1394 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1395 // Only do the variant replacement if the given variant is a valid
1396 // variant for the page's language.
1397 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1398 $url = str_replace( '$1', $dbkey, $url );
1402 if ( $url === false ) {
1403 if ( $query == '-' ) {
1406 $url = "{$wgScript}?title={$dbkey}&{$query}";
1410 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1412 // @todo FIXME: This causes breakage in various places when we
1413 // actually expected a local URL and end up with dupe prefixes.
1414 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1415 $url = $wgServer . $url;
1418 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1423 * Get a URL that's the simplest URL that will be valid to link, locally,
1424 * to the current Title. It includes the fragment, but does not include
1425 * the server unless action=render is used (or the link is external). If
1426 * there's a fragment but the prefixed text is empty, we just return a link
1429 * The result obviously should not be URL-escaped, but does need to be
1430 * HTML-escaped if it's being output in HTML.
1432 * See getLocalURL for the arguments.
1434 * @see self::getLocalURL
1435 * @return String the URL
1437 public function getLinkURL( $query = '', $query2 = false ) {
1438 wfProfileIn( __METHOD__
);
1439 if ( $this->isExternal() ) {
1440 $ret = $this->getFullURL( $query, $query2 );
1441 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1442 $ret = $this->getFragmentForURL();
1444 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1446 wfProfileOut( __METHOD__
);
1451 * Get an HTML-escaped version of the URL form, suitable for
1452 * using in a link, without a server name or fragment
1454 * See getLocalURL for the arguments.
1456 * @see self::getLocalURL
1457 * @return String the URL
1459 public function escapeLocalURL( $query = '', $query2 = false ) {
1460 wfDeprecated( __METHOD__
, '1.19' );
1461 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1465 * Get an HTML-escaped version of the URL form, suitable for
1466 * using in a link, including the server name and fragment
1468 * See getLocalURL for the arguments.
1470 * @see self::getLocalURL
1471 * @return String the URL
1473 public function escapeFullURL( $query = '', $query2 = false ) {
1474 wfDeprecated( __METHOD__
, '1.19' );
1475 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1479 * Get the URL form for an internal link.
1480 * - Used in various Squid-related code, in case we have a different
1481 * internal hostname for the server from the exposed one.
1483 * This uses $wgInternalServer to qualify the path, or $wgServer
1484 * if $wgInternalServer is not set. If the server variable used is
1485 * protocol-relative, the URL will be expanded to http://
1487 * See getLocalURL for the arguments.
1489 * @see self::getLocalURL
1490 * @return String the URL
1492 public function getInternalURL( $query = '', $query2 = false ) {
1493 global $wgInternalServer, $wgServer;
1494 $query = self
::fixUrlQueryArgs( $query, $query2 );
1495 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1496 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1497 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1502 * Get the URL for a canonical link, for use in things like IRC and
1503 * e-mail notifications. Uses $wgCanonicalServer and the
1504 * GetCanonicalURL hook.
1506 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1508 * See getLocalURL for the arguments.
1510 * @see self::getLocalURL
1511 * @return string The URL
1514 public function getCanonicalURL( $query = '', $query2 = false ) {
1515 $query = self
::fixUrlQueryArgs( $query, $query2 );
1516 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1517 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1522 * HTML-escaped version of getCanonicalURL()
1524 * See getLocalURL for the arguments.
1526 * @see self::getLocalURL
1530 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1531 wfDeprecated( __METHOD__
, '1.19' );
1532 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1536 * Get the edit URL for this Title
1538 * @return String the URL, or a null string if this is an
1541 public function getEditURL() {
1542 if ( $this->mInterwiki
!= '' ) {
1545 $s = $this->getLocalURL( 'action=edit' );
1551 * Is $wgUser watching this page?
1555 public function userIsWatching() {
1558 if ( is_null( $this->mWatched
) ) {
1559 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1560 $this->mWatched
= false;
1562 $this->mWatched
= $wgUser->isWatched( $this );
1565 return $this->mWatched
;
1569 * Can $wgUser read this page?
1571 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1573 * @todo fold these checks into userCan()
1575 public function userCanRead() {
1576 wfDeprecated( __METHOD__
, '1.19' );
1577 return $this->userCan( 'read' );
1581 * Can $user perform $action on this page?
1582 * This skips potentially expensive cascading permission checks
1583 * as well as avoids expensive error formatting
1585 * Suitable for use for nonessential UI controls in common cases, but
1586 * _not_ for functional access control.
1588 * May provide false positives, but should never provide a false negative.
1590 * @param $action String action that permission needs to be checked for
1591 * @param $user User to check (since 1.19); $wgUser will be used if not
1595 public function quickUserCan( $action, $user = null ) {
1596 return $this->userCan( $action, $user, false );
1600 * Can $user perform $action on this page?
1602 * @param $action String action that permission needs to be checked for
1603 * @param $user User to check (since 1.19); $wgUser will be used if not
1605 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1606 * unnecessary queries.
1609 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1610 if ( !$user instanceof User
) {
1614 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1618 * Can $user perform $action on this page?
1620 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1622 * @param $action String action that permission needs to be checked for
1623 * @param $user User to check
1624 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1625 * queries by skipping checks for cascading protections and user blocks.
1626 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1627 * whose corresponding errors may be ignored.
1628 * @return Array of arguments to wfMsg to explain permissions problems.
1630 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1631 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1633 // Remove the errors being ignored.
1634 foreach ( $errors as $index => $error ) {
1635 $error_key = is_array( $error ) ?
$error[0] : $error;
1637 if ( in_array( $error_key, $ignoreErrors ) ) {
1638 unset( $errors[$index] );
1646 * Permissions checks that fail most often, and which are easiest to test.
1648 * @param $action String the action to check
1649 * @param $user User user to check
1650 * @param $errors Array list of current errors
1651 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1652 * @param $short Boolean short circuit on first error
1654 * @return Array list of errors
1656 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1657 if ( $action == 'create' ) {
1658 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1659 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1660 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1662 } elseif ( $action == 'move' ) {
1663 if ( !$user->isAllowed( 'move-rootuserpages' )
1664 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1665 // Show user page-specific message only if the user can move other pages
1666 $errors[] = array( 'cant-move-user-page' );
1669 // Check if user is allowed to move files if it's a file
1670 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1671 $errors[] = array( 'movenotallowedfile' );
1674 if ( !$user->isAllowed( 'move' ) ) {
1675 // User can't move anything
1676 global $wgGroupPermissions;
1677 $userCanMove = false;
1678 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1679 $userCanMove = $wgGroupPermissions['user']['move'];
1681 $autoconfirmedCanMove = false;
1682 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1683 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1685 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1686 // custom message if logged-in users without any special rights can move
1687 $errors[] = array( 'movenologintext' );
1689 $errors[] = array( 'movenotallowed' );
1692 } elseif ( $action == 'move-target' ) {
1693 if ( !$user->isAllowed( 'move' ) ) {
1694 // User can't move anything
1695 $errors[] = array( 'movenotallowed' );
1696 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1697 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1698 // Show user page-specific message only if the user can move other pages
1699 $errors[] = array( 'cant-move-to-user-page' );
1701 } elseif ( !$user->isAllowed( $action ) ) {
1702 $errors[] = $this->missingPermissionError( $action, $short );
1709 * Add the resulting error code to the errors array
1711 * @param $errors Array list of current errors
1712 * @param $result Mixed result of errors
1714 * @return Array list of errors
1716 private function resultToError( $errors, $result ) {
1717 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1718 // A single array representing an error
1719 $errors[] = $result;
1720 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1721 // A nested array representing multiple errors
1722 $errors = array_merge( $errors, $result );
1723 } elseif ( $result !== '' && is_string( $result ) ) {
1724 // A string representing a message-id
1725 $errors[] = array( $result );
1726 } elseif ( $result === false ) {
1727 // a generic "We don't want them to do that"
1728 $errors[] = array( 'badaccess-group0' );
1734 * Check various permission hooks
1736 * @param $action String the action to check
1737 * @param $user User user to check
1738 * @param $errors Array list of current errors
1739 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1740 * @param $short Boolean short circuit on first error
1742 * @return Array list of errors
1744 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1745 // Use getUserPermissionsErrors instead
1747 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1748 return $result ?
array() : array( array( 'badaccess-group0' ) );
1750 // Check getUserPermissionsErrors hook
1751 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1752 $errors = $this->resultToError( $errors, $result );
1754 // Check getUserPermissionsErrorsExpensive hook
1755 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1756 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1757 $errors = $this->resultToError( $errors, $result );
1764 * Check permissions on special pages & namespaces
1766 * @param $action String the action to check
1767 * @param $user User user to check
1768 * @param $errors Array list of current errors
1769 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1770 * @param $short Boolean short circuit on first error
1772 * @return Array list of errors
1774 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1775 # Only 'createaccount' and 'execute' can be performed on
1776 # special pages, which don't actually exist in the DB.
1777 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1778 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1779 $errors[] = array( 'ns-specialprotected' );
1782 # Check $wgNamespaceProtection for restricted namespaces
1783 if ( $this->isNamespaceProtected( $user ) ) {
1784 $ns = $this->mNamespace
== NS_MAIN ?
1785 wfMsg( 'nstab-main' ) : $this->getNsText();
1786 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1787 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1794 * Check CSS/JS sub-page permissions
1796 * @param $action String the action to check
1797 * @param $user User user to check
1798 * @param $errors Array list of current errors
1799 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1800 * @param $short Boolean short circuit on first error
1802 * @return Array list of errors
1804 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1805 # Protect css/js subpages of user pages
1806 # XXX: this might be better using restrictions
1807 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1808 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1809 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1810 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1811 $errors[] = array( 'customcssprotected' );
1812 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1813 $errors[] = array( 'customjsprotected' );
1821 * Check against page_restrictions table requirements on this
1822 * page. The user must possess all required rights for this
1825 * @param $action String the action to check
1826 * @param $user User user to check
1827 * @param $errors Array list of current errors
1828 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1829 * @param $short Boolean short circuit on first error
1831 * @return Array list of errors
1833 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1834 foreach ( $this->getRestrictions( $action ) as $right ) {
1835 // Backwards compatibility, rewrite sysop -> protect
1836 if ( $right == 'sysop' ) {
1839 if ( $right != '' && !$user->isAllowed( $right ) ) {
1840 // Users with 'editprotected' permission can edit protected pages
1841 // without cascading option turned on.
1842 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1843 ||
$this->mCascadeRestriction
)
1845 $errors[] = array( 'protectedpagetext', $right );
1854 * Check restrictions on cascading pages.
1856 * @param $action String the action to check
1857 * @param $user User to check
1858 * @param $errors Array list of current errors
1859 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1860 * @param $short Boolean short circuit on first error
1862 * @return Array list of errors
1864 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1865 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1866 # We /could/ use the protection level on the source page, but it's
1867 # fairly ugly as we have to establish a precedence hierarchy for pages
1868 # included by multiple cascade-protected pages. So just restrict
1869 # it to people with 'protect' permission, as they could remove the
1870 # protection anyway.
1871 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1872 # Cascading protection depends on more than this page...
1873 # Several cascading protected pages may include this page...
1874 # Check each cascading level
1875 # This is only for protection restrictions, not for all actions
1876 if ( isset( $restrictions[$action] ) ) {
1877 foreach ( $restrictions[$action] as $right ) {
1878 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1879 if ( $right != '' && !$user->isAllowed( $right ) ) {
1881 foreach ( $cascadingSources as $page )
1882 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1883 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1893 * Check action permissions not already checked in checkQuickPermissions
1895 * @param $action String the action to check
1896 * @param $user User to check
1897 * @param $errors Array list of current errors
1898 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1899 * @param $short Boolean short circuit on first error
1901 * @return Array list of errors
1903 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1904 global $wgDeleteRevisionsLimit, $wgLang;
1906 if ( $action == 'protect' ) {
1907 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1908 // If they can't edit, they shouldn't protect.
1909 $errors[] = array( 'protect-cantedit' );
1911 } elseif ( $action == 'create' ) {
1912 $title_protection = $this->getTitleProtection();
1913 if( $title_protection ) {
1914 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1915 $title_protection['pt_create_perm'] = 'protect'; // B/C
1917 if( $title_protection['pt_create_perm'] == '' ||
1918 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1920 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1923 } elseif ( $action == 'move' ) {
1924 // Check for immobile pages
1925 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1926 // Specific message for this case
1927 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1928 } elseif ( !$this->isMovable() ) {
1929 // Less specific message for rarer cases
1930 $errors[] = array( 'immobile-source-page' );
1932 } elseif ( $action == 'move-target' ) {
1933 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1934 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1935 } elseif ( !$this->isMovable() ) {
1936 $errors[] = array( 'immobile-target-page' );
1938 } elseif ( $action == 'delete' ) {
1939 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1940 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1942 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1949 * Check that the user isn't blocked from editting.
1951 * @param $action String the action to check
1952 * @param $user User to check
1953 * @param $errors Array list of current errors
1954 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1955 * @param $short Boolean short circuit on first error
1957 * @return Array list of errors
1959 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1960 // Account creation blocks handled at userlogin.
1961 // Unblocking handled in SpecialUnblock
1962 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1966 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1968 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1969 $errors[] = array( 'confirmedittext' );
1972 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1973 // Don't block the user from editing their own talk page unless they've been
1974 // explicitly blocked from that too.
1975 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1976 $block = $user->getBlock();
1978 // This is from OutputPage::blockedPage
1979 // Copied at r23888 by werdna
1981 $id = $user->blockedBy();
1982 $reason = $user->blockedFor();
1983 if ( $reason == '' ) {
1984 $reason = wfMsg( 'blockednoreason' );
1986 $ip = $user->getRequest()->getIP();
1988 if ( is_numeric( $id ) ) {
1989 $name = User
::whoIs( $id );
1994 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1995 $blockid = $block->getId();
1996 $blockExpiry = $block->getExpiry();
1997 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1998 if ( $blockExpiry == 'infinity' ) {
1999 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2001 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2004 $intended = strval( $block->getTarget() );
2006 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2007 $blockid, $blockExpiry, $intended, $blockTimestamp );
2014 * Check that the user is allowed to read this page.
2016 * @param $action String the action to check
2017 * @param $user User to check
2018 * @param $errors Array list of current errors
2019 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2020 * @param $short Boolean short circuit on first error
2022 * @return Array list of errors
2024 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2025 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2026 static $useShortcut = null;
2028 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2029 if ( is_null( $useShortcut ) ) {
2030 $useShortcut = true;
2031 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2032 # Not a public wiki, so no shortcut
2033 $useShortcut = false;
2034 } elseif ( !empty( $wgRevokePermissions ) ) {
2036 * Iterate through each group with permissions being revoked (key not included since we don't care
2037 * what the group name is), then check if the read permission is being revoked. If it is, then
2038 * we don't use the shortcut below since the user might not be able to read, even though anon
2039 * reading is allowed.
2041 foreach ( $wgRevokePermissions as $perms ) {
2042 if ( !empty( $perms['read'] ) ) {
2043 # We might be removing the read right from the user, so no shortcut
2044 $useShortcut = false;
2051 $whitelisted = false;
2052 if ( $useShortcut ) {
2053 # Shortcut for public wikis, allows skipping quite a bit of code
2054 $whitelisted = true;
2055 } elseif ( $user->isAllowed( 'read' ) ) {
2056 # If the user is allowed to read pages, he is allowed to read all pages
2057 $whitelisted = true;
2058 } elseif ( $this->isSpecial( 'Userlogin' )
2059 ||
$this->isSpecial( 'ChangePassword' )
2060 ||
$this->isSpecial( 'PasswordReset' )
2062 # Always grant access to the login page.
2063 # Even anons need to be able to log in.
2064 $whitelisted = true;
2065 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2066 # Time to check the whitelist
2067 # Only do these checks is there's something to check against
2068 $name = $this->getPrefixedText();
2069 $dbName = $this->getPrefixedDBKey();
2071 // Check for explicit whitelisting with and without underscores
2072 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2073 $whitelisted = true;
2074 } elseif ( $this->getNamespace() == NS_MAIN
) {
2075 # Old settings might have the title prefixed with
2076 # a colon for main-namespace pages
2077 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2078 $whitelisted = true;
2080 } elseif ( $this->isSpecialPage() ) {
2081 # If it's a special page, ditch the subpage bit and check again
2082 $name = $this->getDBkey();
2083 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2084 if ( $name !== false ) {
2085 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2086 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2087 $whitelisted = true;
2093 if ( !$whitelisted ) {
2094 # If the title is not whitelisted, give extensions a chance to do so...
2095 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2096 if ( !$whitelisted ) {
2097 $errors[] = $this->missingPermissionError( $action, $short );
2105 * Get a description array when the user doesn't have the right to perform
2106 * $action (i.e. when User::isAllowed() returns false)
2108 * @param $action String the action to check
2109 * @param $short Boolean short circuit on first error
2110 * @return Array list of errors
2112 private function missingPermissionError( $action, $short ) {
2113 // We avoid expensive display logic for quickUserCan's and such
2115 return array( 'badaccess-group0' );
2118 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2119 User
::getGroupsWithPermission( $action ) );
2121 if ( count( $groups ) ) {
2125 $wgLang->commaList( $groups ),
2129 return array( 'badaccess-group0' );
2134 * Can $user perform $action on this page? This is an internal function,
2135 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2136 * checks on wfReadOnly() and blocks)
2138 * @param $action String action that permission needs to be checked for
2139 * @param $user User to check
2140 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2141 * @param $short Bool Set this to true to stop after the first permission error.
2142 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2144 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2145 wfProfileIn( __METHOD__
);
2147 # Read has special handling
2148 if ( $action == 'read' ) {
2150 'checkPermissionHooks',
2151 'checkReadPermissions',
2155 'checkQuickPermissions',
2156 'checkPermissionHooks',
2157 'checkSpecialsAndNSPermissions',
2158 'checkCSSandJSPermissions',
2159 'checkPageRestrictions',
2160 'checkCascadingSourcesRestrictions',
2161 'checkActionPermissions',
2167 while( count( $checks ) > 0 &&
2168 !( $short && count( $errors ) > 0 ) ) {
2169 $method = array_shift( $checks );
2170 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2173 wfProfileOut( __METHOD__
);
2178 * Protect css subpages of user pages: can $wgUser edit
2181 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2184 public function userCanEditCssSubpage() {
2186 wfDeprecated( __METHOD__
, '1.19' );
2187 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2188 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2192 * Protect js subpages of user pages: can $wgUser edit
2195 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2198 public function userCanEditJsSubpage() {
2200 wfDeprecated( __METHOD__
, '1.19' );
2201 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2202 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2206 * Get a filtered list of all restriction types supported by this wiki.
2207 * @param bool $exists True to get all restriction types that apply to
2208 * titles that do exist, False for all restriction types that apply to
2209 * titles that do not exist
2212 public static function getFilteredRestrictionTypes( $exists = true ) {
2213 global $wgRestrictionTypes;
2214 $types = $wgRestrictionTypes;
2216 # Remove the create restriction for existing titles
2217 $types = array_diff( $types, array( 'create' ) );
2219 # Only the create and upload restrictions apply to non-existing titles
2220 $types = array_intersect( $types, array( 'create', 'upload' ) );
2226 * Returns restriction types for the current Title
2228 * @return array applicable restriction types
2230 public function getRestrictionTypes() {
2231 if ( $this->isSpecialPage() ) {
2235 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2237 if ( $this->getNamespace() != NS_FILE
) {
2238 # Remove the upload restriction for non-file titles
2239 $types = array_diff( $types, array( 'upload' ) );
2242 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2244 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2245 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2251 * Is this title subject to title protection?
2252 * Title protection is the one applied against creation of such title.
2254 * @return Mixed An associative array representing any existent title
2255 * protection, or false if there's none.
2257 private function getTitleProtection() {
2258 // Can't protect pages in special namespaces
2259 if ( $this->getNamespace() < 0 ) {
2263 // Can't protect pages that exist.
2264 if ( $this->exists() ) {
2268 if ( !isset( $this->mTitleProtection
) ) {
2269 $dbr = wfGetDB( DB_SLAVE
);
2270 $res = $dbr->select( 'protected_titles', '*',
2271 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2274 // fetchRow returns false if there are no rows.
2275 $this->mTitleProtection
= $dbr->fetchRow( $res );
2277 return $this->mTitleProtection
;
2281 * Update the title protection status
2283 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2284 * @param $create_perm String Permission required for creation
2285 * @param $reason String Reason for protection
2286 * @param $expiry String Expiry timestamp
2287 * @return boolean true
2289 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2290 wfDeprecated( __METHOD__
, '1.19' );
2294 $limit = array( 'create' => $create_perm );
2295 $expiry = array( 'create' => $expiry );
2297 $page = WikiPage
::factory( $this );
2298 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2300 return $status->isOK();
2304 * Remove any title protection due to page existing
2306 public function deleteTitleProtection() {
2307 $dbw = wfGetDB( DB_MASTER
);
2311 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2314 $this->mTitleProtection
= false;
2318 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2320 * @param $action String Action to check (default: edit)
2323 public function isSemiProtected( $action = 'edit' ) {
2324 if ( $this->exists() ) {
2325 $restrictions = $this->getRestrictions( $action );
2326 if ( count( $restrictions ) > 0 ) {
2327 foreach ( $restrictions as $restriction ) {
2328 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2338 # If it doesn't exist, it can't be protected
2344 * Does the title correspond to a protected article?
2346 * @param $action String the action the page is protected from,
2347 * by default checks all actions.
2350 public function isProtected( $action = '' ) {
2351 global $wgRestrictionLevels;
2353 $restrictionTypes = $this->getRestrictionTypes();
2355 # Special pages have inherent protection
2356 if( $this->isSpecialPage() ) {
2360 # Check regular protection levels
2361 foreach ( $restrictionTypes as $type ) {
2362 if ( $action == $type ||
$action == '' ) {
2363 $r = $this->getRestrictions( $type );
2364 foreach ( $wgRestrictionLevels as $level ) {
2365 if ( in_array( $level, $r ) && $level != '' ) {
2376 * Determines if $user is unable to edit this page because it has been protected
2377 * by $wgNamespaceProtection.
2379 * @param $user User object to check permissions
2382 public function isNamespaceProtected( User
$user ) {
2383 global $wgNamespaceProtection;
2385 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2386 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2387 if ( $right != '' && !$user->isAllowed( $right ) ) {
2396 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2398 * @return Bool If the page is subject to cascading restrictions.
2400 public function isCascadeProtected() {
2401 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2402 return ( $sources > 0 );
2406 * Cascading protection: Get the source of any cascading restrictions on this page.
2408 * @param $getPages Bool Whether or not to retrieve the actual pages
2409 * that the restrictions have come from.
2410 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2411 * have come, false for none, or true if such restrictions exist, but $getPages
2412 * was not set. The restriction array is an array of each type, each of which
2413 * contains a array of unique groups.
2415 public function getCascadeProtectionSources( $getPages = true ) {
2417 $pagerestrictions = array();
2419 if ( isset( $this->mCascadeSources
) && $getPages ) {
2420 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2421 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2422 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2425 wfProfileIn( __METHOD__
);
2427 $dbr = wfGetDB( DB_SLAVE
);
2429 if ( $this->getNamespace() == NS_FILE
) {
2430 $tables = array( 'imagelinks', 'page_restrictions' );
2431 $where_clauses = array(
2432 'il_to' => $this->getDBkey(),
2437 $tables = array( 'templatelinks', 'page_restrictions' );
2438 $where_clauses = array(
2439 'tl_namespace' => $this->getNamespace(),
2440 'tl_title' => $this->getDBkey(),
2447 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2448 'pr_expiry', 'pr_type', 'pr_level' );
2449 $where_clauses[] = 'page_id=pr_page';
2452 $cols = array( 'pr_expiry' );
2455 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2457 $sources = $getPages ?
array() : false;
2458 $now = wfTimestampNow();
2459 $purgeExpired = false;
2461 foreach ( $res as $row ) {
2462 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2463 if ( $expiry > $now ) {
2465 $page_id = $row->pr_page
;
2466 $page_ns = $row->page_namespace
;
2467 $page_title = $row->page_title
;
2468 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2469 # Add groups needed for each restriction type if its not already there
2470 # Make sure this restriction type still exists
2472 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2473 $pagerestrictions[$row->pr_type
] = array();
2476 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2477 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2478 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2484 // Trigger lazy purge of expired restrictions from the db
2485 $purgeExpired = true;
2488 if ( $purgeExpired ) {
2489 Title
::purgeExpiredRestrictions();
2493 $this->mCascadeSources
= $sources;
2494 $this->mCascadingRestrictions
= $pagerestrictions;
2496 $this->mHasCascadingRestrictions
= $sources;
2499 wfProfileOut( __METHOD__
);
2500 return array( $sources, $pagerestrictions );
2504 * Accessor/initialisation for mRestrictions
2506 * @param $action String action that permission needs to be checked for
2507 * @return Array of Strings the array of groups allowed to edit this article
2509 public function getRestrictions( $action ) {
2510 if ( !$this->mRestrictionsLoaded
) {
2511 $this->loadRestrictions();
2513 return isset( $this->mRestrictions
[$action] )
2514 ?
$this->mRestrictions
[$action]
2519 * Get the expiry time for the restriction against a given action
2521 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2522 * or not protected at all, or false if the action is not recognised.
2524 public function getRestrictionExpiry( $action ) {
2525 if ( !$this->mRestrictionsLoaded
) {
2526 $this->loadRestrictions();
2528 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2532 * Returns cascading restrictions for the current article
2536 function areRestrictionsCascading() {
2537 if ( !$this->mRestrictionsLoaded
) {
2538 $this->loadRestrictions();
2541 return $this->mCascadeRestriction
;
2545 * Loads a string into mRestrictions array
2547 * @param $res Resource restrictions as an SQL result.
2548 * @param $oldFashionedRestrictions String comma-separated list of page
2549 * restrictions from page table (pre 1.10)
2551 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2554 foreach ( $res as $row ) {
2558 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2562 * Compiles list of active page restrictions from both page table (pre 1.10)
2563 * and page_restrictions table for this existing page.
2564 * Public for usage by LiquidThreads.
2566 * @param $rows array of db result objects
2567 * @param $oldFashionedRestrictions string comma-separated list of page
2568 * restrictions from page table (pre 1.10)
2570 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2572 $dbr = wfGetDB( DB_SLAVE
);
2574 $restrictionTypes = $this->getRestrictionTypes();
2576 foreach ( $restrictionTypes as $type ) {
2577 $this->mRestrictions
[$type] = array();
2578 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2581 $this->mCascadeRestriction
= false;
2583 # Backwards-compatibility: also load the restrictions from the page record (old format).
2585 if ( $oldFashionedRestrictions === null ) {
2586 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2587 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2590 if ( $oldFashionedRestrictions != '' ) {
2592 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2593 $temp = explode( '=', trim( $restrict ) );
2594 if ( count( $temp ) == 1 ) {
2595 // old old format should be treated as edit/move restriction
2596 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2597 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2599 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2603 $this->mOldRestrictions
= true;
2607 if ( count( $rows ) ) {
2608 # Current system - load second to make them override.
2609 $now = wfTimestampNow();
2610 $purgeExpired = false;
2612 # Cycle through all the restrictions.
2613 foreach ( $rows as $row ) {
2615 // Don't take care of restrictions types that aren't allowed
2616 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2619 // This code should be refactored, now that it's being used more generally,
2620 // But I don't really see any harm in leaving it in Block for now -werdna
2621 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2623 // Only apply the restrictions if they haven't expired!
2624 if ( !$expiry ||
$expiry > $now ) {
2625 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2626 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2628 $this->mCascadeRestriction |
= $row->pr_cascade
;
2630 // Trigger a lazy purge of expired restrictions
2631 $purgeExpired = true;
2635 if ( $purgeExpired ) {
2636 Title
::purgeExpiredRestrictions();
2640 $this->mRestrictionsLoaded
= true;
2644 * Load restrictions from the page_restrictions table
2646 * @param $oldFashionedRestrictions String comma-separated list of page
2647 * restrictions from page table (pre 1.10)
2649 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2651 if ( !$this->mRestrictionsLoaded
) {
2652 if ( $this->exists() ) {
2653 $dbr = wfGetDB( DB_SLAVE
);
2655 $res = $dbr->select(
2656 'page_restrictions',
2658 array( 'pr_page' => $this->getArticleID() ),
2662 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2664 $title_protection = $this->getTitleProtection();
2666 if ( $title_protection ) {
2667 $now = wfTimestampNow();
2668 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2670 if ( !$expiry ||
$expiry > $now ) {
2671 // Apply the restrictions
2672 $this->mRestrictionsExpiry
['create'] = $expiry;
2673 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2674 } else { // Get rid of the old restrictions
2675 Title
::purgeExpiredRestrictions();
2676 $this->mTitleProtection
= false;
2679 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2681 $this->mRestrictionsLoaded
= true;
2687 * Flush the protection cache in this object and force reload from the database.
2688 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2690 public function flushRestrictions() {
2691 $this->mRestrictionsLoaded
= false;
2692 $this->mTitleProtection
= null;
2696 * Purge expired restrictions from the page_restrictions table
2698 static function purgeExpiredRestrictions() {
2699 $dbw = wfGetDB( DB_MASTER
);
2701 'page_restrictions',
2702 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2708 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2714 * Does this have subpages? (Warning, usually requires an extra DB query.)
2718 public function hasSubpages() {
2719 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2724 # We dynamically add a member variable for the purpose of this method
2725 # alone to cache the result. There's no point in having it hanging
2726 # around uninitialized in every Title object; therefore we only add it
2727 # if needed and don't declare it statically.
2728 if ( isset( $this->mHasSubpages
) ) {
2729 return $this->mHasSubpages
;
2732 $subpages = $this->getSubpages( 1 );
2733 if ( $subpages instanceof TitleArray
) {
2734 return $this->mHasSubpages
= (bool)$subpages->count();
2736 return $this->mHasSubpages
= false;
2740 * Get all subpages of this page.
2742 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2743 * @return mixed TitleArray, or empty array if this page's namespace
2744 * doesn't allow subpages
2746 public function getSubpages( $limit = -1 ) {
2747 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2751 $dbr = wfGetDB( DB_SLAVE
);
2752 $conds['page_namespace'] = $this->getNamespace();
2753 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2755 if ( $limit > -1 ) {
2756 $options['LIMIT'] = $limit;
2758 return $this->mSubpages
= TitleArray
::newFromResult(
2759 $dbr->select( 'page',
2760 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2769 * Is there a version of this page in the deletion archive?
2771 * @return Int the number of archived revisions
2773 public function isDeleted() {
2774 if ( $this->getNamespace() < 0 ) {
2777 $dbr = wfGetDB( DB_SLAVE
);
2779 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2780 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2783 if ( $this->getNamespace() == NS_FILE
) {
2784 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2785 array( 'fa_name' => $this->getDBkey() ),
2794 * Is there a version of this page in the deletion archive?
2798 public function isDeletedQuick() {
2799 if ( $this->getNamespace() < 0 ) {
2802 $dbr = wfGetDB( DB_SLAVE
);
2803 $deleted = (bool)$dbr->selectField( 'archive', '1',
2804 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2807 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2808 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2809 array( 'fa_name' => $this->getDBkey() ),
2817 * Get the article ID for this Title from the link cache,
2818 * adding it if necessary
2820 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2822 * @return Int the ID
2824 public function getArticleID( $flags = 0 ) {
2825 if ( $this->getNamespace() < 0 ) {
2826 return $this->mArticleID
= 0;
2828 $linkCache = LinkCache
::singleton();
2829 if ( $flags & self
::GAID_FOR_UPDATE
) {
2830 $oldUpdate = $linkCache->forUpdate( true );
2831 $linkCache->clearLink( $this );
2832 $this->mArticleID
= $linkCache->addLinkObj( $this );
2833 $linkCache->forUpdate( $oldUpdate );
2835 if ( -1 == $this->mArticleID
) {
2836 $this->mArticleID
= $linkCache->addLinkObj( $this );
2839 return $this->mArticleID
;
2843 * Is this an article that is a redirect page?
2844 * Uses link cache, adding it if necessary
2846 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2849 public function isRedirect( $flags = 0 ) {
2850 if ( !is_null( $this->mRedirect
) ) {
2851 return $this->mRedirect
;
2853 # Calling getArticleID() loads the field from cache as needed
2854 if ( !$this->getArticleID( $flags ) ) {
2855 return $this->mRedirect
= false;
2857 $linkCache = LinkCache
::singleton();
2858 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2860 return $this->mRedirect
;
2864 * What is the length of this page?
2865 * Uses link cache, adding it if necessary
2867 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2870 public function getLength( $flags = 0 ) {
2871 if ( $this->mLength
!= -1 ) {
2872 return $this->mLength
;
2874 # Calling getArticleID() loads the field from cache as needed
2875 if ( !$this->getArticleID( $flags ) ) {
2876 return $this->mLength
= 0;
2878 $linkCache = LinkCache
::singleton();
2879 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2881 return $this->mLength
;
2885 * What is the page_latest field for this page?
2887 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2888 * @return Int or 0 if the page doesn't exist
2890 public function getLatestRevID( $flags = 0 ) {
2891 if ( $this->mLatestID
!== false ) {
2892 return intval( $this->mLatestID
);
2894 # Calling getArticleID() loads the field from cache as needed
2895 if ( !$this->getArticleID( $flags ) ) {
2896 return $this->mLatestID
= 0;
2898 $linkCache = LinkCache
::singleton();
2899 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2901 return $this->mLatestID
;
2905 * This clears some fields in this object, and clears any associated
2906 * keys in the "bad links" section of the link cache.
2908 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2909 * loading of the new page_id. It's also called from
2910 * WikiPage::doDeleteArticle()
2912 * @param $newid Int the new Article ID
2914 public function resetArticleID( $newid ) {
2915 $linkCache = LinkCache
::singleton();
2916 $linkCache->clearLink( $this );
2918 if ( $newid === false ) {
2919 $this->mArticleID
= -1;
2921 $this->mArticleID
= intval( $newid );
2923 $this->mRestrictionsLoaded
= false;
2924 $this->mRestrictions
= array();
2925 $this->mRedirect
= null;
2926 $this->mLength
= -1;
2927 $this->mLatestID
= false;
2928 $this->mEstimateRevisions
= null;
2932 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2934 * @param $text String containing title to capitalize
2935 * @param $ns int namespace index, defaults to NS_MAIN
2936 * @return String containing capitalized title
2938 public static function capitalize( $text, $ns = NS_MAIN
) {
2941 if ( MWNamespace
::isCapitalized( $ns ) ) {
2942 return $wgContLang->ucfirst( $text );
2949 * Secure and split - main initialisation function for this object
2951 * Assumes that mDbkeyform has been set, and is urldecoded
2952 * and uses underscores, but not otherwise munged. This function
2953 * removes illegal characters, splits off the interwiki and
2954 * namespace prefixes, sets the other forms, and canonicalizes
2957 * @return Bool true on success
2959 private function secureAndSplit() {
2960 global $wgContLang, $wgLocalInterwiki;
2963 $this->mInterwiki
= $this->mFragment
= '';
2964 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2966 $dbkey = $this->mDbkeyform
;
2968 # Strip Unicode bidi override characters.
2969 # Sometimes they slip into cut-n-pasted page titles, where the
2970 # override chars get included in list displays.
2971 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2973 # Clean up whitespace
2974 # Note: use of the /u option on preg_replace here will cause
2975 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2976 # conveniently disabling them.
2977 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2978 $dbkey = trim( $dbkey, '_' );
2980 if ( $dbkey == '' ) {
2984 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2985 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2989 $this->mDbkeyform
= $dbkey;
2991 # Initial colon indicates main namespace rather than specified default
2992 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2993 if ( ':' == $dbkey[0] ) {
2994 $this->mNamespace
= NS_MAIN
;
2995 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2996 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2999 # Namespace or interwiki prefix
3001 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3004 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3006 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3007 # Ordinary namespace
3009 $this->mNamespace
= $ns;
3010 # For Talk:X pages, check if X has a "namespace" prefix
3011 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3012 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3013 # Disallow Talk:File:x type titles...
3015 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3016 # Disallow Talk:Interwiki:x type titles...
3020 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3021 if ( !$firstPass ) {
3022 # Can't make a local interwiki link to an interwiki link.
3023 # That's just crazy!
3029 $this->mInterwiki
= $wgContLang->lc( $p );
3031 # Redundant interwiki prefix to the local wiki
3032 if ( $wgLocalInterwiki !== false
3033 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3035 if ( $dbkey == '' ) {
3036 # Can't have an empty self-link
3039 $this->mInterwiki
= '';
3041 # Do another namespace split...
3045 # If there's an initial colon after the interwiki, that also
3046 # resets the default namespace
3047 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3048 $this->mNamespace
= NS_MAIN
;
3049 $dbkey = substr( $dbkey, 1 );
3052 # If there's no recognized interwiki or namespace,
3053 # then let the colon expression be part of the title.
3058 # We already know that some pages won't be in the database!
3059 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3060 $this->mArticleID
= 0;
3062 $fragment = strstr( $dbkey, '#' );
3063 if ( false !== $fragment ) {
3064 $this->setFragment( $fragment );
3065 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3066 # remove whitespace again: prevents "Foo_bar_#"
3067 # becoming "Foo_bar_"
3068 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3071 # Reject illegal characters.
3072 $rxTc = self
::getTitleInvalidRegex();
3073 if ( preg_match( $rxTc, $dbkey ) ) {
3077 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3078 # reachable due to the way web browsers deal with 'relative' URLs.
3079 # Also, they conflict with subpage syntax. Forbid them explicitly.
3080 if ( strpos( $dbkey, '.' ) !== false &&
3081 ( $dbkey === '.' ||
$dbkey === '..' ||
3082 strpos( $dbkey, './' ) === 0 ||
3083 strpos( $dbkey, '../' ) === 0 ||
3084 strpos( $dbkey, '/./' ) !== false ||
3085 strpos( $dbkey, '/../' ) !== false ||
3086 substr( $dbkey, -2 ) == '/.' ||
3087 substr( $dbkey, -3 ) == '/..' ) )
3092 # Magic tilde sequences? Nu-uh!
3093 if ( strpos( $dbkey, '~~~' ) !== false ) {
3097 # Limit the size of titles to 255 bytes. This is typically the size of the
3098 # underlying database field. We make an exception for special pages, which
3099 # don't need to be stored in the database, and may edge over 255 bytes due
3100 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3101 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3102 strlen( $dbkey ) > 512 )
3107 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3108 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3109 # other site might be case-sensitive.
3110 $this->mUserCaseDBKey
= $dbkey;
3111 if ( $this->mInterwiki
== '' ) {
3112 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3115 # Can't make a link to a namespace alone... "empty" local links can only be
3116 # self-links with a fragment identifier.
3117 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3121 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3122 // IP names are not allowed for accounts, and can only be referring to
3123 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3124 // there are numerous ways to present the same IP. Having sp:contribs scan
3125 // them all is silly and having some show the edits and others not is
3126 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3127 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3128 ? IP
::sanitizeIP( $dbkey )
3131 // Any remaining initial :s are illegal.
3132 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3137 $this->mDbkeyform
= $dbkey;
3138 $this->mUrlform
= wfUrlencode( $dbkey );
3140 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3146 * Get an array of Title objects linking to this Title
3147 * Also stores the IDs in the link cache.
3149 * WARNING: do not use this function on arbitrary user-supplied titles!
3150 * On heavily-used templates it will max out the memory.
3152 * @param $options Array: may be FOR UPDATE
3153 * @param $table String: table name
3154 * @param $prefix String: fields prefix
3155 * @return Array of Title objects linking here
3157 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3158 if ( count( $options ) > 0 ) {
3159 $db = wfGetDB( DB_MASTER
);
3161 $db = wfGetDB( DB_SLAVE
);
3165 array( 'page', $table ),
3166 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3168 "{$prefix}_from=page_id",
3169 "{$prefix}_namespace" => $this->getNamespace(),
3170 "{$prefix}_title" => $this->getDBkey() ),
3176 if ( $res->numRows() ) {
3177 $linkCache = LinkCache
::singleton();
3178 foreach ( $res as $row ) {
3179 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3181 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3182 $retVal[] = $titleObj;
3190 * Get an array of Title objects using this Title as a template
3191 * Also stores the IDs in the link cache.
3193 * WARNING: do not use this function on arbitrary user-supplied titles!
3194 * On heavily-used templates it will max out the memory.
3196 * @param $options Array: may be FOR UPDATE
3197 * @return Array of Title the Title objects linking here
3199 public function getTemplateLinksTo( $options = array() ) {
3200 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3204 * Get an array of Title objects linked from this Title
3205 * Also stores the IDs in the link cache.
3207 * WARNING: do not use this function on arbitrary user-supplied titles!
3208 * On heavily-used templates it will max out the memory.
3210 * @param $options Array: may be FOR UPDATE
3211 * @param $table String: table name
3212 * @param $prefix String: fields prefix
3213 * @return Array of Title objects linking here
3215 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3216 $id = $this->getArticleID();
3218 # If the page doesn't exist; there can't be any link from this page
3223 if ( count( $options ) > 0 ) {
3224 $db = wfGetDB( DB_MASTER
);
3226 $db = wfGetDB( DB_SLAVE
);
3229 $namespaceFiled = "{$prefix}_namespace";
3230 $titleField = "{$prefix}_title";
3233 array( $table, 'page' ),
3234 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3235 array( "{$prefix}_from" => $id ),
3238 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3242 if ( $res->numRows() ) {
3243 $linkCache = LinkCache
::singleton();
3244 foreach ( $res as $row ) {
3245 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3247 if ( $row->page_id
) {
3248 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3250 $linkCache->addBadLinkObj( $titleObj );
3252 $retVal[] = $titleObj;
3260 * Get an array of Title objects used on this Title as a template
3261 * Also stores the IDs in the link cache.
3263 * WARNING: do not use this function on arbitrary user-supplied titles!
3264 * On heavily-used templates it will max out the memory.
3266 * @param $options Array: may be FOR UPDATE
3267 * @return Array of Title the Title objects used here
3269 public function getTemplateLinksFrom( $options = array() ) {
3270 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3274 * Get an array of Title objects referring to non-existent articles linked from this page
3276 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3277 * @return Array of Title the Title objects
3279 public function getBrokenLinksFrom() {
3280 if ( $this->getArticleID() == 0 ) {
3281 # All links from article ID 0 are false positives
3285 $dbr = wfGetDB( DB_SLAVE
);
3286 $res = $dbr->select(
3287 array( 'page', 'pagelinks' ),
3288 array( 'pl_namespace', 'pl_title' ),
3290 'pl_from' => $this->getArticleID(),
3291 'page_namespace IS NULL'
3293 __METHOD__
, array(),
3297 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3303 foreach ( $res as $row ) {
3304 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3311 * Get a list of URLs to purge from the Squid cache when this
3314 * @return Array of String the URLs
3316 public function getSquidURLs() {
3320 $this->getInternalURL(),
3321 $this->getInternalURL( 'action=history' )
3324 // purge variant urls as well
3325 if ( $wgContLang->hasVariants() ) {
3326 $variants = $wgContLang->getVariants();
3327 foreach ( $variants as $vCode ) {
3328 $urls[] = $this->getInternalURL( '', $vCode );
3336 * Purge all applicable Squid URLs
3338 public function purgeSquid() {
3340 if ( $wgUseSquid ) {
3341 $urls = $this->getSquidURLs();
3342 $u = new SquidUpdate( $urls );
3348 * Move this page without authentication
3350 * @param $nt Title the new page Title
3351 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3353 public function moveNoAuth( &$nt ) {
3354 return $this->moveTo( $nt, false );
3358 * Check whether a given move operation would be valid.
3359 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3361 * @param $nt Title the new title
3362 * @param $auth Bool indicates whether $wgUser's permissions
3364 * @param $reason String is the log summary of the move, used for spam checking
3365 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3367 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3372 // Normally we'd add this to $errors, but we'll get
3373 // lots of syntax errors if $nt is not an object
3374 return array( array( 'badtitletext' ) );
3376 if ( $this->equals( $nt ) ) {
3377 $errors[] = array( 'selfmove' );
3379 if ( !$this->isMovable() ) {
3380 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3382 if ( $nt->getInterwiki() != '' ) {
3383 $errors[] = array( 'immobile-target-namespace-iw' );
3385 if ( !$nt->isMovable() ) {
3386 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3389 $oldid = $this->getArticleID();
3390 $newid = $nt->getArticleID();
3392 if ( strlen( $nt->getDBkey() ) < 1 ) {
3393 $errors[] = array( 'articleexists' );
3395 if ( ( $this->getDBkey() == '' ) ||
3397 ( $nt->getDBkey() == '' ) ) {
3398 $errors[] = array( 'badarticleerror' );
3401 // Image-specific checks
3402 if ( $this->getNamespace() == NS_FILE
) {
3403 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3406 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3407 $errors[] = array( 'nonfile-cannot-move-to-file' );
3411 $errors = wfMergeErrorArrays( $errors,
3412 $this->getUserPermissionsErrors( 'move', $wgUser ),
3413 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3414 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3415 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3418 $match = EditPage
::matchSummarySpamRegex( $reason );
3419 if ( $match !== false ) {
3420 // This is kind of lame, won't display nice
3421 $errors[] = array( 'spamprotectiontext' );
3425 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3426 $errors[] = array( 'hookaborted', $err );
3429 # The move is allowed only if (1) the target doesn't exist, or
3430 # (2) the target is a redirect to the source, and has no history
3431 # (so we can undo bad moves right after they're done).
3433 if ( 0 != $newid ) { # Target exists; check for validity
3434 if ( !$this->isValidMoveTarget( $nt ) ) {
3435 $errors[] = array( 'articleexists' );
3438 $tp = $nt->getTitleProtection();
3439 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3440 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3441 $errors[] = array( 'cantmove-titleprotected' );
3444 if ( empty( $errors ) ) {
3451 * Check if the requested move target is a valid file move target
3452 * @param Title $nt Target title
3453 * @return array List of errors
3455 protected function validateFileMoveOperation( $nt ) {
3460 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3462 $file = wfLocalFile( $this );
3463 if ( $file->exists() ) {
3464 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3465 $errors[] = array( 'imageinvalidfilename' );
3467 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3468 $errors[] = array( 'imagetypemismatch' );
3472 if ( $nt->getNamespace() != NS_FILE
) {
3473 $errors[] = array( 'imagenocrossnamespace' );
3474 // From here we want to do checks on a file object, so if we can't
3475 // create one, we must return.
3479 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3481 $destFile = wfLocalFile( $nt );
3482 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3483 $errors[] = array( 'file-exists-sharedrepo' );
3490 * Move a title to a new location
3492 * @param $nt Title the new title
3493 * @param $auth Bool indicates whether $wgUser's permissions
3495 * @param $reason String the reason for the move
3496 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3497 * Ignored if the user doesn't have the suppressredirect right.
3498 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3500 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3502 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3503 if ( is_array( $err ) ) {
3504 // Auto-block user's IP if the account was "hard" blocked
3505 $wgUser->spreadAnyEditBlock();
3509 // If it is a file, move it first.
3510 // It is done before all other moving stuff is done because it's hard to revert.
3511 $dbw = wfGetDB( DB_MASTER
);
3512 if ( $this->getNamespace() == NS_FILE
) {
3513 $file = wfLocalFile( $this );
3514 if ( $file->exists() ) {
3515 $status = $file->move( $nt );
3516 if ( !$status->isOk() ) {
3517 return $status->getErrorsArray();
3520 // Clear RepoGroup process cache
3521 RepoGroup
::singleton()->clearCache( $this );
3522 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3525 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3526 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3527 $protected = $this->isProtected();
3529 // Do the actual move
3530 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3531 if ( is_array( $err ) ) {
3532 # @todo FIXME: What about the File we have already moved?
3533 $dbw->rollback( __METHOD__
);
3537 // Refresh the sortkey for this row. Be careful to avoid resetting
3538 // cl_timestamp, which may disturb time-based lists on some sites.
3539 $prefixes = $dbw->select(
3541 array( 'cl_sortkey_prefix', 'cl_to' ),
3542 array( 'cl_from' => $pageid ),
3545 foreach ( $prefixes as $prefixRow ) {
3546 $prefix = $prefixRow->cl_sortkey_prefix
;
3547 $catTo = $prefixRow->cl_to
;
3548 $dbw->update( 'categorylinks',
3550 'cl_sortkey' => Collation
::singleton()->getSortKey(
3551 $nt->getCategorySortkey( $prefix ) ),
3552 'cl_timestamp=cl_timestamp' ),
3554 'cl_from' => $pageid,
3555 'cl_to' => $catTo ),
3560 $redirid = $this->getArticleID();
3563 # Protect the redirect title as the title used to be...
3564 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3566 'pr_page' => $redirid,
3567 'pr_type' => 'pr_type',
3568 'pr_level' => 'pr_level',
3569 'pr_cascade' => 'pr_cascade',
3570 'pr_user' => 'pr_user',
3571 'pr_expiry' => 'pr_expiry'
3573 array( 'pr_page' => $pageid ),
3577 # Update the protection log
3578 $log = new LogPage( 'protect' );
3579 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3581 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3583 // @todo FIXME: $params?
3584 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3588 $oldnamespace = $this->getNamespace() & ~
1;
3589 $newnamespace = $nt->getNamespace() & ~
1;
3590 $oldtitle = $this->getDBkey();
3591 $newtitle = $nt->getDBkey();
3593 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3594 WatchedItem
::duplicateEntries( $this, $nt );
3597 $dbw->commit( __METHOD__
);
3599 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3604 * Move page to a title which is either a redirect to the
3605 * source page or nonexistent
3607 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3608 * @param $reason String The reason for the move
3609 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3610 * if the user doesn't have the suppressredirect right
3612 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3613 global $wgUser, $wgContLang;
3615 if ( $nt->exists() ) {
3616 $moveOverRedirect = true;
3617 $logType = 'move_redir';
3619 $moveOverRedirect = false;
3623 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3625 $logEntry = new ManualLogEntry( 'move', $logType );
3626 $logEntry->setPerformer( $wgUser );
3627 $logEntry->setTarget( $this );
3628 $logEntry->setComment( $reason );
3629 $logEntry->setParameters( array(
3630 '4::target' => $nt->getPrefixedText(),
3631 '5::noredir' => $redirectSuppressed ?
'1': '0',
3634 $formatter = LogFormatter
::newFromEntry( $logEntry );
3635 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3636 $comment = $formatter->getPlainActionText();
3638 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3640 # Truncate for whole multibyte characters.
3641 $comment = $wgContLang->truncate( $comment, 255 );
3643 $oldid = $this->getArticleID();
3645 $dbw = wfGetDB( DB_MASTER
);
3647 $newpage = WikiPage
::factory( $nt );
3649 if ( $moveOverRedirect ) {
3650 $newid = $nt->getArticleID();
3652 # Delete the old redirect. We don't save it to history since
3653 # by definition if we've got here it's rather uninteresting.
3654 # We have to remove it so that the next step doesn't trigger
3655 # a conflict on the unique namespace+title index...
3656 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3658 $newpage->doDeleteUpdates( $newid );
3661 # Save a null revision in the page's history notifying of the move
3662 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3663 if ( !is_object( $nullRevision ) ) {
3664 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3666 $nullRevId = $nullRevision->insertOn( $dbw );
3668 # Change the name of the target page:
3669 $dbw->update( 'page',
3671 'page_namespace' => $nt->getNamespace(),
3672 'page_title' => $nt->getDBkey(),
3674 /* WHERE */ array( 'page_id' => $oldid ),
3678 $this->resetArticleID( 0 );
3679 $nt->resetArticleID( $oldid );
3681 $newpage->updateRevisionOn( $dbw, $nullRevision );
3683 wfRunHooks( 'NewRevisionFromEditComplete',
3684 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3686 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3688 if ( !$moveOverRedirect ) {
3689 WikiPage
::onArticleCreate( $nt );
3692 # Recreate the redirect, this time in the other direction.
3693 if ( $redirectSuppressed ) {
3694 WikiPage
::onArticleDelete( $this );
3696 $mwRedir = MagicWord
::get( 'redirect' );
3697 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3698 $redirectArticle = WikiPage
::factory( $this );
3699 $newid = $redirectArticle->insertOn( $dbw );
3700 if ( $newid ) { // sanity
3701 $redirectRevision = new Revision( array(
3703 'comment' => $comment,
3704 'text' => $redirectText ) );
3705 $redirectRevision->insertOn( $dbw );
3706 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3708 wfRunHooks( 'NewRevisionFromEditComplete',
3709 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3711 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3716 $logid = $logEntry->insert();
3717 $logEntry->publish( $logid );
3721 * Move this page's subpages to be subpages of $nt
3723 * @param $nt Title Move target
3724 * @param $auth bool Whether $wgUser's permissions should be checked
3725 * @param $reason string The reason for the move
3726 * @param $createRedirect bool Whether to create redirects from the old subpages to
3727 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3728 * @return mixed array with old page titles as keys, and strings (new page titles) or
3729 * arrays (errors) as values, or an error array with numeric indices if no pages
3732 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3733 global $wgMaximumMovedPages;
3734 // Check permissions
3735 if ( !$this->userCan( 'move-subpages' ) ) {
3736 return array( 'cant-move-subpages' );
3738 // Do the source and target namespaces support subpages?
3739 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3740 return array( 'namespace-nosubpages',
3741 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3743 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3744 return array( 'namespace-nosubpages',
3745 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3748 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3751 foreach ( $subpages as $oldSubpage ) {
3753 if ( $count > $wgMaximumMovedPages ) {
3754 $retval[$oldSubpage->getPrefixedTitle()] =
3755 array( 'movepage-max-pages',
3756 $wgMaximumMovedPages );
3760 // We don't know whether this function was called before
3761 // or after moving the root page, so check both
3763 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3764 $oldSubpage->getArticleID() == $nt->getArticleID() )
3766 // When moving a page to a subpage of itself,
3767 // don't move it twice
3770 $newPageName = preg_replace(
3771 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3772 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3773 $oldSubpage->getDBkey() );
3774 if ( $oldSubpage->isTalkPage() ) {
3775 $newNs = $nt->getTalkPage()->getNamespace();
3777 $newNs = $nt->getSubjectPage()->getNamespace();
3779 # Bug 14385: we need makeTitleSafe because the new page names may
3780 # be longer than 255 characters.
3781 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3783 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3784 if ( $success === true ) {
3785 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3787 $retval[$oldSubpage->getPrefixedText()] = $success;
3794 * Checks if this page is just a one-rev redirect.
3795 * Adds lock, so don't use just for light purposes.
3799 public function isSingleRevRedirect() {
3800 $dbw = wfGetDB( DB_MASTER
);
3802 $row = $dbw->selectRow( 'page',
3803 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3806 array( 'FOR UPDATE' )
3808 # Cache some fields we may want
3809 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3810 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3811 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3812 if ( !$this->mRedirect
) {
3815 # Does the article have a history?
3816 $row = $dbw->selectField( array( 'page', 'revision' ),
3818 array( 'page_namespace' => $this->getNamespace(),
3819 'page_title' => $this->getDBkey(),
3821 'page_latest != rev_id'
3824 array( 'FOR UPDATE' )
3826 # Return true if there was no history
3827 return ( $row === false );
3831 * Checks if $this can be moved to a given Title
3832 * - Selects for update, so don't call it unless you mean business
3834 * @param $nt Title the new title to check
3837 public function isValidMoveTarget( $nt ) {
3838 # Is it an existing file?
3839 if ( $nt->getNamespace() == NS_FILE
) {
3840 $file = wfLocalFile( $nt );
3841 if ( $file->exists() ) {
3842 wfDebug( __METHOD__
. ": file exists\n" );
3846 # Is it a redirect with no history?
3847 if ( !$nt->isSingleRevRedirect() ) {
3848 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3851 # Get the article text
3852 $rev = Revision
::newFromTitle( $nt );
3853 if( !is_object( $rev ) ){
3856 $text = $rev->getText();
3857 # Does the redirect point to the source?
3858 # Or is it a broken self-redirect, usually caused by namespace collisions?
3860 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3861 $redirTitle = Title
::newFromText( $m[1] );
3862 if ( !is_object( $redirTitle ) ||
3863 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3864 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3865 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3870 wfDebug( __METHOD__
. ": failsafe\n" );
3877 * Get categories to which this Title belongs and return an array of
3878 * categories' names.
3880 * @return Array of parents in the form:
3881 * $parent => $currentarticle
3883 public function getParentCategories() {
3888 $titleKey = $this->getArticleID();
3890 if ( $titleKey === 0 ) {
3894 $dbr = wfGetDB( DB_SLAVE
);
3896 $res = $dbr->select( 'categorylinks', '*',
3898 'cl_from' => $titleKey,
3904 if ( $dbr->numRows( $res ) > 0 ) {
3905 foreach ( $res as $row ) {
3906 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3907 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3914 * Get a tree of parent categories
3916 * @param $children Array with the children in the keys, to check for circular refs
3917 * @return Array Tree of parent categories
3919 public function getParentCategoryTree( $children = array() ) {
3921 $parents = $this->getParentCategories();
3924 foreach ( $parents as $parent => $current ) {
3925 if ( array_key_exists( $parent, $children ) ) {
3926 # Circular reference
3927 $stack[$parent] = array();
3929 $nt = Title
::newFromText( $parent );
3931 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3941 * Get an associative array for selecting this title from
3944 * @return Array suitable for the $where parameter of DB::select()
3946 public function pageCond() {
3947 if ( $this->mArticleID
> 0 ) {
3948 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3949 return array( 'page_id' => $this->mArticleID
);
3951 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3956 * Get the revision ID of the previous revision
3958 * @param $revId Int Revision ID. Get the revision that was before this one.
3959 * @param $flags Int Title::GAID_FOR_UPDATE
3960 * @return Int|Bool Old revision ID, or FALSE if none exists
3962 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3963 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3964 return $db->selectField( 'revision', 'rev_id',
3966 'rev_page' => $this->getArticleID( $flags ),
3967 'rev_id < ' . intval( $revId )
3970 array( 'ORDER BY' => 'rev_id DESC' )
3975 * Get the revision ID of the next revision
3977 * @param $revId Int Revision ID. Get the revision that was after this one.
3978 * @param $flags Int Title::GAID_FOR_UPDATE
3979 * @return Int|Bool Next revision ID, or FALSE if none exists
3981 public function getNextRevisionID( $revId, $flags = 0 ) {
3982 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3983 return $db->selectField( 'revision', 'rev_id',
3985 'rev_page' => $this->getArticleID( $flags ),
3986 'rev_id > ' . intval( $revId )
3989 array( 'ORDER BY' => 'rev_id' )
3994 * Get the first revision of the page
3996 * @param $flags Int Title::GAID_FOR_UPDATE
3997 * @return Revision|Null if page doesn't exist
3999 public function getFirstRevision( $flags = 0 ) {
4000 $pageId = $this->getArticleID( $flags );
4002 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4003 $row = $db->selectRow( 'revision', '*',
4004 array( 'rev_page' => $pageId ),
4006 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4009 return new Revision( $row );
4016 * Get the oldest revision timestamp of this page
4018 * @param $flags Int Title::GAID_FOR_UPDATE
4019 * @return String: MW timestamp
4021 public function getEarliestRevTime( $flags = 0 ) {
4022 $rev = $this->getFirstRevision( $flags );
4023 return $rev ?
$rev->getTimestamp() : null;
4027 * Check if this is a new page
4031 public function isNewPage() {
4032 $dbr = wfGetDB( DB_SLAVE
);
4033 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4037 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4041 public function isBigDeletion() {
4042 global $wgDeleteRevisionsLimit;
4044 if ( !$wgDeleteRevisionsLimit ) {
4048 $revCount = $this->estimateRevisionCount();
4049 return $revCount > $wgDeleteRevisionsLimit;
4053 * Get the approximate revision count of this page.
4057 public function estimateRevisionCount() {
4058 if ( !$this->exists() ) {
4062 if ( $this->mEstimateRevisions
=== null ) {
4063 $dbr = wfGetDB( DB_SLAVE
);
4064 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4065 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4068 return $this->mEstimateRevisions
;
4072 * Get the number of revisions between the given revision.
4073 * Used for diffs and other things that really need it.
4075 * @param $old int|Revision Old revision or rev ID (first before range)
4076 * @param $new int|Revision New revision or rev ID (first after range)
4077 * @return Int Number of revisions between these revisions.
4079 public function countRevisionsBetween( $old, $new ) {
4080 if ( !( $old instanceof Revision
) ) {
4081 $old = Revision
::newFromTitle( $this, (int)$old );
4083 if ( !( $new instanceof Revision
) ) {
4084 $new = Revision
::newFromTitle( $this, (int)$new );
4086 if ( !$old ||
!$new ) {
4087 return 0; // nothing to compare
4089 $dbr = wfGetDB( DB_SLAVE
);
4090 return (int)$dbr->selectField( 'revision', 'count(*)',
4092 'rev_page' => $this->getArticleID(),
4093 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4094 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4101 * Get the number of authors between the given revision IDs.
4102 * Used for diffs and other things that really need it.
4104 * @param $old int|Revision Old revision or rev ID (first before range)
4105 * @param $new int|Revision New revision or rev ID (first after range)
4106 * @param $limit Int Maximum number of authors
4107 * @return Int Number of revision authors between these revisions.
4109 public function countAuthorsBetween( $old, $new, $limit ) {
4110 if ( !( $old instanceof Revision
) ) {
4111 $old = Revision
::newFromTitle( $this, (int)$old );
4113 if ( !( $new instanceof Revision
) ) {
4114 $new = Revision
::newFromTitle( $this, (int)$new );
4116 if ( !$old ||
!$new ) {
4117 return 0; // nothing to compare
4119 $dbr = wfGetDB( DB_SLAVE
);
4120 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4122 'rev_page' => $this->getArticleID(),
4123 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4124 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4126 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4128 return (int)$dbr->numRows( $res );
4132 * Compare with another title.
4134 * @param $title Title
4137 public function equals( Title
$title ) {
4138 // Note: === is necessary for proper matching of number-like titles.
4139 return $this->getInterwiki() === $title->getInterwiki()
4140 && $this->getNamespace() == $title->getNamespace()
4141 && $this->getDBkey() === $title->getDBkey();
4145 * Check if this title is a subpage of another title
4147 * @param $title Title
4150 public function isSubpageOf( Title
$title ) {
4151 return $this->getInterwiki() === $title->getInterwiki()
4152 && $this->getNamespace() == $title->getNamespace()
4153 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4157 * Check if page exists. For historical reasons, this function simply
4158 * checks for the existence of the title in the page table, and will
4159 * thus return false for interwiki links, special pages and the like.
4160 * If you want to know if a title can be meaningfully viewed, you should
4161 * probably call the isKnown() method instead.
4165 public function exists() {
4166 return $this->getArticleID() != 0;
4170 * Should links to this title be shown as potentially viewable (i.e. as
4171 * "bluelinks"), even if there's no record by this title in the page
4174 * This function is semi-deprecated for public use, as well as somewhat
4175 * misleadingly named. You probably just want to call isKnown(), which
4176 * calls this function internally.
4178 * (ISSUE: Most of these checks are cheap, but the file existence check
4179 * can potentially be quite expensive. Including it here fixes a lot of
4180 * existing code, but we might want to add an optional parameter to skip
4181 * it and any other expensive checks.)
4185 public function isAlwaysKnown() {
4189 * Allows overriding default behaviour for determining if a page exists.
4190 * If $isKnown is kept as null, regular checks happen. If it's
4191 * a boolean, this value is returned by the isKnown method.
4195 * @param Title $title
4196 * @param boolean|null $isKnown
4198 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4200 if ( !is_null( $isKnown ) ) {
4204 if ( $this->mInterwiki
!= '' ) {
4205 return true; // any interwiki link might be viewable, for all we know
4208 switch( $this->mNamespace
) {
4211 // file exists, possibly in a foreign repo
4212 return (bool)wfFindFile( $this );
4214 // valid special page
4215 return SpecialPageFactory
::exists( $this->getDBkey() );
4217 // selflink, possibly with fragment
4218 return $this->mDbkeyform
== '';
4220 // known system message
4221 return $this->hasSourceText() !== false;
4228 * Does this title refer to a page that can (or might) be meaningfully
4229 * viewed? In particular, this function may be used to determine if
4230 * links to the title should be rendered as "bluelinks" (as opposed to
4231 * "redlinks" to non-existent pages).
4232 * Adding something else to this function will cause inconsistency
4233 * since LinkHolderArray calls isAlwaysKnown() and does its own
4234 * page existence check.
4238 public function isKnown() {
4239 return $this->isAlwaysKnown() ||
$this->exists();
4243 * Does this page have source text?
4247 public function hasSourceText() {
4248 if ( $this->exists() ) {
4252 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4253 // If the page doesn't exist but is a known system message, default
4254 // message content will be displayed, same for language subpages-
4255 // Use always content language to avoid loading hundreds of languages
4256 // to get the link color.
4258 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4259 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4260 return $message->exists();
4267 * Get the default message text or false if the message doesn't exist
4269 * @return String or false
4271 public function getDefaultMessageText() {
4274 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4278 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4279 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4281 if ( $message->exists() ) {
4282 return $message->plain();
4289 * Updates page_touched for this page; called from LinksUpdate.php
4291 * @return Bool true if the update succeded
4293 public function invalidateCache() {
4294 if ( wfReadOnly() ) {
4297 $dbw = wfGetDB( DB_MASTER
);
4298 $success = $dbw->update(
4300 array( 'page_touched' => $dbw->timestamp() ),
4304 HTMLFileCache
::clearFileCache( $this );
4309 * Update page_touched timestamps and send squid purge messages for
4310 * pages linking to this title. May be sent to the job queue depending
4311 * on the number of links. Typically called on create and delete.
4313 public function touchLinks() {
4314 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4317 if ( $this->getNamespace() == NS_CATEGORY
) {
4318 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4324 * Get the last touched timestamp
4326 * @param $db DatabaseBase: optional db
4327 * @return String last-touched timestamp
4329 public function getTouched( $db = null ) {
4330 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4331 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4336 * Get the timestamp when this page was updated since the user last saw it.
4339 * @return String|Null
4341 public function getNotificationTimestamp( $user = null ) {
4342 global $wgUser, $wgShowUpdatedMarker;
4343 // Assume current user if none given
4347 // Check cache first
4348 $uid = $user->getId();
4349 // avoid isset here, as it'll return false for null entries
4350 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4351 return $this->mNotificationTimestamp
[$uid];
4353 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4354 return $this->mNotificationTimestamp
[$uid] = false;
4356 // Don't cache too much!
4357 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4358 $this->mNotificationTimestamp
= array();
4360 $dbr = wfGetDB( DB_SLAVE
);
4361 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4362 'wl_notificationtimestamp',
4363 array( 'wl_namespace' => $this->getNamespace(),
4364 'wl_title' => $this->getDBkey(),
4365 'wl_user' => $user->getId()
4369 return $this->mNotificationTimestamp
[$uid];
4373 * Generate strings used for xml 'id' names in monobook tabs
4375 * @param $prepend string defaults to 'nstab-'
4376 * @return String XML 'id' name
4378 public function getNamespaceKey( $prepend = 'nstab-' ) {
4380 // Gets the subject namespace if this title
4381 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4382 // Checks if cononical namespace name exists for namespace
4383 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4384 // Uses canonical namespace name
4385 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4387 // Uses text of namespace
4388 $namespaceKey = $this->getSubjectNsText();
4390 // Makes namespace key lowercase
4391 $namespaceKey = $wgContLang->lc( $namespaceKey );
4393 if ( $namespaceKey == '' ) {
4394 $namespaceKey = 'main';
4396 // Changes file to image for backwards compatibility
4397 if ( $namespaceKey == 'file' ) {
4398 $namespaceKey = 'image';
4400 return $prepend . $namespaceKey;
4404 * Get all extant redirects to this Title
4406 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4407 * @return Array of Title redirects to this title
4409 public function getRedirectsHere( $ns = null ) {
4412 $dbr = wfGetDB( DB_SLAVE
);
4414 'rd_namespace' => $this->getNamespace(),
4415 'rd_title' => $this->getDBkey(),
4418 if ( !is_null( $ns ) ) {
4419 $where['page_namespace'] = $ns;
4422 $res = $dbr->select(
4423 array( 'redirect', 'page' ),
4424 array( 'page_namespace', 'page_title' ),
4429 foreach ( $res as $row ) {
4430 $redirs[] = self
::newFromRow( $row );
4436 * Check if this Title is a valid redirect target
4440 public function isValidRedirectTarget() {
4441 global $wgInvalidRedirectTargets;
4443 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4444 if ( $this->isSpecial( 'Userlogout' ) ) {
4448 foreach ( $wgInvalidRedirectTargets as $target ) {
4449 if ( $this->isSpecial( $target ) ) {
4458 * Get a backlink cache object
4460 * @return BacklinkCache
4462 function getBacklinkCache() {
4463 if ( is_null( $this->mBacklinkCache
) ) {
4464 $this->mBacklinkCache
= new BacklinkCache( $this );
4466 return $this->mBacklinkCache
;
4470 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4474 public function canUseNoindex() {
4475 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4477 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4478 ?
$wgContentNamespaces
4479 : $wgExemptFromUserRobotsControl;
4481 return !in_array( $this->mNamespace
, $bannedNamespaces );
4486 * Returns the raw sort key to be used for categories, with the specified
4487 * prefix. This will be fed to Collation::getSortKey() to get a
4488 * binary sortkey that can be used for actual sorting.
4490 * @param $prefix string The prefix to be used, specified using
4491 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4495 public function getCategorySortkey( $prefix = '' ) {
4496 $unprefixed = $this->getText();
4498 // Anything that uses this hook should only depend
4499 // on the Title object passed in, and should probably
4500 // tell the users to run updateCollations.php --force
4501 // in order to re-sort existing category relations.
4502 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4503 if ( $prefix !== '' ) {
4504 # Separate with a line feed, so the unprefixed part is only used as
4505 # a tiebreaker when two pages have the exact same prefix.
4506 # In UCA, tab is the only character that can sort above LF
4507 # so we strip both of them from the original prefix.
4508 $prefix = strtr( $prefix, "\n\t", ' ' );
4509 return "$prefix\n$unprefixed";
4515 * Get the language in which the content of this page is written.
4516 * Defaults to $wgContLang, but in certain cases it can be e.g.
4517 * $wgLang (such as special pages, which are in the user language).
4520 * @return object Language
4522 public function getPageLanguage() {
4524 if ( $this->isSpecialPage() ) {
4525 // special pages are in the user language
4527 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4528 // css/js should always be LTR and is, in fact, English
4529 return wfGetLangObj( 'en' );
4530 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4531 // Parse mediawiki messages with correct target language
4532 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4533 return wfGetLangObj( $lang );
4536 // If nothing special, it should be in the wiki content language
4537 $pageLang = $wgContLang;
4538 // Hook at the end because we don't want to override the above stuff
4539 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4540 return wfGetLangObj( $pageLang );