3 * Representation a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
31 * @internal documentation reviewed 15 Mar 2010
34 /** @name Static cache variables */
36 static private $titleCache = array();
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
69 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
70 var $mOldRestrictions = false;
71 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
72 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
73 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
74 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
75 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
76 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
77 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
78 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
79 # Don't change the following default, NS_MAIN is hardcoded in several
80 # places. See bug 696.
81 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
82 # Zero except in {{transclusion}} tags
83 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
84 var $mLength = -1; // /< The page length, 0 for special pages
85 var $mRedirect = null; // /< Is the article at this title a redirect?
86 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
87 var $mHasSubpage; // /< Whether a page has any subpages
94 /*protected*/ function __construct() { }
97 * Create a new Title from a prefixed DB key
99 * @param $key String the database key, which has underscores
100 * instead of spaces, possibly including namespace and
102 * @return Title, or NULL on an error
104 public static function newFromDBkey( $key ) {
106 $t->mDbkeyform
= $key;
107 if ( $t->secureAndSplit() ) {
115 * Create a new Title from text, such as what one would find in a link. De-
116 * codes any HTML entities in the text.
118 * @param $text String the link text; spaces, prefixes, and an
119 * initial ':' indicating the main namespace are accepted.
120 * @param $defaultNamespace Int the namespace to use if none is speci-
121 * fied by a prefix. If you want to force a specific namespace even if
122 * $text might begin with a namespace prefix, use makeTitle() or
124 * @throws MWException
125 * @return Title|null - Title or null on an error.
127 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
128 if ( is_object( $text ) ) {
129 throw new MWException( 'Title::newFromText given an object' );
133 * Wiki pages often contain multiple links to the same page.
134 * Title normalization and parsing can become expensive on
135 * pages with many links, so we can save a little time by
138 * In theory these are value objects and won't get changed...
140 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
141 return Title
::$titleCache[$text];
144 # Convert things like é ā or 〗 into normalized (bug 14952) text
145 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
148 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
149 $t->mDefaultNamespace
= $defaultNamespace;
151 static $cachedcount = 0 ;
152 if ( $t->secureAndSplit() ) {
153 if ( $defaultNamespace == NS_MAIN
) {
154 if ( $cachedcount >= self
::CACHE_MAX
) {
155 # Avoid memory leaks on mass operations...
156 Title
::$titleCache = array();
160 Title
::$titleCache[$text] =& $t;
170 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
172 * Example of wrong and broken code:
173 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
175 * Example of right code:
176 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
178 * Create a new Title from URL-encoded text. Ensures that
179 * the given title's length does not exceed the maximum.
181 * @param $url String the title, as might be taken from a URL
182 * @return Title the new object, or NULL on an error
184 public static function newFromURL( $url ) {
187 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
188 # but some URLs used it as a space replacement and they still come
189 # from some external search tools.
190 if ( strpos( self
::legalChars(), '+' ) === false ) {
191 $url = str_replace( '+', ' ', $url );
194 $t->mDbkeyform
= str_replace( ' ', '_', $url );
195 if ( $t->secureAndSplit() ) {
203 * Create a new Title from an article ID
205 * @param $id Int the page_id corresponding to the Title to create
206 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
207 * @return Title the new object, or NULL on an error
209 public static function newFromID( $id, $flags = 0 ) {
210 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
211 $row = $db->selectRow(
214 'page_namespace', 'page_title', 'page_id',
215 'page_len', 'page_is_redirect', 'page_latest',
217 array( 'page_id' => $id ),
220 if ( $row !== false ) {
221 $title = Title
::newFromRow( $row );
229 * Make an array of titles from an array of IDs
231 * @param $ids Array of Int Array of IDs
232 * @return Array of Titles
234 public static function newFromIDs( $ids ) {
235 if ( !count( $ids ) ) {
238 $dbr = wfGetDB( DB_SLAVE
);
243 'page_namespace', 'page_title', 'page_id',
244 'page_len', 'page_is_redirect', 'page_latest',
246 array( 'page_id' => $ids ),
251 foreach ( $res as $row ) {
252 $titles[] = Title
::newFromRow( $row );
258 * Make a Title object from a DB row
260 * @param $row Object database row (needs at least page_title,page_namespace)
261 * @return Title corresponding Title
263 public static function newFromRow( $row ) {
264 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
265 $t->loadFromRow( $row );
270 * Load Title object fields from a DB row.
271 * If false is given, the title will be treated as non-existing.
273 * @param $row Object|bool database row
275 public function loadFromRow( $row ) {
276 if ( $row ) { // page found
277 if ( isset( $row->page_id
) )
278 $this->mArticleID
= (int)$row->page_id
;
279 if ( isset( $row->page_len
) )
280 $this->mLength
= (int)$row->page_len
;
281 if ( isset( $row->page_is_redirect
) )
282 $this->mRedirect
= (bool)$row->page_is_redirect
;
283 if ( isset( $row->page_latest
) )
284 $this->mLatestID
= (int)$row->page_latest
;
285 } else { // page not found
286 $this->mArticleID
= 0;
288 $this->mRedirect
= false;
289 $this->mLatestID
= 0;
294 * Create a new Title from a namespace index and a DB key.
295 * It's assumed that $ns and $title are *valid*, for instance when
296 * they came directly from the database or a special page name.
297 * For convenience, spaces are converted to underscores so that
298 * eg user_text fields can be used directly.
300 * @param $ns Int the namespace of the article
301 * @param $title String the unprefixed database key form
302 * @param $fragment String the link fragment (after the "#")
303 * @param $interwiki String the interwiki prefix
304 * @return Title the new object
306 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
308 $t->mInterwiki
= $interwiki;
309 $t->mFragment
= $fragment;
310 $t->mNamespace
= $ns = intval( $ns );
311 $t->mDbkeyform
= str_replace( ' ', '_', $title );
312 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
313 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
314 $t->mTextform
= str_replace( '_', ' ', $title );
319 * Create a new Title from a namespace index and a DB key.
320 * The parameters will be checked for validity, which is a bit slower
321 * than makeTitle() but safer for user-provided data.
323 * @param $ns Int the namespace of the article
324 * @param $title String database key form
325 * @param $fragment String the link fragment (after the "#")
326 * @param $interwiki String interwiki prefix
327 * @return Title the new object, or NULL on an error
329 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
330 if ( !MWNamespace
::exists( $ns ) ) {
335 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
336 if ( $t->secureAndSplit() ) {
344 * Create a new Title for the Main Page
346 * @return Title the new object
348 public static function newMainPage() {
349 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
350 // Don't give fatal errors if the message is broken
352 $title = Title
::newFromText( 'Main Page' );
358 * Extract a redirect destination from a string and return the
359 * Title, or null if the text doesn't contain a valid redirect
360 * This will only return the very next target, useful for
361 * the redirect table and other checks that don't need full recursion
363 * @param $text String: Text with possible redirect
364 * @return Title: The corresponding Title
366 public static function newFromRedirect( $text ) {
367 return self
::newFromRedirectInternal( $text );
371 * Extract a redirect destination from a string and return the
372 * Title, or null if the text doesn't contain a valid redirect
373 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
374 * in order to provide (hopefully) the Title of the final destination instead of another redirect
376 * @param $text String Text with possible redirect
379 public static function newFromRedirectRecurse( $text ) {
380 $titles = self
::newFromRedirectArray( $text );
381 return $titles ?
array_pop( $titles ) : null;
385 * Extract a redirect destination from a string and return an
386 * array of Titles, or null if the text doesn't contain a valid redirect
387 * The last element in the array is the final destination after all redirects
388 * have been resolved (up to $wgMaxRedirects times)
390 * @param $text String Text with possible redirect
391 * @return Array of Titles, with the destination last
393 public static function newFromRedirectArray( $text ) {
394 global $wgMaxRedirects;
395 $title = self
::newFromRedirectInternal( $text );
396 if ( is_null( $title ) ) {
399 // recursive check to follow double redirects
400 $recurse = $wgMaxRedirects;
401 $titles = array( $title );
402 while ( --$recurse > 0 ) {
403 if ( $title->isRedirect() ) {
404 $page = WikiPage
::factory( $title );
405 $newtitle = $page->getRedirectTarget();
409 // Redirects to some special pages are not permitted
410 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
411 // the new title passes the checks, so make that our current title so that further recursion can be checked
413 $titles[] = $newtitle;
422 * Really extract the redirect destination
423 * Do not call this function directly, use one of the newFromRedirect* functions above
425 * @param $text String Text with possible redirect
428 protected static function newFromRedirectInternal( $text ) {
429 global $wgMaxRedirects;
430 if ( $wgMaxRedirects < 1 ) {
431 //redirects are disabled, so quit early
434 $redir = MagicWord
::get( 'redirect' );
435 $text = trim( $text );
436 if ( $redir->matchStartAndRemove( $text ) ) {
437 // Extract the first link and see if it's usable
438 // Ensure that it really does come directly after #REDIRECT
439 // Some older redirects included a colon, so don't freak about that!
441 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
442 // Strip preceding colon used to "escape" categories, etc.
443 // and URL-decode links
444 if ( strpos( $m[1], '%' ) !== false ) {
445 // Match behavior of inline link parsing here;
446 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
448 $title = Title
::newFromText( $m[1] );
449 // If the title is a redirect to bad special pages or is invalid, return null
450 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
460 * Get the prefixed DB key associated with an ID
462 * @param $id Int the page_id of the article
463 * @return Title an object representing the article, or NULL if no such article was found
465 public static function nameOf( $id ) {
466 $dbr = wfGetDB( DB_SLAVE
);
468 $s = $dbr->selectRow(
470 array( 'page_namespace', 'page_title' ),
471 array( 'page_id' => $id ),
474 if ( $s === false ) {
478 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
483 * Get a regex character class describing the legal characters in a link
485 * @return String the list of characters, not delimited
487 public static function legalChars() {
488 global $wgLegalTitleChars;
489 return $wgLegalTitleChars;
493 * Returns a simple regex that will match on characters and sequences invalid in titles.
494 * Note that this doesn't pick up many things that could be wrong with titles, but that
495 * replacing this regex with something valid will make many titles valid.
497 * @return String regex string
499 static function getTitleInvalidRegex() {
500 static $rxTc = false;
502 # Matching titles will be held as illegal.
504 # Any character not allowed is forbidden...
505 '[^' . self
::legalChars() . ']' .
506 # URL percent encoding sequences interfere with the ability
507 # to round-trip titles -- you can't link to them consistently.
509 # XML/HTML character references produce similar issues.
510 '|&[A-Za-z0-9\x80-\xff]+;' .
512 '|&#x[0-9A-Fa-f]+;' .
520 * Get a string representation of a title suitable for
521 * including in a search index
523 * @param $ns Int a namespace index
524 * @param $title String text-form main part
525 * @return String a stripped-down title string ready for the search index
527 public static function indexTitle( $ns, $title ) {
530 $lc = SearchEngine
::legalSearchChars() . '&#;';
531 $t = $wgContLang->normalizeForSearch( $title );
532 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
533 $t = $wgContLang->lc( $t );
536 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
537 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
539 $t = preg_replace( "/\\s+/", ' ', $t );
541 if ( $ns == NS_FILE
) {
542 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
548 * Make a prefixed DB key from a DB key and a namespace index
550 * @param $ns Int numerical representation of the namespace
551 * @param $title String the DB key form the title
552 * @param $fragment String The link fragment (after the "#")
553 * @param $interwiki String The interwiki prefix
554 * @return String the prefixed form of the title
556 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
559 $namespace = $wgContLang->getNsText( $ns );
560 $name = $namespace == '' ?
$title : "$namespace:$title";
561 if ( strval( $interwiki ) != '' ) {
562 $name = "$interwiki:$name";
564 if ( strval( $fragment ) != '' ) {
565 $name .= '#' . $fragment;
571 * Escape a text fragment, say from a link, for a URL
573 * @param $fragment string containing a URL or link fragment (after the "#")
574 * @return String: escaped string
576 static function escapeFragmentForURL( $fragment ) {
577 # Note that we don't urlencode the fragment. urlencoded Unicode
578 # fragments appear not to work in IE (at least up to 7) or in at least
579 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
580 # to care if they aren't encoded.
581 return Sanitizer
::escapeId( $fragment, 'noninitial' );
585 * Callback for usort() to do title sorts by (namespace, title)
590 * @return Integer: result of string comparison, or namespace comparison
592 public static function compare( $a, $b ) {
593 if ( $a->getNamespace() == $b->getNamespace() ) {
594 return strcmp( $a->getText(), $b->getText() );
596 return $a->getNamespace() - $b->getNamespace();
601 * Determine whether the object refers to a page within
604 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
606 public function isLocal() {
607 if ( $this->mInterwiki
!= '' ) {
608 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
615 * Is this Title interwiki?
619 public function isExternal() {
620 return ( $this->mInterwiki
!= '' );
624 * Get the interwiki prefix (or null string)
626 * @return String Interwiki prefix
628 public function getInterwiki() {
629 return $this->mInterwiki
;
633 * Determine whether the object refers to a page within
634 * this project and is transcludable.
636 * @return Bool TRUE if this is transcludable
638 public function isTrans() {
639 if ( $this->mInterwiki
== '' ) {
643 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
647 * Returns the DB name of the distant wiki which owns the object.
649 * @return String the DB name
651 public function getTransWikiID() {
652 if ( $this->mInterwiki
== '' ) {
656 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
660 * Get the text form (spaces not underscores) of the main part
662 * @return String Main part of the title
664 public function getText() {
665 return $this->mTextform
;
669 * Get the URL-encoded form of the main part
671 * @return String Main part of the title, URL-encoded
673 public function getPartialURL() {
674 return $this->mUrlform
;
678 * Get the main part with underscores
680 * @return String: Main part of the title, with underscores
682 public function getDBkey() {
683 return $this->mDbkeyform
;
687 * Get the DB key with the initial letter case as specified by the user
689 * @return String DB key
691 function getUserCaseDBKey() {
692 return $this->mUserCaseDBKey
;
696 * Get the namespace index, i.e. one of the NS_xxxx constants.
698 * @return Integer: Namespace index
700 public function getNamespace() {
701 return $this->mNamespace
;
705 * Get the namespace text
707 * @return String: Namespace text
709 public function getNsText() {
712 if ( $this->mInterwiki
!= '' ) {
713 // This probably shouldn't even happen. ohh man, oh yuck.
714 // But for interwiki transclusion it sometimes does.
715 // Shit. Shit shit shit.
717 // Use the canonical namespaces if possible to try to
718 // resolve a foreign namespace.
719 if ( MWNamespace
::exists( $this->mNamespace
) ) {
720 return MWNamespace
::getCanonicalName( $this->mNamespace
);
724 if ( $wgContLang->needsGenderDistinction() &&
725 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
726 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
727 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
730 return $wgContLang->getNsText( $this->mNamespace
);
734 * Get the namespace text of the subject (rather than talk) page
736 * @return String Namespace text
738 public function getSubjectNsText() {
740 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
744 * Get the namespace text of the talk page
746 * @return String Namespace text
748 public function getTalkNsText() {
750 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
754 * Could this title have a corresponding talk page?
756 * @return Bool TRUE or FALSE
758 public function canTalk() {
759 return( MWNamespace
::canTalk( $this->mNamespace
) );
763 * Is this in a namespace that allows actual pages?
766 * @internal note -- uses hardcoded namespace index instead of constants
768 public function canExist() {
769 return $this->mNamespace
>= NS_MAIN
;
773 * Can this title be added to a user's watchlist?
775 * @return Bool TRUE or FALSE
777 public function isWatchable() {
778 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
782 * Returns true if this is a special page.
786 public function isSpecialPage() {
787 return $this->getNamespace() == NS_SPECIAL
;
791 * Returns true if this title resolves to the named special page
793 * @param $name String The special page name
796 public function isSpecial( $name ) {
797 if ( $this->isSpecialPage() ) {
798 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
799 if ( $name == $thisName ) {
807 * If the Title refers to a special page alias which is not the local default, resolve
808 * the alias, and localise the name as necessary. Otherwise, return $this
812 public function fixSpecialName() {
813 if ( $this->isSpecialPage() ) {
814 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
815 if ( $canonicalName ) {
816 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
817 if ( $localName != $this->mDbkeyform
) {
818 return Title
::makeTitle( NS_SPECIAL
, $localName );
826 * Returns true if the title is inside the specified namespace.
828 * Please make use of this instead of comparing to getNamespace()
829 * This function is much more resistant to changes we may make
830 * to namespaces than code that makes direct comparisons.
831 * @param $ns int The namespace
835 public function inNamespace( $ns ) {
836 return MWNamespace
::equals( $this->getNamespace(), $ns );
840 * Returns true if the title is inside one of the specified namespaces.
842 * @param ...$namespaces The namespaces to check for
846 public function inNamespaces( /* ... */ ) {
847 $namespaces = func_get_args();
848 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
849 $namespaces = $namespaces[0];
852 foreach ( $namespaces as $ns ) {
853 if ( $this->inNamespace( $ns ) ) {
862 * Returns true if the title has the same subject namespace as the
863 * namespace specified.
864 * For example this method will take NS_USER and return true if namespace
865 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
866 * as their subject namespace.
868 * This is MUCH simpler than individually testing for equivilance
869 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
874 public function hasSubjectNamespace( $ns ) {
875 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
879 * Is this Title in a namespace which contains content?
880 * In other words, is this a content page, for the purposes of calculating
885 public function isContentPage() {
886 return MWNamespace
::isContent( $this->getNamespace() );
890 * Would anybody with sufficient privileges be able to move this page?
891 * Some pages just aren't movable.
893 * @return Bool TRUE or FALSE
895 public function isMovable() {
896 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
897 // Interwiki title or immovable namespace. Hooks don't get to override here
902 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
907 * Is this the mainpage?
908 * @note Title::newFromText seams to be sufficiently optimized by the title
909 * cache that we don't need to over-optimize by doing direct comparisons and
910 * acidentally creating new bugs where $title->equals( Title::newFromText() )
911 * ends up reporting something differently than $title->isMainPage();
916 public function isMainPage() {
917 return $this->equals( Title
::newMainPage() );
925 public function isSubpage() {
926 return MWNamespace
::hasSubpages( $this->mNamespace
)
927 ?
strpos( $this->getText(), '/' ) !== false
932 * Is this a conversion table for the LanguageConverter?
936 public function isConversionTable() {
937 return $this->getNamespace() == NS_MEDIAWIKI
&&
938 strpos( $this->getText(), 'Conversiontable/' ) === 0;
942 * Does that page contain wikitext, or it is JS, CSS or whatever?
946 public function isWikitextPage() {
947 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
948 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
953 * Could this page contain custom CSS or JavaScript, based
958 public function isCssOrJsPage() {
959 $retval = $this->mNamespace
== NS_MEDIAWIKI
960 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
961 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
966 * Is this a .css or .js subpage of a user page?
969 public function isCssJsSubpage() {
970 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
974 * Trim down a .css or .js subpage title to get the corresponding skin name
976 * @return string containing skin name from .css or .js subpage title
978 public function getSkinFromCssJsSubpage() {
979 $subpage = explode( '/', $this->mTextform
);
980 $subpage = $subpage[ count( $subpage ) - 1 ];
981 $lastdot = strrpos( $subpage, '.' );
982 if ( $lastdot === false )
983 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
984 return substr( $subpage, 0, $lastdot );
988 * Is this a .css subpage of a user page?
992 public function isCssSubpage() {
993 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
997 * Is this a .js subpage of a user page?
1001 public function isJsSubpage() {
1002 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1006 * Is this a talk page of some sort?
1010 public function isTalkPage() {
1011 return MWNamespace
::isTalk( $this->getNamespace() );
1015 * Get a Title object associated with the talk page of this article
1017 * @return Title the object for the talk page
1019 public function getTalkPage() {
1020 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1024 * Get a title object associated with the subject page of this
1027 * @return Title the object for the subject page
1029 public function getSubjectPage() {
1030 // Is this the same title?
1031 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1032 if ( $this->getNamespace() == $subjectNS ) {
1035 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1039 * Get the default namespace index, for when there is no namespace
1041 * @return Int Default namespace index
1043 public function getDefaultNamespace() {
1044 return $this->mDefaultNamespace
;
1048 * Get title for search index
1050 * @return String a stripped-down title string ready for the
1053 public function getIndexTitle() {
1054 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1058 * Get the Title fragment (i.e.\ the bit after the #) in text form
1060 * @return String Title fragment
1062 public function getFragment() {
1063 return $this->mFragment
;
1067 * Get the fragment in URL form, including the "#" character if there is one
1068 * @return String Fragment in URL form
1070 public function getFragmentForURL() {
1071 if ( $this->mFragment
== '' ) {
1074 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1079 * Set the fragment for this title. Removes the first character from the
1080 * specified fragment before setting, so it assumes you're passing it with
1083 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1084 * Still in active use privately.
1086 * @param $fragment String text
1088 public function setFragment( $fragment ) {
1089 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1093 * Prefix some arbitrary text with the namespace or interwiki prefix
1096 * @param $name String the text
1097 * @return String the prefixed text
1100 private function prefix( $name ) {
1102 if ( $this->mInterwiki
!= '' ) {
1103 $p = $this->mInterwiki
. ':';
1106 if ( 0 != $this->mNamespace
) {
1107 $p .= $this->getNsText() . ':';
1113 * Get the prefixed database key form
1115 * @return String the prefixed title, with underscores and
1116 * any interwiki and namespace prefixes
1118 public function getPrefixedDBkey() {
1119 $s = $this->prefix( $this->mDbkeyform
);
1120 $s = str_replace( ' ', '_', $s );
1125 * Get the prefixed title with spaces.
1126 * This is the form usually used for display
1128 * @return String the prefixed title, with spaces
1130 public function getPrefixedText() {
1131 // @todo FIXME: Bad usage of empty() ?
1132 if ( empty( $this->mPrefixedText
) ) {
1133 $s = $this->prefix( $this->mTextform
);
1134 $s = str_replace( '_', ' ', $s );
1135 $this->mPrefixedText
= $s;
1137 return $this->mPrefixedText
;
1141 * Return a string representation of this title
1143 * @return String representation of this title
1145 public function __toString() {
1146 return $this->getPrefixedText();
1150 * Get the prefixed title with spaces, plus any fragment
1151 * (part beginning with '#')
1153 * @return String the prefixed title, with spaces and the fragment, including '#'
1155 public function getFullText() {
1156 $text = $this->getPrefixedText();
1157 if ( $this->mFragment
!= '' ) {
1158 $text .= '#' . $this->mFragment
;
1164 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1168 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1172 * @return String Root name
1175 public function getRootText() {
1176 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1177 return $this->getText();
1180 return strtok( $this->getText(), '/' );
1184 * Get the root page name title, i.e. the leftmost part before any slashes
1188 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1189 * # returns: Title{User:Foo}
1192 * @return Title Root title
1195 public function getRootTitle() {
1196 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1200 * Get the base page name without a namespace, i.e. the part before the subpage name
1204 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1205 * # returns: 'Foo/Bar'
1208 * @return String Base name
1210 public function getBaseText() {
1211 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1212 return $this->getText();
1215 $parts = explode( '/', $this->getText() );
1216 # Don't discard the real title if there's no subpage involved
1217 if ( count( $parts ) > 1 ) {
1218 unset( $parts[count( $parts ) - 1] );
1220 return implode( '/', $parts );
1224 * Get the base page name title, i.e. the part before the subpage name
1228 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1229 * # returns: Title{User:Foo/Bar}
1232 * @return Title Base title
1235 public function getBaseTitle() {
1236 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1240 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1244 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1248 * @return String Subpage name
1250 public function getSubpageText() {
1251 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1252 return( $this->mTextform
);
1254 $parts = explode( '/', $this->mTextform
);
1255 return( $parts[count( $parts ) - 1] );
1259 * Get the title for a subpage of the current page
1263 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1264 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1267 * @param $text String The subpage name to add to the title
1268 * @return Title Subpage title
1271 public function getSubpage( $text ) {
1272 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1276 * Get the HTML-escaped displayable text form.
1277 * Used for the title field in <a> tags.
1279 * @return String the text, including any prefixes
1281 public function getEscapedText() {
1282 wfDeprecated( __METHOD__
, '1.19' );
1283 return htmlspecialchars( $this->getPrefixedText() );
1287 * Get a URL-encoded form of the subpage text
1289 * @return String URL-encoded subpage name
1291 public function getSubpageUrlForm() {
1292 $text = $this->getSubpageText();
1293 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1298 * Get a URL-encoded title (not an actual URL) including interwiki
1300 * @return String the URL-encoded form
1302 public function getPrefixedURL() {
1303 $s = $this->prefix( $this->mDbkeyform
);
1304 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1309 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1310 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1311 * second argument named variant. This was deprecated in favor
1312 * of passing an array of option with a "variant" key
1313 * Once $query2 is removed for good, this helper can be dropped
1314 * andthe wfArrayToCGI moved to getLocalURL();
1316 * @since 1.19 (r105919)
1318 * @param $query2 bool
1321 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1322 if( $query2 !== false ) {
1323 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" );
1325 if ( is_array( $query ) ) {
1326 $query = wfArrayToCGI( $query );
1329 if ( is_string( $query2 ) ) {
1330 // $query2 is a string, we will consider this to be
1331 // a deprecated $variant argument and add it to the query
1332 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1334 $query2 = wfArrayToCGI( $query2 );
1336 // If we have $query content add a & to it first
1340 // Now append the queries together
1347 * Get a real URL referring to this title, with interwiki link and
1350 * See getLocalURL for the arguments.
1352 * @see self::getLocalURL
1354 * @param $proto Protocol type to use in URL
1355 * @return String the URL
1357 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1358 $query = self
::fixUrlQueryArgs( $query, $query2 );
1360 # Hand off all the decisions on urls to getLocalURL
1361 $url = $this->getLocalURL( $query );
1363 # Expand the url to make it a full url. Note that getLocalURL has the
1364 # potential to output full urls for a variety of reasons, so we use
1365 # wfExpandUrl instead of simply prepending $wgServer
1366 $url = wfExpandUrl( $url, $proto );
1368 # Finally, add the fragment.
1369 $url .= $this->getFragmentForURL();
1371 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1376 * Get a URL with no fragment or server name. If this page is generated
1377 * with action=render, $wgServer is prepended.
1380 * @param $query string|array an optional query string,
1381 * not used for interwiki links. Can be specified as an associative array as well,
1382 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1383 * Some query patterns will trigger various shorturl path replacements.
1384 * @param $query2 Mixed: An optional secondary query array. This one MUST
1385 * be an array. If a string is passed it will be interpreted as a deprecated
1386 * variant argument and urlencoded into a variant= argument.
1387 * This second query argument will be added to the $query
1388 * The second parameter is deprecated since 1.19. Pass it as a key,value
1389 * pair in the first parameter array instead.
1391 * @return String the URL
1393 public function getLocalURL( $query = '', $query2 = false ) {
1394 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1396 $query = self
::fixUrlQueryArgs( $query, $query2 );
1398 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1400 $namespace = $this->getNsText();
1401 if ( $namespace != '' ) {
1402 # Can this actually happen? Interwikis shouldn't be parsed.
1403 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1406 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1407 $url = wfAppendQuery( $url, $query );
1409 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1410 if ( $query == '' ) {
1411 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1412 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1414 global $wgVariantArticlePath, $wgActionPaths;
1418 if ( !empty( $wgActionPaths ) &&
1419 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1421 $action = urldecode( $matches[2] );
1422 if ( isset( $wgActionPaths[$action] ) ) {
1423 $query = $matches[1];
1424 if ( isset( $matches[4] ) ) {
1425 $query .= $matches[4];
1427 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1428 if ( $query != '' ) {
1429 $url = wfAppendQuery( $url, $query );
1434 if ( $url === false &&
1435 $wgVariantArticlePath &&
1436 $this->getPageLanguage()->hasVariants() &&
1437 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1439 $variant = urldecode( $matches[1] );
1440 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1441 // Only do the variant replacement if the given variant is a valid
1442 // variant for the page's language.
1443 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1444 $url = str_replace( '$1', $dbkey, $url );
1448 if ( $url === false ) {
1449 if ( $query == '-' ) {
1452 $url = "{$wgScript}?title={$dbkey}&{$query}";
1456 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1458 // @todo FIXME: This causes breakage in various places when we
1459 // actually expected a local URL and end up with dupe prefixes.
1460 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1461 $url = $wgServer . $url;
1464 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1469 * Get a URL that's the simplest URL that will be valid to link, locally,
1470 * to the current Title. It includes the fragment, but does not include
1471 * the server unless action=render is used (or the link is external). If
1472 * there's a fragment but the prefixed text is empty, we just return a link
1475 * The result obviously should not be URL-escaped, but does need to be
1476 * HTML-escaped if it's being output in HTML.
1478 * See getLocalURL for the arguments.
1480 * @param $proto Protocol to use; setting this will cause a full URL to be used
1481 * @see self::getLocalURL
1482 * @return String the URL
1484 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1485 wfProfileIn( __METHOD__
);
1486 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1487 $ret = $this->getFullURL( $query, $query2, $proto );
1488 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1489 $ret = $this->getFragmentForURL();
1491 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1493 wfProfileOut( __METHOD__
);
1498 * Get an HTML-escaped version of the URL form, suitable for
1499 * using in a link, without a server name or fragment
1501 * See getLocalURL for the arguments.
1503 * @see self::getLocalURL
1504 * @param $query string
1505 * @param $query2 bool|string
1506 * @return String the URL
1508 public function escapeLocalURL( $query = '', $query2 = false ) {
1509 wfDeprecated( __METHOD__
, '1.19' );
1510 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1514 * Get an HTML-escaped version of the URL form, suitable for
1515 * using in a link, including the server name and fragment
1517 * See getLocalURL for the arguments.
1519 * @see self::getLocalURL
1520 * @return String the URL
1522 public function escapeFullURL( $query = '', $query2 = false ) {
1523 wfDeprecated( __METHOD__
, '1.19' );
1524 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1528 * Get the URL form for an internal link.
1529 * - Used in various Squid-related code, in case we have a different
1530 * internal hostname for the server from the exposed one.
1532 * This uses $wgInternalServer to qualify the path, or $wgServer
1533 * if $wgInternalServer is not set. If the server variable used is
1534 * protocol-relative, the URL will be expanded to http://
1536 * See getLocalURL for the arguments.
1538 * @see self::getLocalURL
1539 * @return String the URL
1541 public function getInternalURL( $query = '', $query2 = false ) {
1542 global $wgInternalServer, $wgServer;
1543 $query = self
::fixUrlQueryArgs( $query, $query2 );
1544 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1545 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1546 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1551 * Get the URL for a canonical link, for use in things like IRC and
1552 * e-mail notifications. Uses $wgCanonicalServer and the
1553 * GetCanonicalURL hook.
1555 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1557 * See getLocalURL for the arguments.
1559 * @see self::getLocalURL
1560 * @return string The URL
1563 public function getCanonicalURL( $query = '', $query2 = false ) {
1564 $query = self
::fixUrlQueryArgs( $query, $query2 );
1565 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1566 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1571 * HTML-escaped version of getCanonicalURL()
1573 * See getLocalURL for the arguments.
1575 * @see self::getLocalURL
1579 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1580 wfDeprecated( __METHOD__
, '1.19' );
1581 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1585 * Get the edit URL for this Title
1587 * @return String the URL, or a null string if this is an
1590 public function getEditURL() {
1591 if ( $this->mInterwiki
!= '' ) {
1594 $s = $this->getLocalURL( 'action=edit' );
1600 * Is $wgUser watching this page?
1602 * @deprecated in 1.20; use User::isWatched() instead.
1605 public function userIsWatching() {
1608 if ( is_null( $this->mWatched
) ) {
1609 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1610 $this->mWatched
= false;
1612 $this->mWatched
= $wgUser->isWatched( $this );
1615 return $this->mWatched
;
1619 * Can $wgUser read this page?
1621 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1623 * @todo fold these checks into userCan()
1625 public function userCanRead() {
1626 wfDeprecated( __METHOD__
, '1.19' );
1627 return $this->userCan( 'read' );
1631 * Can $user perform $action on this page?
1632 * This skips potentially expensive cascading permission checks
1633 * as well as avoids expensive error formatting
1635 * Suitable for use for nonessential UI controls in common cases, but
1636 * _not_ for functional access control.
1638 * May provide false positives, but should never provide a false negative.
1640 * @param $action String action that permission needs to be checked for
1641 * @param $user User to check (since 1.19); $wgUser will be used if not
1645 public function quickUserCan( $action, $user = null ) {
1646 return $this->userCan( $action, $user, false );
1650 * Can $user perform $action on this page?
1652 * @param $action String action that permission needs to be checked for
1653 * @param $user User to check (since 1.19); $wgUser will be used if not
1655 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1656 * unnecessary queries.
1659 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1660 if ( !$user instanceof User
) {
1664 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1668 * Can $user perform $action on this page?
1670 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1672 * @param $action String action that permission needs to be checked for
1673 * @param $user User to check
1674 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1675 * queries by skipping checks for cascading protections and user blocks.
1676 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1677 * whose corresponding errors may be ignored.
1678 * @return Array of arguments to wfMessage to explain permissions problems.
1680 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1681 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1683 // Remove the errors being ignored.
1684 foreach ( $errors as $index => $error ) {
1685 $error_key = is_array( $error ) ?
$error[0] : $error;
1687 if ( in_array( $error_key, $ignoreErrors ) ) {
1688 unset( $errors[$index] );
1696 * Permissions checks that fail most often, and which are easiest to test.
1698 * @param $action String the action to check
1699 * @param $user User user to check
1700 * @param $errors Array list of current errors
1701 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1702 * @param $short Boolean short circuit on first error
1704 * @return Array list of errors
1706 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1707 if ( $action == 'create' ) {
1708 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1709 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1710 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1712 } elseif ( $action == 'move' ) {
1713 if ( !$user->isAllowed( 'move-rootuserpages' )
1714 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1715 // Show user page-specific message only if the user can move other pages
1716 $errors[] = array( 'cant-move-user-page' );
1719 // Check if user is allowed to move files if it's a file
1720 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1721 $errors[] = array( 'movenotallowedfile' );
1724 if ( !$user->isAllowed( 'move' ) ) {
1725 // User can't move anything
1726 global $wgGroupPermissions;
1727 $userCanMove = false;
1728 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1729 $userCanMove = $wgGroupPermissions['user']['move'];
1731 $autoconfirmedCanMove = false;
1732 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1733 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1735 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1736 // custom message if logged-in users without any special rights can move
1737 $errors[] = array( 'movenologintext' );
1739 $errors[] = array( 'movenotallowed' );
1742 } elseif ( $action == 'move-target' ) {
1743 if ( !$user->isAllowed( 'move' ) ) {
1744 // User can't move anything
1745 $errors[] = array( 'movenotallowed' );
1746 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1747 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1748 // Show user page-specific message only if the user can move other pages
1749 $errors[] = array( 'cant-move-to-user-page' );
1751 } elseif ( !$user->isAllowed( $action ) ) {
1752 $errors[] = $this->missingPermissionError( $action, $short );
1759 * Add the resulting error code to the errors array
1761 * @param $errors Array list of current errors
1762 * @param $result Mixed result of errors
1764 * @return Array list of errors
1766 private function resultToError( $errors, $result ) {
1767 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1768 // A single array representing an error
1769 $errors[] = $result;
1770 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1771 // A nested array representing multiple errors
1772 $errors = array_merge( $errors, $result );
1773 } elseif ( $result !== '' && is_string( $result ) ) {
1774 // A string representing a message-id
1775 $errors[] = array( $result );
1776 } elseif ( $result === false ) {
1777 // a generic "We don't want them to do that"
1778 $errors[] = array( 'badaccess-group0' );
1784 * Check various permission hooks
1786 * @param $action String the action to check
1787 * @param $user User user to check
1788 * @param $errors Array list of current errors
1789 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1790 * @param $short Boolean short circuit on first error
1792 * @return Array list of errors
1794 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1795 // Use getUserPermissionsErrors instead
1797 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1798 return $result ?
array() : array( array( 'badaccess-group0' ) );
1800 // Check getUserPermissionsErrors hook
1801 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1802 $errors = $this->resultToError( $errors, $result );
1804 // Check getUserPermissionsErrorsExpensive hook
1805 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1806 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1807 $errors = $this->resultToError( $errors, $result );
1814 * Check permissions on special pages & namespaces
1816 * @param $action String the action to check
1817 * @param $user User user to check
1818 * @param $errors Array list of current errors
1819 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1820 * @param $short Boolean short circuit on first error
1822 * @return Array list of errors
1824 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1825 # Only 'createaccount' and 'execute' can be performed on
1826 # special pages, which don't actually exist in the DB.
1827 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1828 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1829 $errors[] = array( 'ns-specialprotected' );
1832 # Check $wgNamespaceProtection for restricted namespaces
1833 if ( $this->isNamespaceProtected( $user ) ) {
1834 $ns = $this->mNamespace
== NS_MAIN ?
1835 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1836 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1837 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1844 * Check CSS/JS sub-page permissions
1846 * @param $action String the action to check
1847 * @param $user User user to check
1848 * @param $errors Array list of current errors
1849 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1850 * @param $short Boolean short circuit on first error
1852 * @return Array list of errors
1854 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1855 # Protect css/js subpages of user pages
1856 # XXX: this might be better using restrictions
1857 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1858 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1859 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1860 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1861 $errors[] = array( 'customcssprotected' );
1862 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1863 $errors[] = array( 'customjsprotected' );
1871 * Check against page_restrictions table requirements on this
1872 * page. The user must possess all required rights for this
1875 * @param $action String the action to check
1876 * @param $user User user to check
1877 * @param $errors Array list of current errors
1878 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1879 * @param $short Boolean short circuit on first error
1881 * @return Array list of errors
1883 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1884 foreach ( $this->getRestrictions( $action ) as $right ) {
1885 // Backwards compatibility, rewrite sysop -> protect
1886 if ( $right == 'sysop' ) {
1889 if ( $right != '' && !$user->isAllowed( $right ) ) {
1890 // Users with 'editprotected' permission can edit protected pages
1891 // without cascading option turned on.
1892 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1893 ||
$this->mCascadeRestriction
)
1895 $errors[] = array( 'protectedpagetext', $right );
1904 * Check restrictions on cascading pages.
1906 * @param $action String the action to check
1907 * @param $user User to check
1908 * @param $errors Array list of current errors
1909 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1910 * @param $short Boolean short circuit on first error
1912 * @return Array list of errors
1914 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1915 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1916 # We /could/ use the protection level on the source page, but it's
1917 # fairly ugly as we have to establish a precedence hierarchy for pages
1918 # included by multiple cascade-protected pages. So just restrict
1919 # it to people with 'protect' permission, as they could remove the
1920 # protection anyway.
1921 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1922 # Cascading protection depends on more than this page...
1923 # Several cascading protected pages may include this page...
1924 # Check each cascading level
1925 # This is only for protection restrictions, not for all actions
1926 if ( isset( $restrictions[$action] ) ) {
1927 foreach ( $restrictions[$action] as $right ) {
1928 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1929 if ( $right != '' && !$user->isAllowed( $right ) ) {
1931 foreach ( $cascadingSources as $page )
1932 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1933 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1943 * Check action permissions not already checked in checkQuickPermissions
1945 * @param $action String the action to check
1946 * @param $user User to check
1947 * @param $errors Array list of current errors
1948 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1949 * @param $short Boolean short circuit on first error
1951 * @return Array list of errors
1953 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1954 global $wgDeleteRevisionsLimit, $wgLang;
1956 if ( $action == 'protect' ) {
1957 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1958 // If they can't edit, they shouldn't protect.
1959 $errors[] = array( 'protect-cantedit' );
1961 } elseif ( $action == 'create' ) {
1962 $title_protection = $this->getTitleProtection();
1963 if( $title_protection ) {
1964 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1965 $title_protection['pt_create_perm'] = 'protect'; // B/C
1967 if( $title_protection['pt_create_perm'] == '' ||
1968 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1970 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1973 } elseif ( $action == 'move' ) {
1974 // Check for immobile pages
1975 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1976 // Specific message for this case
1977 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1978 } elseif ( !$this->isMovable() ) {
1979 // Less specific message for rarer cases
1980 $errors[] = array( 'immobile-source-page' );
1982 } elseif ( $action == 'move-target' ) {
1983 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1984 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1985 } elseif ( !$this->isMovable() ) {
1986 $errors[] = array( 'immobile-target-page' );
1988 } elseif ( $action == 'delete' ) {
1989 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1990 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1992 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1999 * Check that the user isn't blocked from editting.
2001 * @param $action String the action to check
2002 * @param $user User to check
2003 * @param $errors Array list of current errors
2004 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2005 * @param $short Boolean short circuit on first error
2007 * @return Array list of errors
2009 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2010 // Account creation blocks handled at userlogin.
2011 // Unblocking handled in SpecialUnblock
2012 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2016 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
2018 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2019 $errors[] = array( 'confirmedittext' );
2022 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2023 // Don't block the user from editing their own talk page unless they've been
2024 // explicitly blocked from that too.
2025 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2026 $block = $user->getBlock();
2028 // This is from OutputPage::blockedPage
2029 // Copied at r23888 by werdna
2031 $id = $user->blockedBy();
2032 $reason = $user->blockedFor();
2033 if ( $reason == '' ) {
2034 $reason = wfMessage( 'blockednoreason' )->text();
2036 $ip = $user->getRequest()->getIP();
2038 if ( is_numeric( $id ) ) {
2039 $name = User
::whoIs( $id );
2044 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
2045 $blockid = $block->getId();
2046 $blockExpiry = $block->getExpiry();
2047 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
2048 if ( $blockExpiry == 'infinity' ) {
2049 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2051 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2054 $intended = strval( $block->getTarget() );
2056 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2057 $blockid, $blockExpiry, $intended, $blockTimestamp );
2064 * Check that the user is allowed to read this page.
2066 * @param $action String the action to check
2067 * @param $user User to check
2068 * @param $errors Array list of current errors
2069 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2070 * @param $short Boolean short circuit on first error
2072 * @return Array list of errors
2074 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2075 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2076 static $useShortcut = null;
2078 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2079 if ( is_null( $useShortcut ) ) {
2080 $useShortcut = true;
2081 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2082 # Not a public wiki, so no shortcut
2083 $useShortcut = false;
2084 } elseif ( !empty( $wgRevokePermissions ) ) {
2086 * Iterate through each group with permissions being revoked (key not included since we don't care
2087 * what the group name is), then check if the read permission is being revoked. If it is, then
2088 * we don't use the shortcut below since the user might not be able to read, even though anon
2089 * reading is allowed.
2091 foreach ( $wgRevokePermissions as $perms ) {
2092 if ( !empty( $perms['read'] ) ) {
2093 # We might be removing the read right from the user, so no shortcut
2094 $useShortcut = false;
2101 $whitelisted = false;
2102 if ( $useShortcut ) {
2103 # Shortcut for public wikis, allows skipping quite a bit of code
2104 $whitelisted = true;
2105 } elseif ( $user->isAllowed( 'read' ) ) {
2106 # If the user is allowed to read pages, he is allowed to read all pages
2107 $whitelisted = true;
2108 } elseif ( $this->isSpecial( 'Userlogin' )
2109 ||
$this->isSpecial( 'ChangePassword' )
2110 ||
$this->isSpecial( 'PasswordReset' )
2112 # Always grant access to the login page.
2113 # Even anons need to be able to log in.
2114 $whitelisted = true;
2115 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2116 # Time to check the whitelist
2117 # Only do these checks is there's something to check against
2118 $name = $this->getPrefixedText();
2119 $dbName = $this->getPrefixedDBKey();
2121 // Check for explicit whitelisting with and without underscores
2122 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2123 $whitelisted = true;
2124 } elseif ( $this->getNamespace() == NS_MAIN
) {
2125 # Old settings might have the title prefixed with
2126 # a colon for main-namespace pages
2127 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2128 $whitelisted = true;
2130 } elseif ( $this->isSpecialPage() ) {
2131 # If it's a special page, ditch the subpage bit and check again
2132 $name = $this->getDBkey();
2133 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2134 if ( $name !== false ) {
2135 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2136 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2137 $whitelisted = true;
2143 if ( !$whitelisted ) {
2144 # If the title is not whitelisted, give extensions a chance to do so...
2145 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2146 if ( !$whitelisted ) {
2147 $errors[] = $this->missingPermissionError( $action, $short );
2155 * Get a description array when the user doesn't have the right to perform
2156 * $action (i.e. when User::isAllowed() returns false)
2158 * @param $action String the action to check
2159 * @param $short Boolean short circuit on first error
2160 * @return Array list of errors
2162 private function missingPermissionError( $action, $short ) {
2163 // We avoid expensive display logic for quickUserCan's and such
2165 return array( 'badaccess-group0' );
2168 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2169 User
::getGroupsWithPermission( $action ) );
2171 if ( count( $groups ) ) {
2175 $wgLang->commaList( $groups ),
2179 return array( 'badaccess-group0' );
2184 * Can $user perform $action on this page? This is an internal function,
2185 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2186 * checks on wfReadOnly() and blocks)
2188 * @param $action String action that permission needs to be checked for
2189 * @param $user User to check
2190 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2191 * @param $short Bool Set this to true to stop after the first permission error.
2192 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2194 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2195 wfProfileIn( __METHOD__
);
2197 # Read has special handling
2198 if ( $action == 'read' ) {
2200 'checkPermissionHooks',
2201 'checkReadPermissions',
2205 'checkQuickPermissions',
2206 'checkPermissionHooks',
2207 'checkSpecialsAndNSPermissions',
2208 'checkCSSandJSPermissions',
2209 'checkPageRestrictions',
2210 'checkCascadingSourcesRestrictions',
2211 'checkActionPermissions',
2217 while( count( $checks ) > 0 &&
2218 !( $short && count( $errors ) > 0 ) ) {
2219 $method = array_shift( $checks );
2220 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2223 wfProfileOut( __METHOD__
);
2228 * Protect css subpages of user pages: can $wgUser edit
2231 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2234 public function userCanEditCssSubpage() {
2236 wfDeprecated( __METHOD__
, '1.19' );
2237 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2238 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2242 * Protect js subpages of user pages: can $wgUser edit
2245 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2248 public function userCanEditJsSubpage() {
2250 wfDeprecated( __METHOD__
, '1.19' );
2251 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2252 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2256 * Get a filtered list of all restriction types supported by this wiki.
2257 * @param bool $exists True to get all restriction types that apply to
2258 * titles that do exist, False for all restriction types that apply to
2259 * titles that do not exist
2262 public static function getFilteredRestrictionTypes( $exists = true ) {
2263 global $wgRestrictionTypes;
2264 $types = $wgRestrictionTypes;
2266 # Remove the create restriction for existing titles
2267 $types = array_diff( $types, array( 'create' ) );
2269 # Only the create and upload restrictions apply to non-existing titles
2270 $types = array_intersect( $types, array( 'create', 'upload' ) );
2276 * Returns restriction types for the current Title
2278 * @return array applicable restriction types
2280 public function getRestrictionTypes() {
2281 if ( $this->isSpecialPage() ) {
2285 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2287 if ( $this->getNamespace() != NS_FILE
) {
2288 # Remove the upload restriction for non-file titles
2289 $types = array_diff( $types, array( 'upload' ) );
2292 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2294 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2295 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2301 * Is this title subject to title protection?
2302 * Title protection is the one applied against creation of such title.
2304 * @return Mixed An associative array representing any existent title
2305 * protection, or false if there's none.
2307 private function getTitleProtection() {
2308 // Can't protect pages in special namespaces
2309 if ( $this->getNamespace() < 0 ) {
2313 // Can't protect pages that exist.
2314 if ( $this->exists() ) {
2318 if ( !isset( $this->mTitleProtection
) ) {
2319 $dbr = wfGetDB( DB_SLAVE
);
2320 $res = $dbr->select( 'protected_titles', '*',
2321 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2324 // fetchRow returns false if there are no rows.
2325 $this->mTitleProtection
= $dbr->fetchRow( $res );
2327 return $this->mTitleProtection
;
2331 * Update the title protection status
2333 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2334 * @param $create_perm String Permission required for creation
2335 * @param $reason String Reason for protection
2336 * @param $expiry String Expiry timestamp
2337 * @return boolean true
2339 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2340 wfDeprecated( __METHOD__
, '1.19' );
2344 $limit = array( 'create' => $create_perm );
2345 $expiry = array( 'create' => $expiry );
2347 $page = WikiPage
::factory( $this );
2348 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2350 return $status->isOK();
2354 * Remove any title protection due to page existing
2356 public function deleteTitleProtection() {
2357 $dbw = wfGetDB( DB_MASTER
);
2361 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2364 $this->mTitleProtection
= false;
2368 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2370 * @param $action String Action to check (default: edit)
2373 public function isSemiProtected( $action = 'edit' ) {
2374 if ( $this->exists() ) {
2375 $restrictions = $this->getRestrictions( $action );
2376 if ( count( $restrictions ) > 0 ) {
2377 foreach ( $restrictions as $restriction ) {
2378 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2388 # If it doesn't exist, it can't be protected
2394 * Does the title correspond to a protected article?
2396 * @param $action String the action the page is protected from,
2397 * by default checks all actions.
2400 public function isProtected( $action = '' ) {
2401 global $wgRestrictionLevels;
2403 $restrictionTypes = $this->getRestrictionTypes();
2405 # Special pages have inherent protection
2406 if( $this->isSpecialPage() ) {
2410 # Check regular protection levels
2411 foreach ( $restrictionTypes as $type ) {
2412 if ( $action == $type ||
$action == '' ) {
2413 $r = $this->getRestrictions( $type );
2414 foreach ( $wgRestrictionLevels as $level ) {
2415 if ( in_array( $level, $r ) && $level != '' ) {
2426 * Determines if $user is unable to edit this page because it has been protected
2427 * by $wgNamespaceProtection.
2429 * @param $user User object to check permissions
2432 public function isNamespaceProtected( User
$user ) {
2433 global $wgNamespaceProtection;
2435 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2436 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2437 if ( $right != '' && !$user->isAllowed( $right ) ) {
2446 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2448 * @return Bool If the page is subject to cascading restrictions.
2450 public function isCascadeProtected() {
2451 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2452 return ( $sources > 0 );
2456 * Cascading protection: Get the source of any cascading restrictions on this page.
2458 * @param $getPages Bool Whether or not to retrieve the actual pages
2459 * that the restrictions have come from.
2460 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2461 * have come, false for none, or true if such restrictions exist, but $getPages
2462 * was not set. The restriction array is an array of each type, each of which
2463 * contains a array of unique groups.
2465 public function getCascadeProtectionSources( $getPages = true ) {
2467 $pagerestrictions = array();
2469 if ( isset( $this->mCascadeSources
) && $getPages ) {
2470 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2471 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2472 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2475 wfProfileIn( __METHOD__
);
2477 $dbr = wfGetDB( DB_SLAVE
);
2479 if ( $this->getNamespace() == NS_FILE
) {
2480 $tables = array( 'imagelinks', 'page_restrictions' );
2481 $where_clauses = array(
2482 'il_to' => $this->getDBkey(),
2487 $tables = array( 'templatelinks', 'page_restrictions' );
2488 $where_clauses = array(
2489 'tl_namespace' => $this->getNamespace(),
2490 'tl_title' => $this->getDBkey(),
2497 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2498 'pr_expiry', 'pr_type', 'pr_level' );
2499 $where_clauses[] = 'page_id=pr_page';
2502 $cols = array( 'pr_expiry' );
2505 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2507 $sources = $getPages ?
array() : false;
2508 $now = wfTimestampNow();
2509 $purgeExpired = false;
2511 foreach ( $res as $row ) {
2512 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2513 if ( $expiry > $now ) {
2515 $page_id = $row->pr_page
;
2516 $page_ns = $row->page_namespace
;
2517 $page_title = $row->page_title
;
2518 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2519 # Add groups needed for each restriction type if its not already there
2520 # Make sure this restriction type still exists
2522 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2523 $pagerestrictions[$row->pr_type
] = array();
2526 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2527 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2528 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2534 // Trigger lazy purge of expired restrictions from the db
2535 $purgeExpired = true;
2538 if ( $purgeExpired ) {
2539 Title
::purgeExpiredRestrictions();
2543 $this->mCascadeSources
= $sources;
2544 $this->mCascadingRestrictions
= $pagerestrictions;
2546 $this->mHasCascadingRestrictions
= $sources;
2549 wfProfileOut( __METHOD__
);
2550 return array( $sources, $pagerestrictions );
2554 * Accessor/initialisation for mRestrictions
2556 * @param $action String action that permission needs to be checked for
2557 * @return Array of Strings the array of groups allowed to edit this article
2559 public function getRestrictions( $action ) {
2560 if ( !$this->mRestrictionsLoaded
) {
2561 $this->loadRestrictions();
2563 return isset( $this->mRestrictions
[$action] )
2564 ?
$this->mRestrictions
[$action]
2569 * Get the expiry time for the restriction against a given action
2572 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2573 * or not protected at all, or false if the action is not recognised.
2575 public function getRestrictionExpiry( $action ) {
2576 if ( !$this->mRestrictionsLoaded
) {
2577 $this->loadRestrictions();
2579 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2583 * Returns cascading restrictions for the current article
2587 function areRestrictionsCascading() {
2588 if ( !$this->mRestrictionsLoaded
) {
2589 $this->loadRestrictions();
2592 return $this->mCascadeRestriction
;
2596 * Loads a string into mRestrictions array
2598 * @param $res Resource restrictions as an SQL result.
2599 * @param $oldFashionedRestrictions String comma-separated list of page
2600 * restrictions from page table (pre 1.10)
2602 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2605 foreach ( $res as $row ) {
2609 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2613 * Compiles list of active page restrictions from both page table (pre 1.10)
2614 * and page_restrictions table for this existing page.
2615 * Public for usage by LiquidThreads.
2617 * @param $rows array of db result objects
2618 * @param $oldFashionedRestrictions string comma-separated list of page
2619 * restrictions from page table (pre 1.10)
2621 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2623 $dbr = wfGetDB( DB_SLAVE
);
2625 $restrictionTypes = $this->getRestrictionTypes();
2627 foreach ( $restrictionTypes as $type ) {
2628 $this->mRestrictions
[$type] = array();
2629 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2632 $this->mCascadeRestriction
= false;
2634 # Backwards-compatibility: also load the restrictions from the page record (old format).
2636 if ( $oldFashionedRestrictions === null ) {
2637 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2638 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2641 if ( $oldFashionedRestrictions != '' ) {
2643 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2644 $temp = explode( '=', trim( $restrict ) );
2645 if ( count( $temp ) == 1 ) {
2646 // old old format should be treated as edit/move restriction
2647 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2648 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2650 $restriction = trim( $temp[1] );
2651 if( $restriction != '' ) { //some old entries are empty
2652 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2657 $this->mOldRestrictions
= true;
2661 if ( count( $rows ) ) {
2662 # Current system - load second to make them override.
2663 $now = wfTimestampNow();
2664 $purgeExpired = false;
2666 # Cycle through all the restrictions.
2667 foreach ( $rows as $row ) {
2669 // Don't take care of restrictions types that aren't allowed
2670 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2673 // This code should be refactored, now that it's being used more generally,
2674 // But I don't really see any harm in leaving it in Block for now -werdna
2675 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2677 // Only apply the restrictions if they haven't expired!
2678 if ( !$expiry ||
$expiry > $now ) {
2679 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2680 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2682 $this->mCascadeRestriction |
= $row->pr_cascade
;
2684 // Trigger a lazy purge of expired restrictions
2685 $purgeExpired = true;
2689 if ( $purgeExpired ) {
2690 Title
::purgeExpiredRestrictions();
2694 $this->mRestrictionsLoaded
= true;
2698 * Load restrictions from the page_restrictions table
2700 * @param $oldFashionedRestrictions String comma-separated list of page
2701 * restrictions from page table (pre 1.10)
2703 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2705 if ( !$this->mRestrictionsLoaded
) {
2706 if ( $this->exists() ) {
2707 $dbr = wfGetDB( DB_SLAVE
);
2709 $res = $dbr->select(
2710 'page_restrictions',
2712 array( 'pr_page' => $this->getArticleID() ),
2716 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2718 $title_protection = $this->getTitleProtection();
2720 if ( $title_protection ) {
2721 $now = wfTimestampNow();
2722 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2724 if ( !$expiry ||
$expiry > $now ) {
2725 // Apply the restrictions
2726 $this->mRestrictionsExpiry
['create'] = $expiry;
2727 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2728 } else { // Get rid of the old restrictions
2729 Title
::purgeExpiredRestrictions();
2730 $this->mTitleProtection
= false;
2733 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2735 $this->mRestrictionsLoaded
= true;
2741 * Flush the protection cache in this object and force reload from the database.
2742 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2744 public function flushRestrictions() {
2745 $this->mRestrictionsLoaded
= false;
2746 $this->mTitleProtection
= null;
2750 * Purge expired restrictions from the page_restrictions table
2752 static function purgeExpiredRestrictions() {
2753 $dbw = wfGetDB( DB_MASTER
);
2755 'page_restrictions',
2756 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2762 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2768 * Does this have subpages? (Warning, usually requires an extra DB query.)
2772 public function hasSubpages() {
2773 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2778 # We dynamically add a member variable for the purpose of this method
2779 # alone to cache the result. There's no point in having it hanging
2780 # around uninitialized in every Title object; therefore we only add it
2781 # if needed and don't declare it statically.
2782 if ( isset( $this->mHasSubpages
) ) {
2783 return $this->mHasSubpages
;
2786 $subpages = $this->getSubpages( 1 );
2787 if ( $subpages instanceof TitleArray
) {
2788 return $this->mHasSubpages
= (bool)$subpages->count();
2790 return $this->mHasSubpages
= false;
2794 * Get all subpages of this page.
2796 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2797 * @return mixed TitleArray, or empty array if this page's namespace
2798 * doesn't allow subpages
2800 public function getSubpages( $limit = -1 ) {
2801 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2805 $dbr = wfGetDB( DB_SLAVE
);
2806 $conds['page_namespace'] = $this->getNamespace();
2807 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2809 if ( $limit > -1 ) {
2810 $options['LIMIT'] = $limit;
2812 return $this->mSubpages
= TitleArray
::newFromResult(
2813 $dbr->select( 'page',
2814 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2823 * Is there a version of this page in the deletion archive?
2825 * @return Int the number of archived revisions
2827 public function isDeleted() {
2828 if ( $this->getNamespace() < 0 ) {
2831 $dbr = wfGetDB( DB_SLAVE
);
2833 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2834 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2837 if ( $this->getNamespace() == NS_FILE
) {
2838 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2839 array( 'fa_name' => $this->getDBkey() ),
2848 * Is there a version of this page in the deletion archive?
2852 public function isDeletedQuick() {
2853 if ( $this->getNamespace() < 0 ) {
2856 $dbr = wfGetDB( DB_SLAVE
);
2857 $deleted = (bool)$dbr->selectField( 'archive', '1',
2858 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2861 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2862 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2863 array( 'fa_name' => $this->getDBkey() ),
2871 * Get the article ID for this Title from the link cache,
2872 * adding it if necessary
2874 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2876 * @return Int the ID
2878 public function getArticleID( $flags = 0 ) {
2879 if ( $this->getNamespace() < 0 ) {
2880 return $this->mArticleID
= 0;
2882 $linkCache = LinkCache
::singleton();
2883 if ( $flags & self
::GAID_FOR_UPDATE
) {
2884 $oldUpdate = $linkCache->forUpdate( true );
2885 $linkCache->clearLink( $this );
2886 $this->mArticleID
= $linkCache->addLinkObj( $this );
2887 $linkCache->forUpdate( $oldUpdate );
2889 if ( -1 == $this->mArticleID
) {
2890 $this->mArticleID
= $linkCache->addLinkObj( $this );
2893 return $this->mArticleID
;
2897 * Is this an article that is a redirect page?
2898 * Uses link cache, adding it if necessary
2900 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2903 public function isRedirect( $flags = 0 ) {
2904 if ( !is_null( $this->mRedirect
) ) {
2905 return $this->mRedirect
;
2907 # Calling getArticleID() loads the field from cache as needed
2908 if ( !$this->getArticleID( $flags ) ) {
2909 return $this->mRedirect
= false;
2911 $linkCache = LinkCache
::singleton();
2912 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2914 return $this->mRedirect
;
2918 * What is the length of this page?
2919 * Uses link cache, adding it if necessary
2921 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2924 public function getLength( $flags = 0 ) {
2925 if ( $this->mLength
!= -1 ) {
2926 return $this->mLength
;
2928 # Calling getArticleID() loads the field from cache as needed
2929 if ( !$this->getArticleID( $flags ) ) {
2930 return $this->mLength
= 0;
2932 $linkCache = LinkCache
::singleton();
2933 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2935 return $this->mLength
;
2939 * What is the page_latest field for this page?
2941 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2942 * @return Int or 0 if the page doesn't exist
2944 public function getLatestRevID( $flags = 0 ) {
2945 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
2946 return intval( $this->mLatestID
);
2948 # Calling getArticleID() loads the field from cache as needed
2949 if ( !$this->getArticleID( $flags ) ) {
2950 return $this->mLatestID
= 0;
2952 $linkCache = LinkCache
::singleton();
2953 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2955 return $this->mLatestID
;
2959 * This clears some fields in this object, and clears any associated
2960 * keys in the "bad links" section of the link cache.
2962 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2963 * loading of the new page_id. It's also called from
2964 * WikiPage::doDeleteArticleReal()
2966 * @param $newid Int the new Article ID
2968 public function resetArticleID( $newid ) {
2969 $linkCache = LinkCache
::singleton();
2970 $linkCache->clearLink( $this );
2972 if ( $newid === false ) {
2973 $this->mArticleID
= -1;
2975 $this->mArticleID
= intval( $newid );
2977 $this->mRestrictionsLoaded
= false;
2978 $this->mRestrictions
= array();
2979 $this->mRedirect
= null;
2980 $this->mLength
= -1;
2981 $this->mLatestID
= false;
2982 $this->mEstimateRevisions
= null;
2986 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2988 * @param $text String containing title to capitalize
2989 * @param $ns int namespace index, defaults to NS_MAIN
2990 * @return String containing capitalized title
2992 public static function capitalize( $text, $ns = NS_MAIN
) {
2995 if ( MWNamespace
::isCapitalized( $ns ) ) {
2996 return $wgContLang->ucfirst( $text );
3003 * Secure and split - main initialisation function for this object
3005 * Assumes that mDbkeyform has been set, and is urldecoded
3006 * and uses underscores, but not otherwise munged. This function
3007 * removes illegal characters, splits off the interwiki and
3008 * namespace prefixes, sets the other forms, and canonicalizes
3011 * @return Bool true on success
3013 private function secureAndSplit() {
3014 global $wgContLang, $wgLocalInterwiki;
3017 $this->mInterwiki
= $this->mFragment
= '';
3018 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3020 $dbkey = $this->mDbkeyform
;
3022 # Strip Unicode bidi override characters.
3023 # Sometimes they slip into cut-n-pasted page titles, where the
3024 # override chars get included in list displays.
3025 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
3027 # Clean up whitespace
3028 # Note: use of the /u option on preg_replace here will cause
3029 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3030 # conveniently disabling them.
3031 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3032 $dbkey = trim( $dbkey, '_' );
3034 if ( $dbkey == '' ) {
3038 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3039 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3043 $this->mDbkeyform
= $dbkey;
3045 # Initial colon indicates main namespace rather than specified default
3046 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3047 if ( ':' == $dbkey[0] ) {
3048 $this->mNamespace
= NS_MAIN
;
3049 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3050 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3053 # Namespace or interwiki prefix
3055 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3058 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3060 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3061 # Ordinary namespace
3063 $this->mNamespace
= $ns;
3064 # For Talk:X pages, check if X has a "namespace" prefix
3065 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3066 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3067 # Disallow Talk:File:x type titles...
3069 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3070 # Disallow Talk:Interwiki:x type titles...
3074 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3075 if ( !$firstPass ) {
3076 # Can't make a local interwiki link to an interwiki link.
3077 # That's just crazy!
3083 $this->mInterwiki
= $wgContLang->lc( $p );
3085 # Redundant interwiki prefix to the local wiki
3086 if ( $wgLocalInterwiki !== false
3087 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3089 if ( $dbkey == '' ) {
3090 # Can't have an empty self-link
3093 $this->mInterwiki
= '';
3095 # Do another namespace split...
3099 # If there's an initial colon after the interwiki, that also
3100 # resets the default namespace
3101 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3102 $this->mNamespace
= NS_MAIN
;
3103 $dbkey = substr( $dbkey, 1 );
3106 # If there's no recognized interwiki or namespace,
3107 # then let the colon expression be part of the title.
3112 # We already know that some pages won't be in the database!
3113 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3114 $this->mArticleID
= 0;
3116 $fragment = strstr( $dbkey, '#' );
3117 if ( false !== $fragment ) {
3118 $this->setFragment( $fragment );
3119 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3120 # remove whitespace again: prevents "Foo_bar_#"
3121 # becoming "Foo_bar_"
3122 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3125 # Reject illegal characters.
3126 $rxTc = self
::getTitleInvalidRegex();
3127 if ( preg_match( $rxTc, $dbkey ) ) {
3131 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3132 # reachable due to the way web browsers deal with 'relative' URLs.
3133 # Also, they conflict with subpage syntax. Forbid them explicitly.
3134 if ( strpos( $dbkey, '.' ) !== false &&
3135 ( $dbkey === '.' ||
$dbkey === '..' ||
3136 strpos( $dbkey, './' ) === 0 ||
3137 strpos( $dbkey, '../' ) === 0 ||
3138 strpos( $dbkey, '/./' ) !== false ||
3139 strpos( $dbkey, '/../' ) !== false ||
3140 substr( $dbkey, -2 ) == '/.' ||
3141 substr( $dbkey, -3 ) == '/..' ) )
3146 # Magic tilde sequences? Nu-uh!
3147 if ( strpos( $dbkey, '~~~' ) !== false ) {
3151 # Limit the size of titles to 255 bytes. This is typically the size of the
3152 # underlying database field. We make an exception for special pages, which
3153 # don't need to be stored in the database, and may edge over 255 bytes due
3154 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3155 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3156 strlen( $dbkey ) > 512 )
3161 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3162 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3163 # other site might be case-sensitive.
3164 $this->mUserCaseDBKey
= $dbkey;
3165 if ( $this->mInterwiki
== '' ) {
3166 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3169 # Can't make a link to a namespace alone... "empty" local links can only be
3170 # self-links with a fragment identifier.
3171 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3175 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3176 // IP names are not allowed for accounts, and can only be referring to
3177 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3178 // there are numerous ways to present the same IP. Having sp:contribs scan
3179 // them all is silly and having some show the edits and others not is
3180 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3181 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3182 ? IP
::sanitizeIP( $dbkey )
3185 // Any remaining initial :s are illegal.
3186 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3191 $this->mDbkeyform
= $dbkey;
3192 $this->mUrlform
= wfUrlencode( $dbkey );
3194 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3200 * Get an array of Title objects linking to this Title
3201 * Also stores the IDs in the link cache.
3203 * WARNING: do not use this function on arbitrary user-supplied titles!
3204 * On heavily-used templates it will max out the memory.
3206 * @param $options Array: may be FOR UPDATE
3207 * @param $table String: table name
3208 * @param $prefix String: fields prefix
3209 * @return Array of Title objects linking here
3211 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3212 if ( count( $options ) > 0 ) {
3213 $db = wfGetDB( DB_MASTER
);
3215 $db = wfGetDB( DB_SLAVE
);
3219 array( 'page', $table ),
3220 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3222 "{$prefix}_from=page_id",
3223 "{$prefix}_namespace" => $this->getNamespace(),
3224 "{$prefix}_title" => $this->getDBkey() ),
3230 if ( $res->numRows() ) {
3231 $linkCache = LinkCache
::singleton();
3232 foreach ( $res as $row ) {
3233 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3235 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3236 $retVal[] = $titleObj;
3244 * Get an array of Title objects using this Title as a template
3245 * Also stores the IDs in the link cache.
3247 * WARNING: do not use this function on arbitrary user-supplied titles!
3248 * On heavily-used templates it will max out the memory.
3250 * @param $options Array: may be FOR UPDATE
3251 * @return Array of Title the Title objects linking here
3253 public function getTemplateLinksTo( $options = array() ) {
3254 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3258 * Get an array of Title objects linked from this Title
3259 * Also stores the IDs in the link cache.
3261 * WARNING: do not use this function on arbitrary user-supplied titles!
3262 * On heavily-used templates it will max out the memory.
3264 * @param $options Array: may be FOR UPDATE
3265 * @param $table String: table name
3266 * @param $prefix String: fields prefix
3267 * @return Array of Title objects linking here
3269 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3270 $id = $this->getArticleID();
3272 # If the page doesn't exist; there can't be any link from this page
3277 if ( count( $options ) > 0 ) {
3278 $db = wfGetDB( DB_MASTER
);
3280 $db = wfGetDB( DB_SLAVE
);
3283 $namespaceFiled = "{$prefix}_namespace";
3284 $titleField = "{$prefix}_title";
3287 array( $table, 'page' ),
3288 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3289 array( "{$prefix}_from" => $id ),
3292 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3296 if ( $res->numRows() ) {
3297 $linkCache = LinkCache
::singleton();
3298 foreach ( $res as $row ) {
3299 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3301 if ( $row->page_id
) {
3302 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3304 $linkCache->addBadLinkObj( $titleObj );
3306 $retVal[] = $titleObj;
3314 * Get an array of Title objects used on this Title as a template
3315 * Also stores the IDs in the link cache.
3317 * WARNING: do not use this function on arbitrary user-supplied titles!
3318 * On heavily-used templates it will max out the memory.
3320 * @param $options Array: may be FOR UPDATE
3321 * @return Array of Title the Title objects used here
3323 public function getTemplateLinksFrom( $options = array() ) {
3324 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3328 * Get an array of Title objects referring to non-existent articles linked from this page
3330 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3331 * @return Array of Title the Title objects
3333 public function getBrokenLinksFrom() {
3334 if ( $this->getArticleID() == 0 ) {
3335 # All links from article ID 0 are false positives
3339 $dbr = wfGetDB( DB_SLAVE
);
3340 $res = $dbr->select(
3341 array( 'page', 'pagelinks' ),
3342 array( 'pl_namespace', 'pl_title' ),
3344 'pl_from' => $this->getArticleID(),
3345 'page_namespace IS NULL'
3347 __METHOD__
, array(),
3351 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3357 foreach ( $res as $row ) {
3358 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3365 * Get a list of URLs to purge from the Squid cache when this
3368 * @return Array of String the URLs
3370 public function getSquidURLs() {
3372 $this->getInternalURL(),
3373 $this->getInternalURL( 'action=history' )
3376 $pageLang = $this->getPageLanguage();
3377 if ( $pageLang->hasVariants() ) {
3378 $variants = $pageLang->getVariants();
3379 foreach ( $variants as $vCode ) {
3380 $urls[] = $this->getInternalURL( '', $vCode );
3388 * Purge all applicable Squid URLs
3390 public function purgeSquid() {
3392 if ( $wgUseSquid ) {
3393 $urls = $this->getSquidURLs();
3394 $u = new SquidUpdate( $urls );
3400 * Move this page without authentication
3402 * @param $nt Title the new page Title
3403 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3405 public function moveNoAuth( &$nt ) {
3406 return $this->moveTo( $nt, false );
3410 * Check whether a given move operation would be valid.
3411 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3413 * @param $nt Title the new title
3414 * @param $auth Bool indicates whether $wgUser's permissions
3416 * @param $reason String is the log summary of the move, used for spam checking
3417 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3419 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3424 // Normally we'd add this to $errors, but we'll get
3425 // lots of syntax errors if $nt is not an object
3426 return array( array( 'badtitletext' ) );
3428 if ( $this->equals( $nt ) ) {
3429 $errors[] = array( 'selfmove' );
3431 if ( !$this->isMovable() ) {
3432 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3434 if ( $nt->getInterwiki() != '' ) {
3435 $errors[] = array( 'immobile-target-namespace-iw' );
3437 if ( !$nt->isMovable() ) {
3438 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3441 $oldid = $this->getArticleID();
3442 $newid = $nt->getArticleID();
3444 if ( strlen( $nt->getDBkey() ) < 1 ) {
3445 $errors[] = array( 'articleexists' );
3447 if ( ( $this->getDBkey() == '' ) ||
3449 ( $nt->getDBkey() == '' ) ) {
3450 $errors[] = array( 'badarticleerror' );
3453 // Image-specific checks
3454 if ( $this->getNamespace() == NS_FILE
) {
3455 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3458 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3459 $errors[] = array( 'nonfile-cannot-move-to-file' );
3463 $errors = wfMergeErrorArrays( $errors,
3464 $this->getUserPermissionsErrors( 'move', $wgUser ),
3465 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3466 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3467 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3470 $match = EditPage
::matchSummarySpamRegex( $reason );
3471 if ( $match !== false ) {
3472 // This is kind of lame, won't display nice
3473 $errors[] = array( 'spamprotectiontext' );
3477 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3478 $errors[] = array( 'hookaborted', $err );
3481 # The move is allowed only if (1) the target doesn't exist, or
3482 # (2) the target is a redirect to the source, and has no history
3483 # (so we can undo bad moves right after they're done).
3485 if ( 0 != $newid ) { # Target exists; check for validity
3486 if ( !$this->isValidMoveTarget( $nt ) ) {
3487 $errors[] = array( 'articleexists' );
3490 $tp = $nt->getTitleProtection();
3491 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3492 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3493 $errors[] = array( 'cantmove-titleprotected' );
3496 if ( empty( $errors ) ) {
3503 * Check if the requested move target is a valid file move target
3504 * @param Title $nt Target title
3505 * @return array List of errors
3507 protected function validateFileMoveOperation( $nt ) {
3512 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3514 $file = wfLocalFile( $this );
3515 if ( $file->exists() ) {
3516 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3517 $errors[] = array( 'imageinvalidfilename' );
3519 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3520 $errors[] = array( 'imagetypemismatch' );
3524 if ( $nt->getNamespace() != NS_FILE
) {
3525 $errors[] = array( 'imagenocrossnamespace' );
3526 // From here we want to do checks on a file object, so if we can't
3527 // create one, we must return.
3531 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3533 $destFile = wfLocalFile( $nt );
3534 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3535 $errors[] = array( 'file-exists-sharedrepo' );
3542 * Move a title to a new location
3544 * @param $nt Title the new title
3545 * @param $auth Bool indicates whether $wgUser's permissions
3547 * @param $reason String the reason for the move
3548 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3549 * Ignored if the user doesn't have the suppressredirect right.
3550 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3552 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3554 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3555 if ( is_array( $err ) ) {
3556 // Auto-block user's IP if the account was "hard" blocked
3557 $wgUser->spreadAnyEditBlock();
3560 // Check suppressredirect permission
3561 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3562 $createRedirect = true;
3565 // If it is a file, move it first.
3566 // It is done before all other moving stuff is done because it's hard to revert.
3567 $dbw = wfGetDB( DB_MASTER
);
3568 if ( $this->getNamespace() == NS_FILE
) {
3569 $file = wfLocalFile( $this );
3570 if ( $file->exists() ) {
3571 $status = $file->move( $nt );
3572 if ( !$status->isOk() ) {
3573 return $status->getErrorsArray();
3576 // Clear RepoGroup process cache
3577 RepoGroup
::singleton()->clearCache( $this );
3578 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3581 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3582 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3583 $protected = $this->isProtected();
3585 // Do the actual move
3586 $this->moveToInternal( $nt, $reason, $createRedirect );
3588 // Refresh the sortkey for this row. Be careful to avoid resetting
3589 // cl_timestamp, which may disturb time-based lists on some sites.
3590 $prefixes = $dbw->select(
3592 array( 'cl_sortkey_prefix', 'cl_to' ),
3593 array( 'cl_from' => $pageid ),
3596 foreach ( $prefixes as $prefixRow ) {
3597 $prefix = $prefixRow->cl_sortkey_prefix
;
3598 $catTo = $prefixRow->cl_to
;
3599 $dbw->update( 'categorylinks',
3601 'cl_sortkey' => Collation
::singleton()->getSortKey(
3602 $nt->getCategorySortkey( $prefix ) ),
3603 'cl_timestamp=cl_timestamp' ),
3605 'cl_from' => $pageid,
3606 'cl_to' => $catTo ),
3611 $redirid = $this->getArticleID();
3614 # Protect the redirect title as the title used to be...
3615 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3617 'pr_page' => $redirid,
3618 'pr_type' => 'pr_type',
3619 'pr_level' => 'pr_level',
3620 'pr_cascade' => 'pr_cascade',
3621 'pr_user' => 'pr_user',
3622 'pr_expiry' => 'pr_expiry'
3624 array( 'pr_page' => $pageid ),
3628 # Update the protection log
3629 $log = new LogPage( 'protect' );
3630 $comment = wfMessage(
3632 $this->getPrefixedText(),
3633 $nt->getPrefixedText()
3634 )->inContentLanguage()->text();
3636 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3638 // @todo FIXME: $params?
3639 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3643 $oldnamespace = $this->getNamespace() & ~
1;
3644 $newnamespace = $nt->getNamespace() & ~
1;
3645 $oldtitle = $this->getDBkey();
3646 $newtitle = $nt->getDBkey();
3648 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3649 WatchedItem
::duplicateEntries( $this, $nt );
3652 $dbw->commit( __METHOD__
);
3654 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3659 * Move page to a title which is either a redirect to the
3660 * source page or nonexistent
3662 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3663 * @param $reason String The reason for the move
3664 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3665 * if the user has the suppressredirect right
3666 * @throws MWException
3668 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3669 global $wgUser, $wgContLang;
3671 if ( $nt->exists() ) {
3672 $moveOverRedirect = true;
3673 $logType = 'move_redir';
3675 $moveOverRedirect = false;
3679 $redirectSuppressed = !$createRedirect;
3681 $logEntry = new ManualLogEntry( 'move', $logType );
3682 $logEntry->setPerformer( $wgUser );
3683 $logEntry->setTarget( $this );
3684 $logEntry->setComment( $reason );
3685 $logEntry->setParameters( array(
3686 '4::target' => $nt->getPrefixedText(),
3687 '5::noredir' => $redirectSuppressed ?
'1': '0',
3690 $formatter = LogFormatter
::newFromEntry( $logEntry );
3691 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3692 $comment = $formatter->getPlainActionText();
3694 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3696 # Truncate for whole multibyte characters.
3697 $comment = $wgContLang->truncate( $comment, 255 );
3699 $oldid = $this->getArticleID();
3701 $dbw = wfGetDB( DB_MASTER
);
3703 $newpage = WikiPage
::factory( $nt );
3705 if ( $moveOverRedirect ) {
3706 $newid = $nt->getArticleID();
3708 # Delete the old redirect. We don't save it to history since
3709 # by definition if we've got here it's rather uninteresting.
3710 # We have to remove it so that the next step doesn't trigger
3711 # a conflict on the unique namespace+title index...
3712 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3714 $newpage->doDeleteUpdates( $newid );
3717 # Save a null revision in the page's history notifying of the move
3718 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3719 if ( !is_object( $nullRevision ) ) {
3720 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3722 $nullRevId = $nullRevision->insertOn( $dbw );
3724 # Change the name of the target page:
3725 $dbw->update( 'page',
3727 'page_namespace' => $nt->getNamespace(),
3728 'page_title' => $nt->getDBkey(),
3730 /* WHERE */ array( 'page_id' => $oldid ),
3734 $this->resetArticleID( 0 );
3735 $nt->resetArticleID( $oldid );
3737 $newpage->updateRevisionOn( $dbw, $nullRevision );
3739 wfRunHooks( 'NewRevisionFromEditComplete',
3740 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3742 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3744 if ( !$moveOverRedirect ) {
3745 WikiPage
::onArticleCreate( $nt );
3748 # Recreate the redirect, this time in the other direction.
3749 if ( $redirectSuppressed ) {
3750 WikiPage
::onArticleDelete( $this );
3752 $mwRedir = MagicWord
::get( 'redirect' );
3753 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3754 $redirectArticle = WikiPage
::factory( $this );
3755 $newid = $redirectArticle->insertOn( $dbw );
3756 if ( $newid ) { // sanity
3757 $redirectRevision = new Revision( array(
3759 'comment' => $comment,
3760 'text' => $redirectText ) );
3761 $redirectRevision->insertOn( $dbw );
3762 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3764 wfRunHooks( 'NewRevisionFromEditComplete',
3765 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3767 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3772 $logid = $logEntry->insert();
3773 $logEntry->publish( $logid );
3777 * Move this page's subpages to be subpages of $nt
3779 * @param $nt Title Move target
3780 * @param $auth bool Whether $wgUser's permissions should be checked
3781 * @param $reason string The reason for the move
3782 * @param $createRedirect bool Whether to create redirects from the old subpages to
3783 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3784 * @return mixed array with old page titles as keys, and strings (new page titles) or
3785 * arrays (errors) as values, or an error array with numeric indices if no pages
3788 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3789 global $wgMaximumMovedPages;
3790 // Check permissions
3791 if ( !$this->userCan( 'move-subpages' ) ) {
3792 return array( 'cant-move-subpages' );
3794 // Do the source and target namespaces support subpages?
3795 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3796 return array( 'namespace-nosubpages',
3797 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3799 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3800 return array( 'namespace-nosubpages',
3801 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3804 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3807 foreach ( $subpages as $oldSubpage ) {
3809 if ( $count > $wgMaximumMovedPages ) {
3810 $retval[$oldSubpage->getPrefixedTitle()] =
3811 array( 'movepage-max-pages',
3812 $wgMaximumMovedPages );
3816 // We don't know whether this function was called before
3817 // or after moving the root page, so check both
3819 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3820 $oldSubpage->getArticleID() == $nt->getArticleID() )
3822 // When moving a page to a subpage of itself,
3823 // don't move it twice
3826 $newPageName = preg_replace(
3827 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3828 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3829 $oldSubpage->getDBkey() );
3830 if ( $oldSubpage->isTalkPage() ) {
3831 $newNs = $nt->getTalkPage()->getNamespace();
3833 $newNs = $nt->getSubjectPage()->getNamespace();
3835 # Bug 14385: we need makeTitleSafe because the new page names may
3836 # be longer than 255 characters.
3837 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3839 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3840 if ( $success === true ) {
3841 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3843 $retval[$oldSubpage->getPrefixedText()] = $success;
3850 * Checks if this page is just a one-rev redirect.
3851 * Adds lock, so don't use just for light purposes.
3855 public function isSingleRevRedirect() {
3856 $dbw = wfGetDB( DB_MASTER
);
3858 $row = $dbw->selectRow( 'page',
3859 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3862 array( 'FOR UPDATE' )
3864 # Cache some fields we may want
3865 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3866 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3867 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3868 if ( !$this->mRedirect
) {
3871 # Does the article have a history?
3872 $row = $dbw->selectField( array( 'page', 'revision' ),
3874 array( 'page_namespace' => $this->getNamespace(),
3875 'page_title' => $this->getDBkey(),
3877 'page_latest != rev_id'
3880 array( 'FOR UPDATE' )
3882 # Return true if there was no history
3883 return ( $row === false );
3887 * Checks if $this can be moved to a given Title
3888 * - Selects for update, so don't call it unless you mean business
3890 * @param $nt Title the new title to check
3893 public function isValidMoveTarget( $nt ) {
3894 # Is it an existing file?
3895 if ( $nt->getNamespace() == NS_FILE
) {
3896 $file = wfLocalFile( $nt );
3897 if ( $file->exists() ) {
3898 wfDebug( __METHOD__
. ": file exists\n" );
3902 # Is it a redirect with no history?
3903 if ( !$nt->isSingleRevRedirect() ) {
3904 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3907 # Get the article text
3908 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3909 if( !is_object( $rev ) ){
3912 $text = $rev->getText();
3913 # Does the redirect point to the source?
3914 # Or is it a broken self-redirect, usually caused by namespace collisions?
3916 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3917 $redirTitle = Title
::newFromText( $m[1] );
3918 if ( !is_object( $redirTitle ) ||
3919 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3920 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3921 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3926 wfDebug( __METHOD__
. ": failsafe\n" );
3933 * Get categories to which this Title belongs and return an array of
3934 * categories' names.
3936 * @return Array of parents in the form:
3937 * $parent => $currentarticle
3939 public function getParentCategories() {
3944 $titleKey = $this->getArticleID();
3946 if ( $titleKey === 0 ) {
3950 $dbr = wfGetDB( DB_SLAVE
);
3952 $res = $dbr->select( 'categorylinks', '*',
3954 'cl_from' => $titleKey,
3960 if ( $dbr->numRows( $res ) > 0 ) {
3961 foreach ( $res as $row ) {
3962 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3963 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3970 * Get a tree of parent categories
3972 * @param $children Array with the children in the keys, to check for circular refs
3973 * @return Array Tree of parent categories
3975 public function getParentCategoryTree( $children = array() ) {
3977 $parents = $this->getParentCategories();
3980 foreach ( $parents as $parent => $current ) {
3981 if ( array_key_exists( $parent, $children ) ) {
3982 # Circular reference
3983 $stack[$parent] = array();
3985 $nt = Title
::newFromText( $parent );
3987 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3997 * Get an associative array for selecting this title from
4000 * @return Array suitable for the $where parameter of DB::select()
4002 public function pageCond() {
4003 if ( $this->mArticleID
> 0 ) {
4004 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4005 return array( 'page_id' => $this->mArticleID
);
4007 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4012 * Get the revision ID of the previous revision
4014 * @param $revId Int Revision ID. Get the revision that was before this one.
4015 * @param $flags Int Title::GAID_FOR_UPDATE
4016 * @return Int|Bool Old revision ID, or FALSE if none exists
4018 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4019 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4020 $revId = $db->selectField( 'revision', 'rev_id',
4022 'rev_page' => $this->getArticleID( $flags ),
4023 'rev_id < ' . intval( $revId )
4026 array( 'ORDER BY' => 'rev_id DESC' )
4029 if ( $revId === false ) {
4032 return intval( $revId );
4037 * Get the revision ID of the next revision
4039 * @param $revId Int Revision ID. Get the revision that was after this one.
4040 * @param $flags Int Title::GAID_FOR_UPDATE
4041 * @return Int|Bool Next revision ID, or FALSE if none exists
4043 public function getNextRevisionID( $revId, $flags = 0 ) {
4044 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4045 $revId = $db->selectField( 'revision', 'rev_id',
4047 'rev_page' => $this->getArticleID( $flags ),
4048 'rev_id > ' . intval( $revId )
4051 array( 'ORDER BY' => 'rev_id' )
4054 if ( $revId === false ) {
4057 return intval( $revId );
4062 * Get the first revision of the page
4064 * @param $flags Int Title::GAID_FOR_UPDATE
4065 * @return Revision|Null if page doesn't exist
4067 public function getFirstRevision( $flags = 0 ) {
4068 $pageId = $this->getArticleID( $flags );
4070 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4071 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4072 array( 'rev_page' => $pageId ),
4074 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4077 return new Revision( $row );
4084 * Get the oldest revision timestamp of this page
4086 * @param $flags Int Title::GAID_FOR_UPDATE
4087 * @return String: MW timestamp
4089 public function getEarliestRevTime( $flags = 0 ) {
4090 $rev = $this->getFirstRevision( $flags );
4091 return $rev ?
$rev->getTimestamp() : null;
4095 * Check if this is a new page
4099 public function isNewPage() {
4100 $dbr = wfGetDB( DB_SLAVE
);
4101 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4105 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4109 public function isBigDeletion() {
4110 global $wgDeleteRevisionsLimit;
4112 if ( !$wgDeleteRevisionsLimit ) {
4116 $revCount = $this->estimateRevisionCount();
4117 return $revCount > $wgDeleteRevisionsLimit;
4121 * Get the approximate revision count of this page.
4125 public function estimateRevisionCount() {
4126 if ( !$this->exists() ) {
4130 if ( $this->mEstimateRevisions
=== null ) {
4131 $dbr = wfGetDB( DB_SLAVE
);
4132 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4133 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4136 return $this->mEstimateRevisions
;
4140 * Get the number of revisions between the given revision.
4141 * Used for diffs and other things that really need it.
4143 * @param $old int|Revision Old revision or rev ID (first before range)
4144 * @param $new int|Revision New revision or rev ID (first after range)
4145 * @return Int Number of revisions between these revisions.
4147 public function countRevisionsBetween( $old, $new ) {
4148 if ( !( $old instanceof Revision
) ) {
4149 $old = Revision
::newFromTitle( $this, (int)$old );
4151 if ( !( $new instanceof Revision
) ) {
4152 $new = Revision
::newFromTitle( $this, (int)$new );
4154 if ( !$old ||
!$new ) {
4155 return 0; // nothing to compare
4157 $dbr = wfGetDB( DB_SLAVE
);
4158 return (int)$dbr->selectField( 'revision', 'count(*)',
4160 'rev_page' => $this->getArticleID(),
4161 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4162 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4169 * Get the number of authors between the given revisions or revision IDs.
4170 * Used for diffs and other things that really need it.
4172 * @param $old int|Revision Old revision or rev ID (first before range by default)
4173 * @param $new int|Revision New revision or rev ID (first after range by default)
4174 * @param $limit int Maximum number of authors
4175 * @param $options string|array (Optional): Single option, or an array of options:
4176 * 'include_old' Include $old in the range; $new is excluded.
4177 * 'include_new' Include $new in the range; $old is excluded.
4178 * 'include_both' Include both $old and $new in the range.
4179 * Unknown option values are ignored.
4180 * @return int Number of revision authors in the range; zero if not both revisions exist
4182 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4183 if ( !( $old instanceof Revision
) ) {
4184 $old = Revision
::newFromTitle( $this, (int)$old );
4186 if ( !( $new instanceof Revision
) ) {
4187 $new = Revision
::newFromTitle( $this, (int)$new );
4189 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4190 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4191 // in the sanity check below?
4192 if ( !$old ||
!$new ) {
4193 return 0; // nothing to compare
4197 $options = (array) $options;
4198 if ( in_array( 'include_old', $options ) ) {
4201 if ( in_array( 'include_new', $options ) ) {
4204 if ( in_array( 'include_both', $options ) ) {
4208 // No DB query needed if $old and $new are the same or successive revisions:
4209 if ( $old->getId() === $new->getId() ) {
4210 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4211 } else if ( $old->getId() === $new->getParentId() ) {
4212 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4213 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4215 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4217 $dbr = wfGetDB( DB_SLAVE
);
4218 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4220 'rev_page' => $this->getArticleID(),
4221 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4222 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4224 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4226 return (int)$dbr->numRows( $res );
4230 * Compare with another title.
4232 * @param $title Title
4235 public function equals( Title
$title ) {
4236 // Note: === is necessary for proper matching of number-like titles.
4237 return $this->getInterwiki() === $title->getInterwiki()
4238 && $this->getNamespace() == $title->getNamespace()
4239 && $this->getDBkey() === $title->getDBkey();
4243 * Check if this title is a subpage of another title
4245 * @param $title Title
4248 public function isSubpageOf( Title
$title ) {
4249 return $this->getInterwiki() === $title->getInterwiki()
4250 && $this->getNamespace() == $title->getNamespace()
4251 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4255 * Check if page exists. For historical reasons, this function simply
4256 * checks for the existence of the title in the page table, and will
4257 * thus return false for interwiki links, special pages and the like.
4258 * If you want to know if a title can be meaningfully viewed, you should
4259 * probably call the isKnown() method instead.
4263 public function exists() {
4264 return $this->getArticleID() != 0;
4268 * Should links to this title be shown as potentially viewable (i.e. as
4269 * "bluelinks"), even if there's no record by this title in the page
4272 * This function is semi-deprecated for public use, as well as somewhat
4273 * misleadingly named. You probably just want to call isKnown(), which
4274 * calls this function internally.
4276 * (ISSUE: Most of these checks are cheap, but the file existence check
4277 * can potentially be quite expensive. Including it here fixes a lot of
4278 * existing code, but we might want to add an optional parameter to skip
4279 * it and any other expensive checks.)
4283 public function isAlwaysKnown() {
4287 * Allows overriding default behaviour for determining if a page exists.
4288 * If $isKnown is kept as null, regular checks happen. If it's
4289 * a boolean, this value is returned by the isKnown method.
4293 * @param Title $title
4294 * @param boolean|null $isKnown
4296 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4298 if ( !is_null( $isKnown ) ) {
4302 if ( $this->mInterwiki
!= '' ) {
4303 return true; // any interwiki link might be viewable, for all we know
4306 switch( $this->mNamespace
) {
4309 // file exists, possibly in a foreign repo
4310 return (bool)wfFindFile( $this );
4312 // valid special page
4313 return SpecialPageFactory
::exists( $this->getDBkey() );
4315 // selflink, possibly with fragment
4316 return $this->mDbkeyform
== '';
4318 // known system message
4319 return $this->hasSourceText() !== false;
4326 * Does this title refer to a page that can (or might) be meaningfully
4327 * viewed? In particular, this function may be used to determine if
4328 * links to the title should be rendered as "bluelinks" (as opposed to
4329 * "redlinks" to non-existent pages).
4330 * Adding something else to this function will cause inconsistency
4331 * since LinkHolderArray calls isAlwaysKnown() and does its own
4332 * page existence check.
4336 public function isKnown() {
4337 return $this->isAlwaysKnown() ||
$this->exists();
4341 * Does this page have source text?
4345 public function hasSourceText() {
4346 if ( $this->exists() ) {
4350 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4351 // If the page doesn't exist but is a known system message, default
4352 // message content will be displayed, same for language subpages-
4353 // Use always content language to avoid loading hundreds of languages
4354 // to get the link color.
4356 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4357 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4358 return $message->exists();
4365 * Get the default message text or false if the message doesn't exist
4367 * @return String or false
4369 public function getDefaultMessageText() {
4372 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4376 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4377 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4379 if ( $message->exists() ) {
4380 return $message->plain();
4387 * Updates page_touched for this page; called from LinksUpdate.php
4389 * @return Bool true if the update succeded
4391 public function invalidateCache() {
4392 if ( wfReadOnly() ) {
4395 $dbw = wfGetDB( DB_MASTER
);
4396 $success = $dbw->update(
4398 array( 'page_touched' => $dbw->timestamp() ),
4402 HTMLFileCache
::clearFileCache( $this );
4407 * Update page_touched timestamps and send squid purge messages for
4408 * pages linking to this title. May be sent to the job queue depending
4409 * on the number of links. Typically called on create and delete.
4411 public function touchLinks() {
4412 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4415 if ( $this->getNamespace() == NS_CATEGORY
) {
4416 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4422 * Get the last touched timestamp
4424 * @param $db DatabaseBase: optional db
4425 * @return String last-touched timestamp
4427 public function getTouched( $db = null ) {
4428 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4429 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4434 * Get the timestamp when this page was updated since the user last saw it.
4437 * @return String|Null
4439 public function getNotificationTimestamp( $user = null ) {
4440 global $wgUser, $wgShowUpdatedMarker;
4441 // Assume current user if none given
4445 // Check cache first
4446 $uid = $user->getId();
4447 // avoid isset here, as it'll return false for null entries
4448 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4449 return $this->mNotificationTimestamp
[$uid];
4451 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4452 return $this->mNotificationTimestamp
[$uid] = false;
4454 // Don't cache too much!
4455 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4456 $this->mNotificationTimestamp
= array();
4458 $dbr = wfGetDB( DB_SLAVE
);
4459 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4460 'wl_notificationtimestamp',
4462 'wl_user' => $user->getId(),
4463 'wl_namespace' => $this->getNamespace(),
4464 'wl_title' => $this->getDBkey(),
4468 return $this->mNotificationTimestamp
[$uid];
4472 * Generate strings used for xml 'id' names in monobook tabs
4474 * @param $prepend string defaults to 'nstab-'
4475 * @return String XML 'id' name
4477 public function getNamespaceKey( $prepend = 'nstab-' ) {
4479 // Gets the subject namespace if this title
4480 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4481 // Checks if cononical namespace name exists for namespace
4482 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4483 // Uses canonical namespace name
4484 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4486 // Uses text of namespace
4487 $namespaceKey = $this->getSubjectNsText();
4489 // Makes namespace key lowercase
4490 $namespaceKey = $wgContLang->lc( $namespaceKey );
4492 if ( $namespaceKey == '' ) {
4493 $namespaceKey = 'main';
4495 // Changes file to image for backwards compatibility
4496 if ( $namespaceKey == 'file' ) {
4497 $namespaceKey = 'image';
4499 return $prepend . $namespaceKey;
4503 * Get all extant redirects to this Title
4505 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4506 * @return Array of Title redirects to this title
4508 public function getRedirectsHere( $ns = null ) {
4511 $dbr = wfGetDB( DB_SLAVE
);
4513 'rd_namespace' => $this->getNamespace(),
4514 'rd_title' => $this->getDBkey(),
4517 if ( $this->isExternal() ) {
4518 $where['rd_interwiki'] = $this->getInterwiki();
4520 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4522 if ( !is_null( $ns ) ) {
4523 $where['page_namespace'] = $ns;
4526 $res = $dbr->select(
4527 array( 'redirect', 'page' ),
4528 array( 'page_namespace', 'page_title' ),
4533 foreach ( $res as $row ) {
4534 $redirs[] = self
::newFromRow( $row );
4540 * Check if this Title is a valid redirect target
4544 public function isValidRedirectTarget() {
4545 global $wgInvalidRedirectTargets;
4547 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4548 if ( $this->isSpecial( 'Userlogout' ) ) {
4552 foreach ( $wgInvalidRedirectTargets as $target ) {
4553 if ( $this->isSpecial( $target ) ) {
4562 * Get a backlink cache object
4564 * @return BacklinkCache
4566 public function getBacklinkCache() {
4567 return BacklinkCache
::get( $this );
4571 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4575 public function canUseNoindex() {
4576 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4578 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4579 ?
$wgContentNamespaces
4580 : $wgExemptFromUserRobotsControl;
4582 return !in_array( $this->mNamespace
, $bannedNamespaces );
4587 * Returns the raw sort key to be used for categories, with the specified
4588 * prefix. This will be fed to Collation::getSortKey() to get a
4589 * binary sortkey that can be used for actual sorting.
4591 * @param $prefix string The prefix to be used, specified using
4592 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4596 public function getCategorySortkey( $prefix = '' ) {
4597 $unprefixed = $this->getText();
4599 // Anything that uses this hook should only depend
4600 // on the Title object passed in, and should probably
4601 // tell the users to run updateCollations.php --force
4602 // in order to re-sort existing category relations.
4603 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4604 if ( $prefix !== '' ) {
4605 # Separate with a line feed, so the unprefixed part is only used as
4606 # a tiebreaker when two pages have the exact same prefix.
4607 # In UCA, tab is the only character that can sort above LF
4608 # so we strip both of them from the original prefix.
4609 $prefix = strtr( $prefix, "\n\t", ' ' );
4610 return "$prefix\n$unprefixed";
4616 * Get the language in which the content of this page is written in
4617 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4618 * e.g. $wgLang (such as special pages, which are in the user language).
4623 public function getPageLanguage() {
4625 if ( $this->isSpecialPage() ) {
4626 // special pages are in the user language
4628 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4629 // css/js should always be LTR and is, in fact, English
4630 return wfGetLangObj( 'en' );
4631 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4632 // Parse mediawiki messages with correct target language
4633 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4634 return wfGetLangObj( $lang );
4637 // If nothing special, it should be in the wiki content language
4638 $pageLang = $wgContLang;
4639 // Hook at the end because we don't want to override the above stuff
4640 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4641 return wfGetLangObj( $pageLang );
4645 * Get the language in which the content of this page is written when
4646 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4647 * e.g. $wgLang (such as special pages, which are in the user language).
4652 public function getPageViewLanguage() {
4653 $pageLang = $this->getPageLanguage();
4654 // If this is nothing special (so the content is converted when viewed)
4655 if ( !$this->isSpecialPage()
4656 && !$this->isCssOrJsPage() && !$this->isCssJsSubpage()
4657 && $this->getNamespace() !== NS_MEDIAWIKI
4659 // If the user chooses a variant, the content is actually
4660 // in a language whose code is the variant code.
4661 $variant = $pageLang->getPreferredVariant();
4662 if ( $pageLang->getCode() !== $variant ) {
4663 $pageLang = Language
::factory( $variant );