5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
92 /*protected*/ function __construct() { }
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
104 $t->mDbkeyform
= $key;
105 if ( $t->secureAndSplit() ) {
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
138 return Title
::$titleCache[$text];
141 # Convert things like é ā or 〗 into normalized (bug 14952) text
142 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
145 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace
= $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN
) {
151 if ( $cachedcount >= self
::CACHE_MAX
) {
152 # Avoid memory leaks on mass operations...
153 Title
::$titleCache = array();
157 Title
::$titleCache[$text] =& $t;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform
= str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
210 if ( $row !== false ) {
211 $title = Title
::newFromRow( $row );
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
228 $dbr = wfGetDB( DB_SLAVE
);
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
241 foreach ( $res as $row ) {
242 $titles[] = Title
::newFromRow( $row );
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
255 $t->loadFromRow( $row );
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|bool database row
266 public function loadFromRow( $row ) {
267 if ( $row ) { // page found
268 if ( isset( $row->page_id
) )
269 $this->mArticleID
= (int)$row->page_id
;
270 if ( isset( $row->page_len
) )
271 $this->mLength
= (int)$row->page_len
;
272 if ( isset( $row->page_is_redirect
) )
273 $this->mRedirect
= (bool)$row->page_is_redirect
;
274 if ( isset( $row->page_latest
) )
275 $this->mLatestID
= (int)$row->page_latest
;
276 } else { // page not found
277 $this->mArticleID
= 0;
279 $this->mRedirect
= false;
280 $this->mLatestID
= 0;
285 * Create a new Title from a namespace index and a DB key.
286 * It's assumed that $ns and $title are *valid*, for instance when
287 * they came directly from the database or a special page name.
288 * For convenience, spaces are converted to underscores so that
289 * eg user_text fields can be used directly.
291 * @param $ns Int the namespace of the article
292 * @param $title String the unprefixed database key form
293 * @param $fragment String the link fragment (after the "#")
294 * @param $interwiki String the interwiki prefix
295 * @return Title the new object
297 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
299 $t->mInterwiki
= $interwiki;
300 $t->mFragment
= $fragment;
301 $t->mNamespace
= $ns = intval( $ns );
302 $t->mDbkeyform
= str_replace( ' ', '_', $title );
303 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
304 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
305 $t->mTextform
= str_replace( '_', ' ', $title );
310 * Create a new Title from a namespace index and a DB key.
311 * The parameters will be checked for validity, which is a bit slower
312 * than makeTitle() but safer for user-provided data.
314 * @param $ns Int the namespace of the article
315 * @param $title String database key form
316 * @param $fragment String the link fragment (after the "#")
317 * @param $interwiki String interwiki prefix
318 * @return Title the new object, or NULL on an error
320 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
322 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
323 if ( $t->secureAndSplit() ) {
331 * Create a new Title for the Main Page
333 * @return Title the new object
335 public static function newMainPage() {
336 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
337 // Don't give fatal errors if the message is broken
339 $title = Title
::newFromText( 'Main Page' );
345 * Extract a redirect destination from a string and return the
346 * Title, or null if the text doesn't contain a valid redirect
347 * This will only return the very next target, useful for
348 * the redirect table and other checks that don't need full recursion
350 * @param $text String: Text with possible redirect
351 * @return Title: The corresponding Title
353 public static function newFromRedirect( $text ) {
354 return self
::newFromRedirectInternal( $text );
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 recurse down $wgMaxRedirects times or until a non-redirect target is hit
361 * in order to provide (hopefully) the Title of the final destination instead of another redirect
363 * @param $text String Text with possible redirect
366 public static function newFromRedirectRecurse( $text ) {
367 $titles = self
::newFromRedirectArray( $text );
368 return $titles ?
array_pop( $titles ) : null;
372 * Extract a redirect destination from a string and return an
373 * array of Titles, or null if the text doesn't contain a valid redirect
374 * The last element in the array is the final destination after all redirects
375 * have been resolved (up to $wgMaxRedirects times)
377 * @param $text String Text with possible redirect
378 * @return Array of Titles, with the destination last
380 public static function newFromRedirectArray( $text ) {
381 global $wgMaxRedirects;
382 $title = self
::newFromRedirectInternal( $text );
383 if ( is_null( $title ) ) {
386 // recursive check to follow double redirects
387 $recurse = $wgMaxRedirects;
388 $titles = array( $title );
389 while ( --$recurse > 0 ) {
390 if ( $title->isRedirect() ) {
391 $page = WikiPage
::factory( $title );
392 $newtitle = $page->getRedirectTarget();
396 // Redirects to some special pages are not permitted
397 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
398 // the new title passes the checks, so make that our current title so that further recursion can be checked
400 $titles[] = $newtitle;
409 * Really extract the redirect destination
410 * Do not call this function directly, use one of the newFromRedirect* functions above
412 * @param $text String Text with possible redirect
415 protected static function newFromRedirectInternal( $text ) {
416 global $wgMaxRedirects;
417 if ( $wgMaxRedirects < 1 ) {
418 //redirects are disabled, so quit early
421 $redir = MagicWord
::get( 'redirect' );
422 $text = trim( $text );
423 if ( $redir->matchStartAndRemove( $text ) ) {
424 // Extract the first link and see if it's usable
425 // Ensure that it really does come directly after #REDIRECT
426 // Some older redirects included a colon, so don't freak about that!
428 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
429 // Strip preceding colon used to "escape" categories, etc.
430 // and URL-decode links
431 if ( strpos( $m[1], '%' ) !== false ) {
432 // Match behavior of inline link parsing here;
433 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
435 $title = Title
::newFromText( $m[1] );
436 // If the title is a redirect to bad special pages or is invalid, return null
437 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
447 * Get the prefixed DB key associated with an ID
449 * @param $id Int the page_id of the article
450 * @return Title an object representing the article, or NULL if no such article was found
452 public static function nameOf( $id ) {
453 $dbr = wfGetDB( DB_SLAVE
);
455 $s = $dbr->selectRow(
457 array( 'page_namespace', 'page_title' ),
458 array( 'page_id' => $id ),
461 if ( $s === false ) {
465 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
470 * Get a regex character class describing the legal characters in a link
472 * @return String the list of characters, not delimited
474 public static function legalChars() {
475 global $wgLegalTitleChars;
476 return $wgLegalTitleChars;
480 * Returns a simple regex that will match on characters and sequences invalid in titles.
481 * Note that this doesn't pick up many things that could be wrong with titles, but that
482 * replacing this regex with something valid will make many titles valid.
484 * @return String regex string
486 static function getTitleInvalidRegex() {
487 static $rxTc = false;
489 # Matching titles will be held as illegal.
491 # Any character not allowed is forbidden...
492 '[^' . self
::legalChars() . ']' .
493 # URL percent encoding sequences interfere with the ability
494 # to round-trip titles -- you can't link to them consistently.
496 # XML/HTML character references produce similar issues.
497 '|&[A-Za-z0-9\x80-\xff]+;' .
499 '|&#x[0-9A-Fa-f]+;' .
507 * Get a string representation of a title suitable for
508 * including in a search index
510 * @param $ns Int a namespace index
511 * @param $title String text-form main part
512 * @return String a stripped-down title string ready for the search index
514 public static function indexTitle( $ns, $title ) {
517 $lc = SearchEngine
::legalSearchChars() . '&#;';
518 $t = $wgContLang->normalizeForSearch( $title );
519 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
520 $t = $wgContLang->lc( $t );
523 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
524 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
526 $t = preg_replace( "/\\s+/", ' ', $t );
528 if ( $ns == NS_FILE
) {
529 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
535 * Make a prefixed DB key from a DB key and a namespace index
537 * @param $ns Int numerical representation of the namespace
538 * @param $title String the DB key form the title
539 * @param $fragment String The link fragment (after the "#")
540 * @param $interwiki String The interwiki prefix
541 * @return String the prefixed form of the title
543 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
546 $namespace = $wgContLang->getNsText( $ns );
547 $name = $namespace == '' ?
$title : "$namespace:$title";
548 if ( strval( $interwiki ) != '' ) {
549 $name = "$interwiki:$name";
551 if ( strval( $fragment ) != '' ) {
552 $name .= '#' . $fragment;
558 * Escape a text fragment, say from a link, for a URL
560 * @param $fragment string containing a URL or link fragment (after the "#")
561 * @return String: escaped string
563 static function escapeFragmentForURL( $fragment ) {
564 # Note that we don't urlencode the fragment. urlencoded Unicode
565 # fragments appear not to work in IE (at least up to 7) or in at least
566 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
567 # to care if they aren't encoded.
568 return Sanitizer
::escapeId( $fragment, 'noninitial' );
572 * Callback for usort() to do title sorts by (namespace, title)
577 * @return Integer: result of string comparison, or namespace comparison
579 public static function compare( $a, $b ) {
580 if ( $a->getNamespace() == $b->getNamespace() ) {
581 return strcmp( $a->getText(), $b->getText() );
583 return $a->getNamespace() - $b->getNamespace();
588 * Determine whether the object refers to a page within
591 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
593 public function isLocal() {
594 if ( $this->mInterwiki
!= '' ) {
595 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
602 * Is this Title interwiki?
606 public function isExternal() {
607 return ( $this->mInterwiki
!= '' );
611 * Get the interwiki prefix (or null string)
613 * @return String Interwiki prefix
615 public function getInterwiki() {
616 return $this->mInterwiki
;
620 * Determine whether the object refers to a page within
621 * this project and is transcludable.
623 * @return Bool TRUE if this is transcludable
625 public function isTrans() {
626 if ( $this->mInterwiki
== '' ) {
630 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
634 * Returns the DB name of the distant wiki which owns the object.
636 * @return String the DB name
638 public function getTransWikiID() {
639 if ( $this->mInterwiki
== '' ) {
643 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
647 * Get the text form (spaces not underscores) of the main part
649 * @return String Main part of the title
651 public function getText() {
652 return $this->mTextform
;
656 * Get the URL-encoded form of the main part
658 * @return String Main part of the title, URL-encoded
660 public function getPartialURL() {
661 return $this->mUrlform
;
665 * Get the main part with underscores
667 * @return String: Main part of the title, with underscores
669 public function getDBkey() {
670 return $this->mDbkeyform
;
674 * Get the DB key with the initial letter case as specified by the user
676 * @return String DB key
678 function getUserCaseDBKey() {
679 return $this->mUserCaseDBKey
;
683 * Get the namespace index, i.e. one of the NS_xxxx constants.
685 * @return Integer: Namespace index
687 public function getNamespace() {
688 return $this->mNamespace
;
692 * Get the namespace text
694 * @return String: Namespace text
696 public function getNsText() {
699 if ( $this->mInterwiki
!= '' ) {
700 // This probably shouldn't even happen. ohh man, oh yuck.
701 // But for interwiki transclusion it sometimes does.
702 // Shit. Shit shit shit.
704 // Use the canonical namespaces if possible to try to
705 // resolve a foreign namespace.
706 if ( MWNamespace
::exists( $this->mNamespace
) ) {
707 return MWNamespace
::getCanonicalName( $this->mNamespace
);
711 // Strip off subpages
712 $pagename = $this->getText();
713 if ( strpos( $pagename, '/' ) !== false ) {
714 list( $username , ) = explode( '/', $pagename, 2 );
716 $username = $pagename;
719 if ( $wgContLang->needsGenderDistinction() &&
720 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
721 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
722 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
725 return $wgContLang->getNsText( $this->mNamespace
);
729 * Get the namespace text of the subject (rather than talk) page
731 * @return String Namespace text
733 public function getSubjectNsText() {
735 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
739 * Get the namespace text of the talk page
741 * @return String Namespace text
743 public function getTalkNsText() {
745 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
749 * Could this title have a corresponding talk page?
751 * @return Bool TRUE or FALSE
753 public function canTalk() {
754 return( MWNamespace
::canTalk( $this->mNamespace
) );
758 * Is this in a namespace that allows actual pages?
761 * @internal note -- uses hardcoded namespace index instead of constants
763 public function canExist() {
764 return $this->mNamespace
>= NS_MAIN
;
768 * Can this title be added to a user's watchlist?
770 * @return Bool TRUE or FALSE
772 public function isWatchable() {
773 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
777 * Returns true if this is a special page.
781 public function isSpecialPage() {
782 return $this->getNamespace() == NS_SPECIAL
;
786 * Returns true if this title resolves to the named special page
788 * @param $name String The special page name
791 public function isSpecial( $name ) {
792 if ( $this->isSpecialPage() ) {
793 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
794 if ( $name == $thisName ) {
802 * If the Title refers to a special page alias which is not the local default, resolve
803 * the alias, and localise the name as necessary. Otherwise, return $this
807 public function fixSpecialName() {
808 if ( $this->isSpecialPage() ) {
809 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
810 if ( $canonicalName ) {
811 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
812 if ( $localName != $this->mDbkeyform
) {
813 return Title
::makeTitle( NS_SPECIAL
, $localName );
821 * Returns true if the title is inside the specified namespace.
823 * Please make use of this instead of comparing to getNamespace()
824 * This function is much more resistant to changes we may make
825 * to namespaces than code that makes direct comparisons.
826 * @param $ns int The namespace
830 public function inNamespace( $ns ) {
831 return MWNamespace
::equals( $this->getNamespace(), $ns );
835 * Returns true if the title is inside one of the specified namespaces.
837 * @param ...$namespaces The namespaces to check for
841 public function inNamespaces( /* ... */ ) {
842 $namespaces = func_get_args();
843 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
844 $namespaces = $namespaces[0];
847 foreach ( $namespaces as $ns ) {
848 if ( $this->inNamespace( $ns ) ) {
857 * Returns true if the title has the same subject namespace as the
858 * namespace specified.
859 * For example this method will take NS_USER and return true if namespace
860 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
861 * as their subject namespace.
863 * This is MUCH simpler than individually testing for equivilance
864 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
868 public function hasSubjectNamespace( $ns ) {
869 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
873 * Is this Title in a namespace which contains content?
874 * In other words, is this a content page, for the purposes of calculating
879 public function isContentPage() {
880 return MWNamespace
::isContent( $this->getNamespace() );
884 * Would anybody with sufficient privileges be able to move this page?
885 * Some pages just aren't movable.
887 * @return Bool TRUE or FALSE
889 public function isMovable() {
890 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
891 // Interwiki title or immovable namespace. Hooks don't get to override here
896 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
901 * Is this the mainpage?
902 * @note Title::newFromText seams to be sufficiently optimized by the title
903 * cache that we don't need to over-optimize by doing direct comparisons and
904 * acidentally creating new bugs where $title->equals( Title::newFromText() )
905 * ends up reporting something differently than $title->isMainPage();
910 public function isMainPage() {
911 return $this->equals( Title
::newMainPage() );
919 public function isSubpage() {
920 return MWNamespace
::hasSubpages( $this->mNamespace
)
921 ?
strpos( $this->getText(), '/' ) !== false
926 * Is this a conversion table for the LanguageConverter?
930 public function isConversionTable() {
931 return $this->getNamespace() == NS_MEDIAWIKI
&&
932 strpos( $this->getText(), 'Conversiontable' ) !== false;
936 * Does that page contain wikitext, or it is JS, CSS or whatever?
940 public function isWikitextPage() {
941 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
942 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
947 * Could this page contain custom CSS or JavaScript, based
952 public function isCssOrJsPage() {
953 $retval = $this->mNamespace
== NS_MEDIAWIKI
954 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
955 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
960 * Is this a .css or .js subpage of a user page?
963 public function isCssJsSubpage() {
964 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
968 * Trim down a .css or .js subpage title to get the corresponding skin name
970 * @return string containing skin name from .css or .js subpage title
972 public function getSkinFromCssJsSubpage() {
973 $subpage = explode( '/', $this->mTextform
);
974 $subpage = $subpage[ count( $subpage ) - 1 ];
975 $lastdot = strrpos( $subpage, '.' );
976 if ( $lastdot === false )
977 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
978 return substr( $subpage, 0, $lastdot );
982 * Is this a .css subpage of a user page?
986 public function isCssSubpage() {
987 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
991 * Is this a .js subpage of a user page?
995 public function isJsSubpage() {
996 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1000 * Is this a talk page of some sort?
1004 public function isTalkPage() {
1005 return MWNamespace
::isTalk( $this->getNamespace() );
1009 * Get a Title object associated with the talk page of this article
1011 * @return Title the object for the talk page
1013 public function getTalkPage() {
1014 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1018 * Get a title object associated with the subject page of this
1021 * @return Title the object for the subject page
1023 public function getSubjectPage() {
1024 // Is this the same title?
1025 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1026 if ( $this->getNamespace() == $subjectNS ) {
1029 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1033 * Get the default namespace index, for when there is no namespace
1035 * @return Int Default namespace index
1037 public function getDefaultNamespace() {
1038 return $this->mDefaultNamespace
;
1042 * Get title for search index
1044 * @return String a stripped-down title string ready for the
1047 public function getIndexTitle() {
1048 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1052 * Get the Title fragment (i.e.\ the bit after the #) in text form
1054 * @return String Title fragment
1056 public function getFragment() {
1057 return $this->mFragment
;
1061 * Get the fragment in URL form, including the "#" character if there is one
1062 * @return String Fragment in URL form
1064 public function getFragmentForURL() {
1065 if ( $this->mFragment
== '' ) {
1068 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1073 * Set the fragment for this title. Removes the first character from the
1074 * specified fragment before setting, so it assumes you're passing it with
1077 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1078 * Still in active use privately.
1080 * @param $fragment String text
1082 public function setFragment( $fragment ) {
1083 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1087 * Prefix some arbitrary text with the namespace or interwiki prefix
1090 * @param $name String the text
1091 * @return String the prefixed text
1094 private function prefix( $name ) {
1096 if ( $this->mInterwiki
!= '' ) {
1097 $p = $this->mInterwiki
. ':';
1100 if ( 0 != $this->mNamespace
) {
1101 $p .= $this->getNsText() . ':';
1107 * Get the prefixed database key form
1109 * @return String the prefixed title, with underscores and
1110 * any interwiki and namespace prefixes
1112 public function getPrefixedDBkey() {
1113 $s = $this->prefix( $this->mDbkeyform
);
1114 $s = str_replace( ' ', '_', $s );
1119 * Get the prefixed title with spaces.
1120 * This is the form usually used for display
1122 * @return String the prefixed title, with spaces
1124 public function getPrefixedText() {
1125 // @todo FIXME: Bad usage of empty() ?
1126 if ( empty( $this->mPrefixedText
) ) {
1127 $s = $this->prefix( $this->mTextform
);
1128 $s = str_replace( '_', ' ', $s );
1129 $this->mPrefixedText
= $s;
1131 return $this->mPrefixedText
;
1135 * Return a string representation of this title
1137 * @return String representation of this title
1139 public function __toString() {
1140 return $this->getPrefixedText();
1144 * Get the prefixed title with spaces, plus any fragment
1145 * (part beginning with '#')
1147 * @return String the prefixed title, with spaces and the fragment, including '#'
1149 public function getFullText() {
1150 $text = $this->getPrefixedText();
1151 if ( $this->mFragment
!= '' ) {
1152 $text .= '#' . $this->mFragment
;
1158 * Get the base page name, i.e. the leftmost part before any slashes
1160 * @return String Base name
1162 public function getBaseText() {
1163 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1164 return $this->getText();
1167 $parts = explode( '/', $this->getText() );
1168 # Don't discard the real title if there's no subpage involved
1169 if ( count( $parts ) > 1 ) {
1170 unset( $parts[count( $parts ) - 1] );
1172 return implode( '/', $parts );
1176 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1178 * @return String Subpage name
1180 public function getSubpageText() {
1181 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1182 return( $this->mTextform
);
1184 $parts = explode( '/', $this->mTextform
);
1185 return( $parts[count( $parts ) - 1] );
1189 * Get the HTML-escaped displayable text form.
1190 * Used for the title field in <a> tags.
1192 * @return String the text, including any prefixes
1194 public function getEscapedText() {
1195 wfDeprecated( __METHOD__
, '1.19' );
1196 return htmlspecialchars( $this->getPrefixedText() );
1200 * Get a URL-encoded form of the subpage text
1202 * @return String URL-encoded subpage name
1204 public function getSubpageUrlForm() {
1205 $text = $this->getSubpageText();
1206 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1211 * Get a URL-encoded title (not an actual URL) including interwiki
1213 * @return String the URL-encoded form
1215 public function getPrefixedURL() {
1216 $s = $this->prefix( $this->mDbkeyform
);
1217 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1222 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1223 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1224 * second argument named variant. This was deprecated in favor
1225 * of passing an array of option with a "variant" key
1226 * Once $query2 is removed for good, this helper can be dropped
1227 * andthe wfArrayToCGI moved to getLocalURL();
1229 * @since 1.19 (r105919)
1232 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1233 if( $query2 !== false ) {
1234 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" );
1236 if ( is_array( $query ) ) {
1237 $query = wfArrayToCGI( $query );
1240 if ( is_string( $query2 ) ) {
1241 // $query2 is a string, we will consider this to be
1242 // a deprecated $variant argument and add it to the query
1243 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1245 $query2 = wfArrayToCGI( $query2 );
1247 // If we have $query content add a & to it first
1251 // Now append the queries together
1258 * Get a real URL referring to this title, with interwiki link and
1261 * See getLocalURL for the arguments.
1263 * @see self::getLocalURL
1264 * @return String the URL
1266 public function getFullURL( $query = '', $query2 = false ) {
1267 $query = self
::fixUrlQueryArgs( $query, $query2 );
1269 # Hand off all the decisions on urls to getLocalURL
1270 $url = $this->getLocalURL( $query );
1272 # Expand the url to make it a full url. Note that getLocalURL has the
1273 # potential to output full urls for a variety of reasons, so we use
1274 # wfExpandUrl instead of simply prepending $wgServer
1275 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1277 # Finally, add the fragment.
1278 $url .= $this->getFragmentForURL();
1280 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1285 * Get a URL with no fragment or server name. If this page is generated
1286 * with action=render, $wgServer is prepended.
1289 * @param $query string|array an optional query string,
1290 * not used for interwiki links. Can be specified as an associative array as well,
1291 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1292 * Some query patterns will trigger various shorturl path replacements.
1293 * @param $query2 Mixed: An optional secondary query array. This one MUST
1294 * be an array. If a string is passed it will be interpreted as a deprecated
1295 * variant argument and urlencoded into a variant= argument.
1296 * This second query argument will be added to the $query
1297 * The second parameter is deprecated since 1.19. Pass it as a key,value
1298 * pair in the first parameter array instead.
1300 * @return String the URL
1302 public function getLocalURL( $query = '', $query2 = false ) {
1303 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1305 $query = self
::fixUrlQueryArgs( $query, $query2 );
1307 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1309 $namespace = $this->getNsText();
1310 if ( $namespace != '' ) {
1311 # Can this actually happen? Interwikis shouldn't be parsed.
1312 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1315 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1316 $url = wfAppendQuery( $url, $query );
1318 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1319 if ( $query == '' ) {
1320 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1321 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1323 global $wgVariantArticlePath, $wgActionPaths;
1327 if ( !empty( $wgActionPaths ) &&
1328 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1330 $action = urldecode( $matches[2] );
1331 if ( isset( $wgActionPaths[$action] ) ) {
1332 $query = $matches[1];
1333 if ( isset( $matches[4] ) ) {
1334 $query .= $matches[4];
1336 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1337 if ( $query != '' ) {
1338 $url = wfAppendQuery( $url, $query );
1343 if ( $url === false &&
1344 $wgVariantArticlePath &&
1345 $this->getPageLanguage()->hasVariants() &&
1346 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1348 $variant = urldecode( $matches[1] );
1349 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1350 // Only do the variant replacement if the given variant is a valid
1351 // variant for the page's language.
1352 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1353 $url = str_replace( '$1', $dbkey, $url );
1357 if ( $url === false ) {
1358 if ( $query == '-' ) {
1361 $url = "{$wgScript}?title={$dbkey}&{$query}";
1365 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1367 // @todo FIXME: This causes breakage in various places when we
1368 // actually expected a local URL and end up with dupe prefixes.
1369 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1370 $url = $wgServer . $url;
1373 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1378 * Get a URL that's the simplest URL that will be valid to link, locally,
1379 * to the current Title. It includes the fragment, but does not include
1380 * the server unless action=render is used (or the link is external). If
1381 * there's a fragment but the prefixed text is empty, we just return a link
1384 * The result obviously should not be URL-escaped, but does need to be
1385 * HTML-escaped if it's being output in HTML.
1387 * See getLocalURL for the arguments.
1389 * @see self::getLocalURL
1390 * @return String the URL
1392 public function getLinkURL( $query = '', $query2 = false ) {
1393 wfProfileIn( __METHOD__
);
1394 if ( $this->isExternal() ) {
1395 $ret = $this->getFullURL( $query, $query2 );
1396 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1397 $ret = $this->getFragmentForURL();
1399 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1401 wfProfileOut( __METHOD__
);
1406 * Get an HTML-escaped version of the URL form, suitable for
1407 * using in a link, without a server name or fragment
1409 * See getLocalURL for the arguments.
1411 * @see self::getLocalURL
1412 * @return String the URL
1414 public function escapeLocalURL( $query = '', $query2 = false ) {
1415 wfDeprecated( __METHOD__
, '1.19' );
1416 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1420 * Get an HTML-escaped version of the URL form, suitable for
1421 * using in a link, including the server name and fragment
1423 * See getLocalURL for the arguments.
1425 * @see self::getLocalURL
1426 * @return String the URL
1428 public function escapeFullURL( $query = '', $query2 = false ) {
1429 wfDeprecated( __METHOD__
, '1.19' );
1430 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1434 * Get the URL form for an internal link.
1435 * - Used in various Squid-related code, in case we have a different
1436 * internal hostname for the server from the exposed one.
1438 * This uses $wgInternalServer to qualify the path, or $wgServer
1439 * if $wgInternalServer is not set. If the server variable used is
1440 * protocol-relative, the URL will be expanded to http://
1442 * See getLocalURL for the arguments.
1444 * @see self::getLocalURL
1445 * @return String the URL
1447 public function getInternalURL( $query = '', $query2 = false ) {
1448 global $wgInternalServer, $wgServer;
1449 $query = self
::fixUrlQueryArgs( $query, $query2 );
1450 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1451 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1452 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1457 * Get the URL for a canonical link, for use in things like IRC and
1458 * e-mail notifications. Uses $wgCanonicalServer and the
1459 * GetCanonicalURL hook.
1461 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1463 * See getLocalURL for the arguments.
1465 * @see self::getLocalURL
1466 * @return string The URL
1469 public function getCanonicalURL( $query = '', $query2 = false ) {
1470 $query = self
::fixUrlQueryArgs( $query, $query2 );
1471 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1472 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1477 * HTML-escaped version of getCanonicalURL()
1479 * See getLocalURL for the arguments.
1481 * @see self::getLocalURL
1485 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1486 wfDeprecated( __METHOD__
, '1.19' );
1487 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1491 * Get the edit URL for this Title
1493 * @return String the URL, or a null string if this is an
1496 public function getEditURL() {
1497 if ( $this->mInterwiki
!= '' ) {
1500 $s = $this->getLocalURL( 'action=edit' );
1506 * Is $wgUser watching this page?
1510 public function userIsWatching() {
1513 if ( is_null( $this->mWatched
) ) {
1514 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1515 $this->mWatched
= false;
1517 $this->mWatched
= $wgUser->isWatched( $this );
1520 return $this->mWatched
;
1524 * Can $wgUser read this page?
1526 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1528 * @todo fold these checks into userCan()
1530 public function userCanRead() {
1531 wfDeprecated( __METHOD__
, '1.19' );
1532 return $this->userCan( 'read' );
1536 * Can $user perform $action on this page?
1537 * This skips potentially expensive cascading permission checks
1538 * as well as avoids expensive error formatting
1540 * Suitable for use for nonessential UI controls in common cases, but
1541 * _not_ for functional access control.
1543 * May provide false positives, but should never provide a false negative.
1545 * @param $action String action that permission needs to be checked for
1546 * @param $user User to check (since 1.19); $wgUser will be used if not
1550 public function quickUserCan( $action, $user = null ) {
1551 return $this->userCan( $action, $user, false );
1555 * Can $user perform $action on this page?
1557 * @param $action String action that permission needs to be checked for
1558 * @param $user User to check (since 1.19); $wgUser will be used if not
1560 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1561 * unnecessary queries.
1564 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1565 if ( !$user instanceof User
) {
1569 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1573 * Can $user perform $action on this page?
1575 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1577 * @param $action String action that permission needs to be checked for
1578 * @param $user User to check
1579 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1580 * queries by skipping checks for cascading protections and user blocks.
1581 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1582 * whose corresponding errors may be ignored.
1583 * @return Array of arguments to wfMsg to explain permissions problems.
1585 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1586 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1588 // Remove the errors being ignored.
1589 foreach ( $errors as $index => $error ) {
1590 $error_key = is_array( $error ) ?
$error[0] : $error;
1592 if ( in_array( $error_key, $ignoreErrors ) ) {
1593 unset( $errors[$index] );
1601 * Permissions checks that fail most often, and which are easiest to test.
1603 * @param $action String the action to check
1604 * @param $user User user to check
1605 * @param $errors Array list of current errors
1606 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1607 * @param $short Boolean short circuit on first error
1609 * @return Array list of errors
1611 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1612 if ( $action == 'create' ) {
1613 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1614 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1615 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1617 } elseif ( $action == 'move' ) {
1618 if ( !$user->isAllowed( 'move-rootuserpages' )
1619 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1620 // Show user page-specific message only if the user can move other pages
1621 $errors[] = array( 'cant-move-user-page' );
1624 // Check if user is allowed to move files if it's a file
1625 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1626 $errors[] = array( 'movenotallowedfile' );
1629 if ( !$user->isAllowed( 'move' ) ) {
1630 // User can't move anything
1631 global $wgGroupPermissions;
1632 $userCanMove = false;
1633 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1634 $userCanMove = $wgGroupPermissions['user']['move'];
1636 $autoconfirmedCanMove = false;
1637 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1638 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1640 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1641 // custom message if logged-in users without any special rights can move
1642 $errors[] = array( 'movenologintext' );
1644 $errors[] = array( 'movenotallowed' );
1647 } elseif ( $action == 'move-target' ) {
1648 if ( !$user->isAllowed( 'move' ) ) {
1649 // User can't move anything
1650 $errors[] = array( 'movenotallowed' );
1651 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1652 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1653 // Show user page-specific message only if the user can move other pages
1654 $errors[] = array( 'cant-move-to-user-page' );
1656 } elseif ( !$user->isAllowed( $action ) ) {
1657 $errors[] = $this->missingPermissionError( $action, $short );
1664 * Add the resulting error code to the errors array
1666 * @param $errors Array list of current errors
1667 * @param $result Mixed result of errors
1669 * @return Array list of errors
1671 private function resultToError( $errors, $result ) {
1672 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1673 // A single array representing an error
1674 $errors[] = $result;
1675 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1676 // A nested array representing multiple errors
1677 $errors = array_merge( $errors, $result );
1678 } elseif ( $result !== '' && is_string( $result ) ) {
1679 // A string representing a message-id
1680 $errors[] = array( $result );
1681 } elseif ( $result === false ) {
1682 // a generic "We don't want them to do that"
1683 $errors[] = array( 'badaccess-group0' );
1689 * Check various permission hooks
1691 * @param $action String the action to check
1692 * @param $user User user to check
1693 * @param $errors Array list of current errors
1694 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1695 * @param $short Boolean short circuit on first error
1697 * @return Array list of errors
1699 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1700 // Use getUserPermissionsErrors instead
1702 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1703 return $result ?
array() : array( array( 'badaccess-group0' ) );
1705 // Check getUserPermissionsErrors hook
1706 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1707 $errors = $this->resultToError( $errors, $result );
1709 // Check getUserPermissionsErrorsExpensive hook
1710 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1711 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1712 $errors = $this->resultToError( $errors, $result );
1719 * Check permissions on special pages & namespaces
1721 * @param $action String the action to check
1722 * @param $user User user to check
1723 * @param $errors Array list of current errors
1724 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1725 * @param $short Boolean short circuit on first error
1727 * @return Array list of errors
1729 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1730 # Only 'createaccount' and 'execute' can be performed on
1731 # special pages, which don't actually exist in the DB.
1732 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1733 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1734 $errors[] = array( 'ns-specialprotected' );
1737 # Check $wgNamespaceProtection for restricted namespaces
1738 if ( $this->isNamespaceProtected( $user ) ) {
1739 $ns = $this->mNamespace
== NS_MAIN ?
1740 wfMsg( 'nstab-main' ) : $this->getNsText();
1741 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1742 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1749 * Check CSS/JS sub-page permissions
1751 * @param $action String the action to check
1752 * @param $user User user to check
1753 * @param $errors Array list of current errors
1754 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1755 * @param $short Boolean short circuit on first error
1757 * @return Array list of errors
1759 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1760 # Protect css/js subpages of user pages
1761 # XXX: this might be better using restrictions
1762 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1763 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1764 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1765 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1766 $errors[] = array( 'customcssprotected' );
1767 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1768 $errors[] = array( 'customjsprotected' );
1776 * Check against page_restrictions table requirements on this
1777 * page. The user must possess all required rights for this
1780 * @param $action String the action to check
1781 * @param $user User user to check
1782 * @param $errors Array list of current errors
1783 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1784 * @param $short Boolean short circuit on first error
1786 * @return Array list of errors
1788 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1789 foreach ( $this->getRestrictions( $action ) as $right ) {
1790 // Backwards compatibility, rewrite sysop -> protect
1791 if ( $right == 'sysop' ) {
1794 if ( $right != '' && !$user->isAllowed( $right ) ) {
1795 // Users with 'editprotected' permission can edit protected pages
1796 // without cascading option turned on.
1797 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1798 ||
$this->mCascadeRestriction
)
1800 $errors[] = array( 'protectedpagetext', $right );
1809 * Check restrictions on cascading pages.
1811 * @param $action String the action to check
1812 * @param $user User to check
1813 * @param $errors Array list of current errors
1814 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1815 * @param $short Boolean short circuit on first error
1817 * @return Array list of errors
1819 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1820 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1821 # We /could/ use the protection level on the source page, but it's
1822 # fairly ugly as we have to establish a precedence hierarchy for pages
1823 # included by multiple cascade-protected pages. So just restrict
1824 # it to people with 'protect' permission, as they could remove the
1825 # protection anyway.
1826 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1827 # Cascading protection depends on more than this page...
1828 # Several cascading protected pages may include this page...
1829 # Check each cascading level
1830 # This is only for protection restrictions, not for all actions
1831 if ( isset( $restrictions[$action] ) ) {
1832 foreach ( $restrictions[$action] as $right ) {
1833 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1834 if ( $right != '' && !$user->isAllowed( $right ) ) {
1836 foreach ( $cascadingSources as $page )
1837 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1838 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1848 * Check action permissions not already checked in checkQuickPermissions
1850 * @param $action String the action to check
1851 * @param $user User to check
1852 * @param $errors Array list of current errors
1853 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1854 * @param $short Boolean short circuit on first error
1856 * @return Array list of errors
1858 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1859 global $wgDeleteRevisionsLimit, $wgLang;
1861 if ( $action == 'protect' ) {
1862 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1863 // If they can't edit, they shouldn't protect.
1864 $errors[] = array( 'protect-cantedit' );
1866 } elseif ( $action == 'create' ) {
1867 $title_protection = $this->getTitleProtection();
1868 if( $title_protection ) {
1869 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1870 $title_protection['pt_create_perm'] = 'protect'; // B/C
1872 if( $title_protection['pt_create_perm'] == '' ||
1873 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1875 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1878 } elseif ( $action == 'move' ) {
1879 // Check for immobile pages
1880 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1881 // Specific message for this case
1882 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1883 } elseif ( !$this->isMovable() ) {
1884 // Less specific message for rarer cases
1885 $errors[] = array( 'immobile-source-page' );
1887 } elseif ( $action == 'move-target' ) {
1888 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1889 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1890 } elseif ( !$this->isMovable() ) {
1891 $errors[] = array( 'immobile-target-page' );
1893 } elseif ( $action == 'delete' ) {
1894 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1895 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1897 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1904 * Check that the user isn't blocked from editting.
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 checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1915 // Account creation blocks handled at userlogin.
1916 // Unblocking handled in SpecialUnblock
1917 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1921 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1923 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1924 $errors[] = array( 'confirmedittext' );
1927 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1928 // Don't block the user from editing their own talk page unless they've been
1929 // explicitly blocked from that too.
1930 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1931 $block = $user->mBlock
;
1933 // This is from OutputPage::blockedPage
1934 // Copied at r23888 by werdna
1936 $id = $user->blockedBy();
1937 $reason = $user->blockedFor();
1938 if ( $reason == '' ) {
1939 $reason = wfMsg( 'blockednoreason' );
1941 $ip = $user->getRequest()->getIP();
1943 if ( is_numeric( $id ) ) {
1944 $name = User
::whoIs( $id );
1949 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1950 $blockid = $block->getId();
1951 $blockExpiry = $user->mBlock
->mExpiry
;
1952 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1953 if ( $blockExpiry == 'infinity' ) {
1954 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1956 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1959 $intended = strval( $user->mBlock
->getTarget() );
1961 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1962 $blockid, $blockExpiry, $intended, $blockTimestamp );
1969 * Check that the user is allowed to read this page.
1971 * @param $action String the action to check
1972 * @param $user User to check
1973 * @param $errors Array list of current errors
1974 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1975 * @param $short Boolean short circuit on first error
1977 * @return Array list of errors
1979 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1980 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1981 static $useShortcut = null;
1983 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1984 if ( is_null( $useShortcut ) ) {
1985 $useShortcut = true;
1986 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1987 # Not a public wiki, so no shortcut
1988 $useShortcut = false;
1989 } elseif ( !empty( $wgRevokePermissions ) ) {
1991 * Iterate through each group with permissions being revoked (key not included since we don't care
1992 * what the group name is), then check if the read permission is being revoked. If it is, then
1993 * we don't use the shortcut below since the user might not be able to read, even though anon
1994 * reading is allowed.
1996 foreach ( $wgRevokePermissions as $perms ) {
1997 if ( !empty( $perms['read'] ) ) {
1998 # We might be removing the read right from the user, so no shortcut
1999 $useShortcut = false;
2006 $whitelisted = false;
2007 if ( $useShortcut ) {
2008 # Shortcut for public wikis, allows skipping quite a bit of code
2009 $whitelisted = true;
2010 } elseif ( $user->isAllowed( 'read' ) ) {
2011 # If the user is allowed to read pages, he is allowed to read all pages
2012 $whitelisted = true;
2013 } elseif ( $this->isSpecial( 'Userlogin' )
2014 ||
$this->isSpecial( 'ChangePassword' )
2015 ||
$this->isSpecial( 'PasswordReset' )
2017 # Always grant access to the login page.
2018 # Even anons need to be able to log in.
2019 $whitelisted = true;
2020 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2021 # Time to check the whitelist
2022 # Only do these checks is there's something to check against
2023 $name = $this->getPrefixedText();
2024 $dbName = $this->getPrefixedDBKey();
2026 // Check for explicit whitelisting with and without underscores
2027 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2028 $whitelisted = true;
2029 } elseif ( $this->getNamespace() == NS_MAIN
) {
2030 # Old settings might have the title prefixed with
2031 # a colon for main-namespace pages
2032 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2033 $whitelisted = true;
2035 } elseif ( $this->isSpecialPage() ) {
2036 # If it's a special page, ditch the subpage bit and check again
2037 $name = $this->getDBkey();
2038 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2039 if ( $name !== false ) {
2040 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2041 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2042 $whitelisted = true;
2048 if ( !$whitelisted ) {
2049 # If the title is not whitelisted, give extensions a chance to do so...
2050 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2051 if ( !$whitelisted ) {
2052 $errors[] = $this->missingPermissionError( $action, $short );
2060 * Get a description array when the user doesn't have the right to perform
2061 * $action (i.e. when User::isAllowed() returns false)
2063 * @param $action String the action to check
2064 * @param $short Boolean short circuit on first error
2065 * @return Array list of errors
2067 private function missingPermissionError( $action, $short ) {
2068 // We avoid expensive display logic for quickUserCan's and such
2070 return array( 'badaccess-group0' );
2073 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2074 User
::getGroupsWithPermission( $action ) );
2076 if ( count( $groups ) ) {
2080 $wgLang->commaList( $groups ),
2084 return array( 'badaccess-group0' );
2089 * Can $user perform $action on this page? This is an internal function,
2090 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2091 * checks on wfReadOnly() and blocks)
2093 * @param $action String action that permission needs to be checked for
2094 * @param $user User to check
2095 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2096 * @param $short Bool Set this to true to stop after the first permission error.
2097 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2099 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2100 wfProfileIn( __METHOD__
);
2102 # Read has special handling
2103 if ( $action == 'read' ) {
2105 'checkPermissionHooks',
2106 'checkReadPermissions',
2110 'checkQuickPermissions',
2111 'checkPermissionHooks',
2112 'checkSpecialsAndNSPermissions',
2113 'checkCSSandJSPermissions',
2114 'checkPageRestrictions',
2115 'checkCascadingSourcesRestrictions',
2116 'checkActionPermissions',
2122 while( count( $checks ) > 0 &&
2123 !( $short && count( $errors ) > 0 ) ) {
2124 $method = array_shift( $checks );
2125 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2128 wfProfileOut( __METHOD__
);
2133 * Protect css subpages of user pages: can $wgUser edit
2136 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2139 public function userCanEditCssSubpage() {
2141 wfDeprecated( __METHOD__
, '1.19' );
2142 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2143 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2147 * Protect js subpages of user pages: can $wgUser edit
2150 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2153 public function userCanEditJsSubpage() {
2155 wfDeprecated( __METHOD__
, '1.19' );
2156 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2157 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2161 * Get a filtered list of all restriction types supported by this wiki.
2162 * @param bool $exists True to get all restriction types that apply to
2163 * titles that do exist, False for all restriction types that apply to
2164 * titles that do not exist
2167 public static function getFilteredRestrictionTypes( $exists = true ) {
2168 global $wgRestrictionTypes;
2169 $types = $wgRestrictionTypes;
2171 # Remove the create restriction for existing titles
2172 $types = array_diff( $types, array( 'create' ) );
2174 # Only the create and upload restrictions apply to non-existing titles
2175 $types = array_intersect( $types, array( 'create', 'upload' ) );
2181 * Returns restriction types for the current Title
2183 * @return array applicable restriction types
2185 public function getRestrictionTypes() {
2186 if ( $this->isSpecialPage() ) {
2190 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2192 if ( $this->getNamespace() != NS_FILE
) {
2193 # Remove the upload restriction for non-file titles
2194 $types = array_diff( $types, array( 'upload' ) );
2197 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2199 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2200 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2206 * Is this title subject to title protection?
2207 * Title protection is the one applied against creation of such title.
2209 * @return Mixed An associative array representing any existent title
2210 * protection, or false if there's none.
2212 private function getTitleProtection() {
2213 // Can't protect pages in special namespaces
2214 if ( $this->getNamespace() < 0 ) {
2218 // Can't protect pages that exist.
2219 if ( $this->exists() ) {
2223 if ( !isset( $this->mTitleProtection
) ) {
2224 $dbr = wfGetDB( DB_SLAVE
);
2225 $res = $dbr->select( 'protected_titles', '*',
2226 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2229 // fetchRow returns false if there are no rows.
2230 $this->mTitleProtection
= $dbr->fetchRow( $res );
2232 return $this->mTitleProtection
;
2236 * Update the title protection status
2238 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2239 * @param $create_perm String Permission required for creation
2240 * @param $reason String Reason for protection
2241 * @param $expiry String Expiry timestamp
2242 * @return boolean true
2244 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2245 wfDeprecated( __METHOD__
, '1.19' );
2249 $limit = array( 'create' => $create_perm );
2250 $expiry = array( 'create' => $expiry );
2252 $page = WikiPage
::factory( $this );
2253 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2255 return $status->isOK();
2259 * Remove any title protection due to page existing
2261 public function deleteTitleProtection() {
2262 $dbw = wfGetDB( DB_MASTER
);
2266 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2269 $this->mTitleProtection
= false;
2273 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2275 * @param $action String Action to check (default: edit)
2278 public function isSemiProtected( $action = 'edit' ) {
2279 if ( $this->exists() ) {
2280 $restrictions = $this->getRestrictions( $action );
2281 if ( count( $restrictions ) > 0 ) {
2282 foreach ( $restrictions as $restriction ) {
2283 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2293 # If it doesn't exist, it can't be protected
2299 * Does the title correspond to a protected article?
2301 * @param $action String the action the page is protected from,
2302 * by default checks all actions.
2305 public function isProtected( $action = '' ) {
2306 global $wgRestrictionLevels;
2308 $restrictionTypes = $this->getRestrictionTypes();
2310 # Special pages have inherent protection
2311 if( $this->isSpecialPage() ) {
2315 # Check regular protection levels
2316 foreach ( $restrictionTypes as $type ) {
2317 if ( $action == $type ||
$action == '' ) {
2318 $r = $this->getRestrictions( $type );
2319 foreach ( $wgRestrictionLevels as $level ) {
2320 if ( in_array( $level, $r ) && $level != '' ) {
2331 * Determines if $user is unable to edit this page because it has been protected
2332 * by $wgNamespaceProtection.
2334 * @param $user User object to check permissions
2337 public function isNamespaceProtected( User
$user ) {
2338 global $wgNamespaceProtection;
2340 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2341 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2342 if ( $right != '' && !$user->isAllowed( $right ) ) {
2351 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2353 * @return Bool If the page is subject to cascading restrictions.
2355 public function isCascadeProtected() {
2356 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2357 return ( $sources > 0 );
2361 * Cascading protection: Get the source of any cascading restrictions on this page.
2363 * @param $getPages Bool Whether or not to retrieve the actual pages
2364 * that the restrictions have come from.
2365 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2366 * have come, false for none, or true if such restrictions exist, but $getPages
2367 * was not set. The restriction array is an array of each type, each of which
2368 * contains a array of unique groups.
2370 public function getCascadeProtectionSources( $getPages = true ) {
2372 $pagerestrictions = array();
2374 if ( isset( $this->mCascadeSources
) && $getPages ) {
2375 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2376 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2377 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2380 wfProfileIn( __METHOD__
);
2382 $dbr = wfGetDB( DB_SLAVE
);
2384 if ( $this->getNamespace() == NS_FILE
) {
2385 $tables = array( 'imagelinks', 'page_restrictions' );
2386 $where_clauses = array(
2387 'il_to' => $this->getDBkey(),
2392 $tables = array( 'templatelinks', 'page_restrictions' );
2393 $where_clauses = array(
2394 'tl_namespace' => $this->getNamespace(),
2395 'tl_title' => $this->getDBkey(),
2402 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2403 'pr_expiry', 'pr_type', 'pr_level' );
2404 $where_clauses[] = 'page_id=pr_page';
2407 $cols = array( 'pr_expiry' );
2410 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2412 $sources = $getPages ?
array() : false;
2413 $now = wfTimestampNow();
2414 $purgeExpired = false;
2416 foreach ( $res as $row ) {
2417 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2418 if ( $expiry > $now ) {
2420 $page_id = $row->pr_page
;
2421 $page_ns = $row->page_namespace
;
2422 $page_title = $row->page_title
;
2423 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2424 # Add groups needed for each restriction type if its not already there
2425 # Make sure this restriction type still exists
2427 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2428 $pagerestrictions[$row->pr_type
] = array();
2431 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2432 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2433 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2439 // Trigger lazy purge of expired restrictions from the db
2440 $purgeExpired = true;
2443 if ( $purgeExpired ) {
2444 Title
::purgeExpiredRestrictions();
2448 $this->mCascadeSources
= $sources;
2449 $this->mCascadingRestrictions
= $pagerestrictions;
2451 $this->mHasCascadingRestrictions
= $sources;
2454 wfProfileOut( __METHOD__
);
2455 return array( $sources, $pagerestrictions );
2459 * Accessor/initialisation for mRestrictions
2461 * @param $action String action that permission needs to be checked for
2462 * @return Array of Strings the array of groups allowed to edit this article
2464 public function getRestrictions( $action ) {
2465 if ( !$this->mRestrictionsLoaded
) {
2466 $this->loadRestrictions();
2468 return isset( $this->mRestrictions
[$action] )
2469 ?
$this->mRestrictions
[$action]
2474 * Get the expiry time for the restriction against a given action
2476 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2477 * or not protected at all, or false if the action is not recognised.
2479 public function getRestrictionExpiry( $action ) {
2480 if ( !$this->mRestrictionsLoaded
) {
2481 $this->loadRestrictions();
2483 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2487 * Returns cascading restrictions for the current article
2491 function areRestrictionsCascading() {
2492 if ( !$this->mRestrictionsLoaded
) {
2493 $this->loadRestrictions();
2496 return $this->mCascadeRestriction
;
2500 * Loads a string into mRestrictions array
2502 * @param $res Resource restrictions as an SQL result.
2503 * @param $oldFashionedRestrictions String comma-separated list of page
2504 * restrictions from page table (pre 1.10)
2506 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2509 foreach ( $res as $row ) {
2513 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2517 * Compiles list of active page restrictions from both page table (pre 1.10)
2518 * and page_restrictions table for this existing page.
2519 * Public for usage by LiquidThreads.
2521 * @param $rows array of db result objects
2522 * @param $oldFashionedRestrictions string comma-separated list of page
2523 * restrictions from page table (pre 1.10)
2525 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2527 $dbr = wfGetDB( DB_SLAVE
);
2529 $restrictionTypes = $this->getRestrictionTypes();
2531 foreach ( $restrictionTypes as $type ) {
2532 $this->mRestrictions
[$type] = array();
2533 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2536 $this->mCascadeRestriction
= false;
2538 # Backwards-compatibility: also load the restrictions from the page record (old format).
2540 if ( $oldFashionedRestrictions === null ) {
2541 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2542 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2545 if ( $oldFashionedRestrictions != '' ) {
2547 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2548 $temp = explode( '=', trim( $restrict ) );
2549 if ( count( $temp ) == 1 ) {
2550 // old old format should be treated as edit/move restriction
2551 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2552 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2554 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2558 $this->mOldRestrictions
= true;
2562 if ( count( $rows ) ) {
2563 # Current system - load second to make them override.
2564 $now = wfTimestampNow();
2565 $purgeExpired = false;
2567 # Cycle through all the restrictions.
2568 foreach ( $rows as $row ) {
2570 // Don't take care of restrictions types that aren't allowed
2571 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2574 // This code should be refactored, now that it's being used more generally,
2575 // But I don't really see any harm in leaving it in Block for now -werdna
2576 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2578 // Only apply the restrictions if they haven't expired!
2579 if ( !$expiry ||
$expiry > $now ) {
2580 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2581 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2583 $this->mCascadeRestriction |
= $row->pr_cascade
;
2585 // Trigger a lazy purge of expired restrictions
2586 $purgeExpired = true;
2590 if ( $purgeExpired ) {
2591 Title
::purgeExpiredRestrictions();
2595 $this->mRestrictionsLoaded
= true;
2599 * Load restrictions from the page_restrictions table
2601 * @param $oldFashionedRestrictions String comma-separated list of page
2602 * restrictions from page table (pre 1.10)
2604 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2606 if ( !$this->mRestrictionsLoaded
) {
2607 if ( $this->exists() ) {
2608 $dbr = wfGetDB( DB_SLAVE
);
2610 $res = $dbr->select(
2611 'page_restrictions',
2613 array( 'pr_page' => $this->getArticleId() ),
2617 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2619 $title_protection = $this->getTitleProtection();
2621 if ( $title_protection ) {
2622 $now = wfTimestampNow();
2623 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2625 if ( !$expiry ||
$expiry > $now ) {
2626 // Apply the restrictions
2627 $this->mRestrictionsExpiry
['create'] = $expiry;
2628 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2629 } else { // Get rid of the old restrictions
2630 Title
::purgeExpiredRestrictions();
2631 $this->mTitleProtection
= false;
2634 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2636 $this->mRestrictionsLoaded
= true;
2642 * Flush the protection cache in this object and force reload from the database.
2643 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2645 public function flushRestrictions() {
2646 $this->mRestrictionsLoaded
= false;
2647 $this->mTitleProtection
= null;
2651 * Purge expired restrictions from the page_restrictions table
2653 static function purgeExpiredRestrictions() {
2654 $dbw = wfGetDB( DB_MASTER
);
2656 'page_restrictions',
2657 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2663 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2669 * Does this have subpages? (Warning, usually requires an extra DB query.)
2673 public function hasSubpages() {
2674 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2679 # We dynamically add a member variable for the purpose of this method
2680 # alone to cache the result. There's no point in having it hanging
2681 # around uninitialized in every Title object; therefore we only add it
2682 # if needed and don't declare it statically.
2683 if ( isset( $this->mHasSubpages
) ) {
2684 return $this->mHasSubpages
;
2687 $subpages = $this->getSubpages( 1 );
2688 if ( $subpages instanceof TitleArray
) {
2689 return $this->mHasSubpages
= (bool)$subpages->count();
2691 return $this->mHasSubpages
= false;
2695 * Get all subpages of this page.
2697 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2698 * @return mixed TitleArray, or empty array if this page's namespace
2699 * doesn't allow subpages
2701 public function getSubpages( $limit = -1 ) {
2702 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2706 $dbr = wfGetDB( DB_SLAVE
);
2707 $conds['page_namespace'] = $this->getNamespace();
2708 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2710 if ( $limit > -1 ) {
2711 $options['LIMIT'] = $limit;
2713 return $this->mSubpages
= TitleArray
::newFromResult(
2714 $dbr->select( 'page',
2715 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2724 * Is there a version of this page in the deletion archive?
2726 * @return Int the number of archived revisions
2728 public function isDeleted() {
2729 if ( $this->getNamespace() < 0 ) {
2732 $dbr = wfGetDB( DB_SLAVE
);
2734 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2735 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2738 if ( $this->getNamespace() == NS_FILE
) {
2739 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2740 array( 'fa_name' => $this->getDBkey() ),
2749 * Is there a version of this page in the deletion archive?
2753 public function isDeletedQuick() {
2754 if ( $this->getNamespace() < 0 ) {
2757 $dbr = wfGetDB( DB_SLAVE
);
2758 $deleted = (bool)$dbr->selectField( 'archive', '1',
2759 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2762 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2763 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2764 array( 'fa_name' => $this->getDBkey() ),
2772 * Get the article ID for this Title from the link cache,
2773 * adding it if necessary
2775 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2777 * @return Int the ID
2779 public function getArticleID( $flags = 0 ) {
2780 if ( $this->getNamespace() < 0 ) {
2781 return $this->mArticleID
= 0;
2783 $linkCache = LinkCache
::singleton();
2784 if ( $flags & self
::GAID_FOR_UPDATE
) {
2785 $oldUpdate = $linkCache->forUpdate( true );
2786 $linkCache->clearLink( $this );
2787 $this->mArticleID
= $linkCache->addLinkObj( $this );
2788 $linkCache->forUpdate( $oldUpdate );
2790 if ( -1 == $this->mArticleID
) {
2791 $this->mArticleID
= $linkCache->addLinkObj( $this );
2794 return $this->mArticleID
;
2798 * Is this an article that is a redirect page?
2799 * Uses link cache, adding it if necessary
2801 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2804 public function isRedirect( $flags = 0 ) {
2805 if ( !is_null( $this->mRedirect
) ) {
2806 return $this->mRedirect
;
2808 # Calling getArticleID() loads the field from cache as needed
2809 if ( !$this->getArticleID( $flags ) ) {
2810 return $this->mRedirect
= false;
2812 $linkCache = LinkCache
::singleton();
2813 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2815 return $this->mRedirect
;
2819 * What is the length of this page?
2820 * Uses link cache, adding it if necessary
2822 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2825 public function getLength( $flags = 0 ) {
2826 if ( $this->mLength
!= -1 ) {
2827 return $this->mLength
;
2829 # Calling getArticleID() loads the field from cache as needed
2830 if ( !$this->getArticleID( $flags ) ) {
2831 return $this->mLength
= 0;
2833 $linkCache = LinkCache
::singleton();
2834 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2836 return $this->mLength
;
2840 * What is the page_latest field for this page?
2842 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2843 * @return Int or 0 if the page doesn't exist
2845 public function getLatestRevID( $flags = 0 ) {
2846 if ( $this->mLatestID
!== false ) {
2847 return intval( $this->mLatestID
);
2849 # Calling getArticleID() loads the field from cache as needed
2850 if ( !$this->getArticleID( $flags ) ) {
2851 return $this->mLatestID
= 0;
2853 $linkCache = LinkCache
::singleton();
2854 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2856 return $this->mLatestID
;
2860 * This clears some fields in this object, and clears any associated
2861 * keys in the "bad links" section of the link cache.
2863 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2864 * loading of the new page_id. It's also called from
2865 * WikiPage::doDeleteArticle()
2867 * @param $newid Int the new Article ID
2869 public function resetArticleID( $newid ) {
2870 $linkCache = LinkCache
::singleton();
2871 $linkCache->clearLink( $this );
2873 if ( $newid === false ) {
2874 $this->mArticleID
= -1;
2876 $this->mArticleID
= intval( $newid );
2878 $this->mRestrictionsLoaded
= false;
2879 $this->mRestrictions
= array();
2880 $this->mRedirect
= null;
2881 $this->mLength
= -1;
2882 $this->mLatestID
= false;
2883 $this->mEstimateRevisions
= null;
2887 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2889 * @param $text String containing title to capitalize
2890 * @param $ns int namespace index, defaults to NS_MAIN
2891 * @return String containing capitalized title
2893 public static function capitalize( $text, $ns = NS_MAIN
) {
2896 if ( MWNamespace
::isCapitalized( $ns ) ) {
2897 return $wgContLang->ucfirst( $text );
2904 * Secure and split - main initialisation function for this object
2906 * Assumes that mDbkeyform has been set, and is urldecoded
2907 * and uses underscores, but not otherwise munged. This function
2908 * removes illegal characters, splits off the interwiki and
2909 * namespace prefixes, sets the other forms, and canonicalizes
2912 * @return Bool true on success
2914 private function secureAndSplit() {
2915 global $wgContLang, $wgLocalInterwiki;
2918 $this->mInterwiki
= $this->mFragment
= '';
2919 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2921 $dbkey = $this->mDbkeyform
;
2923 # Strip Unicode bidi override characters.
2924 # Sometimes they slip into cut-n-pasted page titles, where the
2925 # override chars get included in list displays.
2926 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2928 # Clean up whitespace
2929 # Note: use of the /u option on preg_replace here will cause
2930 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2931 # conveniently disabling them.
2932 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2933 $dbkey = trim( $dbkey, '_' );
2935 if ( $dbkey == '' ) {
2939 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2940 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2944 $this->mDbkeyform
= $dbkey;
2946 # Initial colon indicates main namespace rather than specified default
2947 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2948 if ( ':' == $dbkey[0] ) {
2949 $this->mNamespace
= NS_MAIN
;
2950 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2951 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2954 # Namespace or interwiki prefix
2956 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2959 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2961 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2962 # Ordinary namespace
2964 $this->mNamespace
= $ns;
2965 # For Talk:X pages, check if X has a "namespace" prefix
2966 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2967 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2968 # Disallow Talk:File:x type titles...
2970 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2971 # Disallow Talk:Interwiki:x type titles...
2975 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2976 if ( !$firstPass ) {
2977 # Can't make a local interwiki link to an interwiki link.
2978 # That's just crazy!
2984 $this->mInterwiki
= $wgContLang->lc( $p );
2986 # Redundant interwiki prefix to the local wiki
2987 if ( $wgLocalInterwiki !== false
2988 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2990 if ( $dbkey == '' ) {
2991 # Can't have an empty self-link
2994 $this->mInterwiki
= '';
2996 # Do another namespace split...
3000 # If there's an initial colon after the interwiki, that also
3001 # resets the default namespace
3002 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3003 $this->mNamespace
= NS_MAIN
;
3004 $dbkey = substr( $dbkey, 1 );
3007 # If there's no recognized interwiki or namespace,
3008 # then let the colon expression be part of the title.
3013 # We already know that some pages won't be in the database!
3014 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3015 $this->mArticleID
= 0;
3017 $fragment = strstr( $dbkey, '#' );
3018 if ( false !== $fragment ) {
3019 $this->setFragment( $fragment );
3020 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3021 # remove whitespace again: prevents "Foo_bar_#"
3022 # becoming "Foo_bar_"
3023 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3026 # Reject illegal characters.
3027 $rxTc = self
::getTitleInvalidRegex();
3028 if ( preg_match( $rxTc, $dbkey ) ) {
3032 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3033 # reachable due to the way web browsers deal with 'relative' URLs.
3034 # Also, they conflict with subpage syntax. Forbid them explicitly.
3035 if ( strpos( $dbkey, '.' ) !== false &&
3036 ( $dbkey === '.' ||
$dbkey === '..' ||
3037 strpos( $dbkey, './' ) === 0 ||
3038 strpos( $dbkey, '../' ) === 0 ||
3039 strpos( $dbkey, '/./' ) !== false ||
3040 strpos( $dbkey, '/../' ) !== false ||
3041 substr( $dbkey, -2 ) == '/.' ||
3042 substr( $dbkey, -3 ) == '/..' ) )
3047 # Magic tilde sequences? Nu-uh!
3048 if ( strpos( $dbkey, '~~~' ) !== false ) {
3052 # Limit the size of titles to 255 bytes. This is typically the size of the
3053 # underlying database field. We make an exception for special pages, which
3054 # don't need to be stored in the database, and may edge over 255 bytes due
3055 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3056 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3057 strlen( $dbkey ) > 512 )
3062 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3063 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3064 # other site might be case-sensitive.
3065 $this->mUserCaseDBKey
= $dbkey;
3066 if ( $this->mInterwiki
== '' ) {
3067 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3070 # Can't make a link to a namespace alone... "empty" local links can only be
3071 # self-links with a fragment identifier.
3072 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3076 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3077 // IP names are not allowed for accounts, and can only be referring to
3078 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3079 // there are numerous ways to present the same IP. Having sp:contribs scan
3080 // them all is silly and having some show the edits and others not is
3081 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3082 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3083 ? IP
::sanitizeIP( $dbkey )
3086 // Any remaining initial :s are illegal.
3087 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3092 $this->mDbkeyform
= $dbkey;
3093 $this->mUrlform
= wfUrlencode( $dbkey );
3095 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3101 * Get an array of Title objects linking to this Title
3102 * Also stores the IDs in the link cache.
3104 * WARNING: do not use this function on arbitrary user-supplied titles!
3105 * On heavily-used templates it will max out the memory.
3107 * @param $options Array: may be FOR UPDATE
3108 * @param $table String: table name
3109 * @param $prefix String: fields prefix
3110 * @return Array of Title objects linking here
3112 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3113 if ( count( $options ) > 0 ) {
3114 $db = wfGetDB( DB_MASTER
);
3116 $db = wfGetDB( DB_SLAVE
);
3120 array( 'page', $table ),
3121 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3123 "{$prefix}_from=page_id",
3124 "{$prefix}_namespace" => $this->getNamespace(),
3125 "{$prefix}_title" => $this->getDBkey() ),
3131 if ( $res->numRows() ) {
3132 $linkCache = LinkCache
::singleton();
3133 foreach ( $res as $row ) {
3134 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3136 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3137 $retVal[] = $titleObj;
3145 * Get an array of Title objects using this Title as a template
3146 * Also stores the IDs in the link cache.
3148 * WARNING: do not use this function on arbitrary user-supplied titles!
3149 * On heavily-used templates it will max out the memory.
3151 * @param $options Array: may be FOR UPDATE
3152 * @return Array of Title the Title objects linking here
3154 public function getTemplateLinksTo( $options = array() ) {
3155 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3159 * Get an array of Title objects linked from this Title
3160 * Also stores the IDs in the link cache.
3162 * WARNING: do not use this function on arbitrary user-supplied titles!
3163 * On heavily-used templates it will max out the memory.
3165 * @param $options Array: may be FOR UPDATE
3166 * @param $table String: table name
3167 * @param $prefix String: fields prefix
3168 * @return Array of Title objects linking here
3170 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3171 $id = $this->getArticleId();
3173 # If the page doesn't exist; there can't be any link from this page
3178 if ( count( $options ) > 0 ) {
3179 $db = wfGetDB( DB_MASTER
);
3181 $db = wfGetDB( DB_SLAVE
);
3184 $namespaceFiled = "{$prefix}_namespace";
3185 $titleField = "{$prefix}_title";
3188 array( $table, 'page' ),
3189 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3190 array( "{$prefix}_from" => $id ),
3193 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3197 if ( $res->numRows() ) {
3198 $linkCache = LinkCache
::singleton();
3199 foreach ( $res as $row ) {
3200 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3202 if ( $row->page_id
) {
3203 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3205 $linkCache->addBadLinkObj( $titleObj );
3207 $retVal[] = $titleObj;
3215 * Get an array of Title objects used on this Title as a template
3216 * Also stores the IDs in the link cache.
3218 * WARNING: do not use this function on arbitrary user-supplied titles!
3219 * On heavily-used templates it will max out the memory.
3221 * @param $options Array: may be FOR UPDATE
3222 * @return Array of Title the Title objects used here
3224 public function getTemplateLinksFrom( $options = array() ) {
3225 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3229 * Get an array of Title objects referring to non-existent articles linked from this page
3231 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3232 * @return Array of Title the Title objects
3234 public function getBrokenLinksFrom() {
3235 if ( $this->getArticleId() == 0 ) {
3236 # All links from article ID 0 are false positives
3240 $dbr = wfGetDB( DB_SLAVE
);
3241 $res = $dbr->select(
3242 array( 'page', 'pagelinks' ),
3243 array( 'pl_namespace', 'pl_title' ),
3245 'pl_from' => $this->getArticleId(),
3246 'page_namespace IS NULL'
3248 __METHOD__
, array(),
3252 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3258 foreach ( $res as $row ) {
3259 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3266 * Get a list of URLs to purge from the Squid cache when this
3269 * @return Array of String the URLs
3271 public function getSquidURLs() {
3275 $this->getInternalURL(),
3276 $this->getInternalURL( 'action=history' )
3279 // purge variant urls as well
3280 if ( $wgContLang->hasVariants() ) {
3281 $variants = $wgContLang->getVariants();
3282 foreach ( $variants as $vCode ) {
3283 $urls[] = $this->getInternalURL( '', $vCode );
3291 * Purge all applicable Squid URLs
3293 public function purgeSquid() {
3295 if ( $wgUseSquid ) {
3296 $urls = $this->getSquidURLs();
3297 $u = new SquidUpdate( $urls );
3303 * Move this page without authentication
3305 * @param $nt Title the new page Title
3306 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3308 public function moveNoAuth( &$nt ) {
3309 return $this->moveTo( $nt, false );
3313 * Check whether a given move operation would be valid.
3314 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3316 * @param $nt Title the new title
3317 * @param $auth Bool indicates whether $wgUser's permissions
3319 * @param $reason String is the log summary of the move, used for spam checking
3320 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3322 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3327 // Normally we'd add this to $errors, but we'll get
3328 // lots of syntax errors if $nt is not an object
3329 return array( array( 'badtitletext' ) );
3331 if ( $this->equals( $nt ) ) {
3332 $errors[] = array( 'selfmove' );
3334 if ( !$this->isMovable() ) {
3335 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3337 if ( $nt->getInterwiki() != '' ) {
3338 $errors[] = array( 'immobile-target-namespace-iw' );
3340 if ( !$nt->isMovable() ) {
3341 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3344 $oldid = $this->getArticleID();
3345 $newid = $nt->getArticleID();
3347 if ( strlen( $nt->getDBkey() ) < 1 ) {
3348 $errors[] = array( 'articleexists' );
3350 if ( ( $this->getDBkey() == '' ) ||
3352 ( $nt->getDBkey() == '' ) ) {
3353 $errors[] = array( 'badarticleerror' );
3356 // Image-specific checks
3357 if ( $this->getNamespace() == NS_FILE
) {
3358 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3361 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3362 $errors[] = array( 'nonfile-cannot-move-to-file' );
3366 $errors = wfMergeErrorArrays( $errors,
3367 $this->getUserPermissionsErrors( 'move', $wgUser ),
3368 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3369 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3370 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3373 $match = EditPage
::matchSummarySpamRegex( $reason );
3374 if ( $match !== false ) {
3375 // This is kind of lame, won't display nice
3376 $errors[] = array( 'spamprotectiontext' );
3380 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3381 $errors[] = array( 'hookaborted', $err );
3384 # The move is allowed only if (1) the target doesn't exist, or
3385 # (2) the target is a redirect to the source, and has no history
3386 # (so we can undo bad moves right after they're done).
3388 if ( 0 != $newid ) { # Target exists; check for validity
3389 if ( !$this->isValidMoveTarget( $nt ) ) {
3390 $errors[] = array( 'articleexists' );
3393 $tp = $nt->getTitleProtection();
3394 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3395 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3396 $errors[] = array( 'cantmove-titleprotected' );
3399 if ( empty( $errors ) ) {
3406 * Check if the requested move target is a valid file move target
3407 * @param Title $nt Target title
3408 * @return array List of errors
3410 protected function validateFileMoveOperation( $nt ) {
3415 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3417 $file = wfLocalFile( $this );
3418 if ( $file->exists() ) {
3419 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3420 $errors[] = array( 'imageinvalidfilename' );
3422 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3423 $errors[] = array( 'imagetypemismatch' );
3427 if ( $nt->getNamespace() != NS_FILE
) {
3428 $errors[] = array( 'imagenocrossnamespace' );
3429 // From here we want to do checks on a file object, so if we can't
3430 // create one, we must return.
3434 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3436 $destFile = wfLocalFile( $nt );
3437 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3438 $errors[] = array( 'file-exists-sharedrepo' );
3445 * Move a title to a new location
3447 * @param $nt Title the new title
3448 * @param $auth Bool indicates whether $wgUser's permissions
3450 * @param $reason String the reason for the move
3451 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3452 * Ignored if the user doesn't have the suppressredirect right.
3453 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3455 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3457 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3458 if ( is_array( $err ) ) {
3459 // Auto-block user's IP if the account was "hard" blocked
3460 $wgUser->spreadAnyEditBlock();
3464 // If it is a file, move it first.
3465 // It is done before all other moving stuff is done because it's hard to revert.
3466 $dbw = wfGetDB( DB_MASTER
);
3467 if ( $this->getNamespace() == NS_FILE
) {
3468 $file = wfLocalFile( $this );
3469 if ( $file->exists() ) {
3470 $status = $file->move( $nt );
3471 if ( !$status->isOk() ) {
3472 return $status->getErrorsArray();
3475 // Clear RepoGroup process cache
3476 RepoGroup
::singleton()->clearCache( $this );
3477 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3480 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3481 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3482 $protected = $this->isProtected();
3484 // Do the actual move
3485 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3486 if ( is_array( $err ) ) {
3487 # @todo FIXME: What about the File we have already moved?
3492 // Refresh the sortkey for this row. Be careful to avoid resetting
3493 // cl_timestamp, which may disturb time-based lists on some sites.
3494 $prefixes = $dbw->select(
3496 array( 'cl_sortkey_prefix', 'cl_to' ),
3497 array( 'cl_from' => $pageid ),
3500 foreach ( $prefixes as $prefixRow ) {
3501 $prefix = $prefixRow->cl_sortkey_prefix
;
3502 $catTo = $prefixRow->cl_to
;
3503 $dbw->update( 'categorylinks',
3505 'cl_sortkey' => Collation
::singleton()->getSortKey(
3506 $nt->getCategorySortkey( $prefix ) ),
3507 'cl_timestamp=cl_timestamp' ),
3509 'cl_from' => $pageid,
3510 'cl_to' => $catTo ),
3515 $redirid = $this->getArticleID();
3518 # Protect the redirect title as the title used to be...
3519 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3521 'pr_page' => $redirid,
3522 'pr_type' => 'pr_type',
3523 'pr_level' => 'pr_level',
3524 'pr_cascade' => 'pr_cascade',
3525 'pr_user' => 'pr_user',
3526 'pr_expiry' => 'pr_expiry'
3528 array( 'pr_page' => $pageid ),
3532 # Update the protection log
3533 $log = new LogPage( 'protect' );
3534 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3536 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3538 // @todo FIXME: $params?
3539 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3543 $oldnamespace = $this->getNamespace() & ~
1;
3544 $newnamespace = $nt->getNamespace() & ~
1;
3545 $oldtitle = $this->getDBkey();
3546 $newtitle = $nt->getDBkey();
3548 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3549 WatchedItem
::duplicateEntries( $this, $nt );
3554 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3559 * Move page to a title which is either a redirect to the
3560 * source page or nonexistent
3562 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3563 * @param $reason String The reason for the move
3564 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3565 * if the user doesn't have the suppressredirect right
3567 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3568 global $wgUser, $wgContLang;
3570 if ( $nt->exists() ) {
3571 $moveOverRedirect = true;
3572 $logType = 'move_redir';
3574 $moveOverRedirect = false;
3578 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3580 $logEntry = new ManualLogEntry( 'move', $logType );
3581 $logEntry->setPerformer( $wgUser );
3582 $logEntry->setTarget( $this );
3583 $logEntry->setComment( $reason );
3584 $logEntry->setParameters( array(
3585 '4::target' => $nt->getPrefixedText(),
3586 '5::noredir' => $redirectSuppressed ?
'1': '0',
3589 $formatter = LogFormatter
::newFromEntry( $logEntry );
3590 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3591 $comment = $formatter->getPlainActionText();
3593 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3595 # Truncate for whole multibyte characters.
3596 $comment = $wgContLang->truncate( $comment, 255 );
3598 $oldid = $this->getArticleID();
3599 $latest = $this->getLatestRevID();
3601 $dbw = wfGetDB( DB_MASTER
);
3603 $newpage = WikiPage
::factory( $nt );
3605 if ( $moveOverRedirect ) {
3606 $newid = $nt->getArticleID();
3608 # Delete the old redirect. We don't save it to history since
3609 # by definition if we've got here it's rather uninteresting.
3610 # We have to remove it so that the next step doesn't trigger
3611 # a conflict on the unique namespace+title index...
3612 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3614 $newpage->doDeleteUpdates( $newid );
3617 # Save a null revision in the page's history notifying of the move
3618 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3619 if ( !is_object( $nullRevision ) ) {
3620 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3622 $nullRevId = $nullRevision->insertOn( $dbw );
3624 # Change the name of the target page:
3625 $dbw->update( 'page',
3627 'page_namespace' => $nt->getNamespace(),
3628 'page_title' => $nt->getDBkey(),
3630 /* WHERE */ array( 'page_id' => $oldid ),
3634 $this->resetArticleID( 0 );
3635 $nt->resetArticleID( $oldid );
3637 $newpage->updateRevisionOn( $dbw, $nullRevision );
3639 wfRunHooks( 'NewRevisionFromEditComplete',
3640 array( $newpage, $nullRevision, $latest, $wgUser ) );
3642 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3644 # Recreate the redirect, this time in the other direction.
3645 if ( $redirectSuppressed ) {
3646 WikiPage
::onArticleDelete( $this );
3648 $mwRedir = MagicWord
::get( 'redirect' );
3649 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3650 $redirectArticle = WikiPage
::factory( $this );
3651 $newid = $redirectArticle->insertOn( $dbw );
3652 if ( $newid ) { // sanity
3653 $redirectRevision = new Revision( array(
3655 'comment' => $comment,
3656 'text' => $redirectText ) );
3657 $redirectRevision->insertOn( $dbw );
3658 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3660 wfRunHooks( 'NewRevisionFromEditComplete',
3661 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3663 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3668 $logid = $logEntry->insert();
3669 $logEntry->publish( $logid );
3673 * Move this page's subpages to be subpages of $nt
3675 * @param $nt Title Move target
3676 * @param $auth bool Whether $wgUser's permissions should be checked
3677 * @param $reason string The reason for the move
3678 * @param $createRedirect bool Whether to create redirects from the old subpages to
3679 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3680 * @return mixed array with old page titles as keys, and strings (new page titles) or
3681 * arrays (errors) as values, or an error array with numeric indices if no pages
3684 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3685 global $wgMaximumMovedPages;
3686 // Check permissions
3687 if ( !$this->userCan( 'move-subpages' ) ) {
3688 return array( 'cant-move-subpages' );
3690 // Do the source and target namespaces support subpages?
3691 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3692 return array( 'namespace-nosubpages',
3693 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3695 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3696 return array( 'namespace-nosubpages',
3697 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3700 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3703 foreach ( $subpages as $oldSubpage ) {
3705 if ( $count > $wgMaximumMovedPages ) {
3706 $retval[$oldSubpage->getPrefixedTitle()] =
3707 array( 'movepage-max-pages',
3708 $wgMaximumMovedPages );
3712 // We don't know whether this function was called before
3713 // or after moving the root page, so check both
3715 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3716 $oldSubpage->getArticleID() == $nt->getArticleId() )
3718 // When moving a page to a subpage of itself,
3719 // don't move it twice
3722 $newPageName = preg_replace(
3723 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3724 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3725 $oldSubpage->getDBkey() );
3726 if ( $oldSubpage->isTalkPage() ) {
3727 $newNs = $nt->getTalkPage()->getNamespace();
3729 $newNs = $nt->getSubjectPage()->getNamespace();
3731 # Bug 14385: we need makeTitleSafe because the new page names may
3732 # be longer than 255 characters.
3733 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3735 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3736 if ( $success === true ) {
3737 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3739 $retval[$oldSubpage->getPrefixedText()] = $success;
3746 * Checks if this page is just a one-rev redirect.
3747 * Adds lock, so don't use just for light purposes.
3751 public function isSingleRevRedirect() {
3752 $dbw = wfGetDB( DB_MASTER
);
3754 $row = $dbw->selectRow( 'page',
3755 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3758 array( 'FOR UPDATE' )
3760 # Cache some fields we may want
3761 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3762 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3763 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3764 if ( !$this->mRedirect
) {
3767 # Does the article have a history?
3768 $row = $dbw->selectField( array( 'page', 'revision' ),
3770 array( 'page_namespace' => $this->getNamespace(),
3771 'page_title' => $this->getDBkey(),
3773 'page_latest != rev_id'
3776 array( 'FOR UPDATE' )
3778 # Return true if there was no history
3779 return ( $row === false );
3783 * Checks if $this can be moved to a given Title
3784 * - Selects for update, so don't call it unless you mean business
3786 * @param $nt Title the new title to check
3789 public function isValidMoveTarget( $nt ) {
3790 # Is it an existing file?
3791 if ( $nt->getNamespace() == NS_FILE
) {
3792 $file = wfLocalFile( $nt );
3793 if ( $file->exists() ) {
3794 wfDebug( __METHOD__
. ": file exists\n" );
3798 # Is it a redirect with no history?
3799 if ( !$nt->isSingleRevRedirect() ) {
3800 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3803 # Get the article text
3804 $rev = Revision
::newFromTitle( $nt );
3805 if( !is_object( $rev ) ){
3808 $text = $rev->getText();
3809 # Does the redirect point to the source?
3810 # Or is it a broken self-redirect, usually caused by namespace collisions?
3812 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3813 $redirTitle = Title
::newFromText( $m[1] );
3814 if ( !is_object( $redirTitle ) ||
3815 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3816 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3817 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3822 wfDebug( __METHOD__
. ": failsafe\n" );
3829 * Get categories to which this Title belongs and return an array of
3830 * categories' names.
3832 * @return Array of parents in the form:
3833 * $parent => $currentarticle
3835 public function getParentCategories() {
3840 $titleKey = $this->getArticleId();
3842 if ( $titleKey === 0 ) {
3846 $dbr = wfGetDB( DB_SLAVE
);
3848 $res = $dbr->select( 'categorylinks', '*',
3850 'cl_from' => $titleKey,
3856 if ( $dbr->numRows( $res ) > 0 ) {
3857 foreach ( $res as $row ) {
3858 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3859 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3866 * Get a tree of parent categories
3868 * @param $children Array with the children in the keys, to check for circular refs
3869 * @return Array Tree of parent categories
3871 public function getParentCategoryTree( $children = array() ) {
3873 $parents = $this->getParentCategories();
3876 foreach ( $parents as $parent => $current ) {
3877 if ( array_key_exists( $parent, $children ) ) {
3878 # Circular reference
3879 $stack[$parent] = array();
3881 $nt = Title
::newFromText( $parent );
3883 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3893 * Get an associative array for selecting this title from
3896 * @return Array suitable for the $where parameter of DB::select()
3898 public function pageCond() {
3899 if ( $this->mArticleID
> 0 ) {
3900 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3901 return array( 'page_id' => $this->mArticleID
);
3903 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3908 * Get the revision ID of the previous revision
3910 * @param $revId Int Revision ID. Get the revision that was before this one.
3911 * @param $flags Int Title::GAID_FOR_UPDATE
3912 * @return Int|Bool Old revision ID, or FALSE if none exists
3914 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3915 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3916 return $db->selectField( 'revision', 'rev_id',
3918 'rev_page' => $this->getArticleId( $flags ),
3919 'rev_id < ' . intval( $revId )
3922 array( 'ORDER BY' => 'rev_id DESC' )
3927 * Get the revision ID of the next revision
3929 * @param $revId Int Revision ID. Get the revision that was after this one.
3930 * @param $flags Int Title::GAID_FOR_UPDATE
3931 * @return Int|Bool Next revision ID, or FALSE if none exists
3933 public function getNextRevisionID( $revId, $flags = 0 ) {
3934 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3935 return $db->selectField( 'revision', 'rev_id',
3937 'rev_page' => $this->getArticleId( $flags ),
3938 'rev_id > ' . intval( $revId )
3941 array( 'ORDER BY' => 'rev_id' )
3946 * Get the first revision of the page
3948 * @param $flags Int Title::GAID_FOR_UPDATE
3949 * @return Revision|Null if page doesn't exist
3951 public function getFirstRevision( $flags = 0 ) {
3952 $pageId = $this->getArticleId( $flags );
3954 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3955 $row = $db->selectRow( 'revision', '*',
3956 array( 'rev_page' => $pageId ),
3958 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3961 return new Revision( $row );
3968 * Get the oldest revision timestamp of this page
3970 * @param $flags Int Title::GAID_FOR_UPDATE
3971 * @return String: MW timestamp
3973 public function getEarliestRevTime( $flags = 0 ) {
3974 $rev = $this->getFirstRevision( $flags );
3975 return $rev ?
$rev->getTimestamp() : null;
3979 * Check if this is a new page
3983 public function isNewPage() {
3984 $dbr = wfGetDB( DB_SLAVE
);
3985 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3989 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3993 public function isBigDeletion() {
3994 global $wgDeleteRevisionsLimit;
3996 if ( !$wgDeleteRevisionsLimit ) {
4000 $revCount = $this->estimateRevisionCount();
4001 return $revCount > $wgDeleteRevisionsLimit;
4005 * Get the approximate revision count of this page.
4009 public function estimateRevisionCount() {
4010 if ( !$this->exists() ) {
4014 if ( $this->mEstimateRevisions
=== null ) {
4015 $dbr = wfGetDB( DB_SLAVE
);
4016 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4017 array( 'rev_page' => $this->getArticleId() ), __METHOD__
);
4020 return $this->mEstimateRevisions
;
4024 * Get the number of revisions between the given revision.
4025 * Used for diffs and other things that really need it.
4027 * @param $old int|Revision Old revision or rev ID (first before range)
4028 * @param $new int|Revision New revision or rev ID (first after range)
4029 * @return Int Number of revisions between these revisions.
4031 public function countRevisionsBetween( $old, $new ) {
4032 if ( !( $old instanceof Revision
) ) {
4033 $old = Revision
::newFromTitle( $this, (int)$old );
4035 if ( !( $new instanceof Revision
) ) {
4036 $new = Revision
::newFromTitle( $this, (int)$new );
4038 if ( !$old ||
!$new ) {
4039 return 0; // nothing to compare
4041 $dbr = wfGetDB( DB_SLAVE
);
4042 return (int)$dbr->selectField( 'revision', 'count(*)',
4044 'rev_page' => $this->getArticleId(),
4045 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4046 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4053 * Get the number of authors between the given revision IDs.
4054 * Used for diffs and other things that really need it.
4056 * @param $old int|Revision Old revision or rev ID (first before range)
4057 * @param $new int|Revision New revision or rev ID (first after range)
4058 * @param $limit Int Maximum number of authors
4059 * @return Int Number of revision authors between these revisions.
4061 public function countAuthorsBetween( $old, $new, $limit ) {
4062 if ( !( $old instanceof Revision
) ) {
4063 $old = Revision
::newFromTitle( $this, (int)$old );
4065 if ( !( $new instanceof Revision
) ) {
4066 $new = Revision
::newFromTitle( $this, (int)$new );
4068 if ( !$old ||
!$new ) {
4069 return 0; // nothing to compare
4071 $dbr = wfGetDB( DB_SLAVE
);
4072 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4074 'rev_page' => $this->getArticleID(),
4075 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4076 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4078 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4080 return (int)$dbr->numRows( $res );
4084 * Compare with another title.
4086 * @param $title Title
4089 public function equals( Title
$title ) {
4090 // Note: === is necessary for proper matching of number-like titles.
4091 return $this->getInterwiki() === $title->getInterwiki()
4092 && $this->getNamespace() == $title->getNamespace()
4093 && $this->getDBkey() === $title->getDBkey();
4097 * Check if this title is a subpage of another title
4099 * @param $title Title
4102 public function isSubpageOf( Title
$title ) {
4103 return $this->getInterwiki() === $title->getInterwiki()
4104 && $this->getNamespace() == $title->getNamespace()
4105 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4109 * Check if page exists. For historical reasons, this function simply
4110 * checks for the existence of the title in the page table, and will
4111 * thus return false for interwiki links, special pages and the like.
4112 * If you want to know if a title can be meaningfully viewed, you should
4113 * probably call the isKnown() method instead.
4117 public function exists() {
4118 return $this->getArticleId() != 0;
4122 * Should links to this title be shown as potentially viewable (i.e. as
4123 * "bluelinks"), even if there's no record by this title in the page
4126 * This function is semi-deprecated for public use, as well as somewhat
4127 * misleadingly named. You probably just want to call isKnown(), which
4128 * calls this function internally.
4130 * (ISSUE: Most of these checks are cheap, but the file existence check
4131 * can potentially be quite expensive. Including it here fixes a lot of
4132 * existing code, but we might want to add an optional parameter to skip
4133 * it and any other expensive checks.)
4137 public function isAlwaysKnown() {
4138 if ( $this->mInterwiki
!= '' ) {
4139 return true; // any interwiki link might be viewable, for all we know
4141 switch( $this->mNamespace
) {
4144 // file exists, possibly in a foreign repo
4145 return (bool)wfFindFile( $this );
4147 // valid special page
4148 return SpecialPageFactory
::exists( $this->getDBkey() );
4150 // selflink, possibly with fragment
4151 return $this->mDbkeyform
== '';
4153 // known system message
4154 return $this->hasSourceText() !== false;
4161 * Does this title refer to a page that can (or might) be meaningfully
4162 * viewed? In particular, this function may be used to determine if
4163 * links to the title should be rendered as "bluelinks" (as opposed to
4164 * "redlinks" to non-existent pages).
4168 public function isKnown() {
4172 * Allows overriding default behaviour for determining if a page exists.
4173 * If $isKnown is kept as null, regular checks happen. If it's
4174 * a boolean, this value is returned by the isKnown method.
4178 * @param Title $title
4179 * @param boolean|null $isKnown
4181 wfRunHooks( 'TitleIsKnown', array( $this, &$isKnown ) );
4183 return is_null( $isKnown ) ?
( $this->isAlwaysKnown() ||
$this->exists() ) : $isKnown;
4187 * Does this page have source text?
4191 public function hasSourceText() {
4192 if ( $this->exists() ) {
4196 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4197 // If the page doesn't exist but is a known system message, default
4198 // message content will be displayed, same for language subpages-
4199 // Use always content language to avoid loading hundreds of languages
4200 // to get the link color.
4202 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4203 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4204 return $message->exists();
4211 * Get the default message text or false if the message doesn't exist
4213 * @return String or false
4215 public function getDefaultMessageText() {
4218 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4222 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4223 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4225 if ( $message->exists() ) {
4226 return $message->plain();
4233 * Updates page_touched for this page; called from LinksUpdate.php
4235 * @return Bool true if the update succeded
4237 public function invalidateCache() {
4238 if ( wfReadOnly() ) {
4241 $dbw = wfGetDB( DB_MASTER
);
4242 $success = $dbw->update(
4244 array( 'page_touched' => $dbw->timestamp() ),
4248 HTMLFileCache
::clearFileCache( $this );
4253 * Update page_touched timestamps and send squid purge messages for
4254 * pages linking to this title. May be sent to the job queue depending
4255 * on the number of links. Typically called on create and delete.
4257 public function touchLinks() {
4258 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4261 if ( $this->getNamespace() == NS_CATEGORY
) {
4262 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4268 * Get the last touched timestamp
4270 * @param $db DatabaseBase: optional db
4271 * @return String last-touched timestamp
4273 public function getTouched( $db = null ) {
4274 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4275 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4280 * Get the timestamp when this page was updated since the user last saw it.
4283 * @return String|Null
4285 public function getNotificationTimestamp( $user = null ) {
4286 global $wgUser, $wgShowUpdatedMarker;
4287 // Assume current user if none given
4291 // Check cache first
4292 $uid = $user->getId();
4293 // avoid isset here, as it'll return false for null entries
4294 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4295 return $this->mNotificationTimestamp
[$uid];
4297 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4298 return $this->mNotificationTimestamp
[$uid] = false;
4300 // Don't cache too much!
4301 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4302 $this->mNotificationTimestamp
= array();
4304 $dbr = wfGetDB( DB_SLAVE
);
4305 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4306 'wl_notificationtimestamp',
4307 array( 'wl_namespace' => $this->getNamespace(),
4308 'wl_title' => $this->getDBkey(),
4309 'wl_user' => $user->getId()
4313 return $this->mNotificationTimestamp
[$uid];
4317 * Generate strings used for xml 'id' names in monobook tabs
4319 * @param $prepend string defaults to 'nstab-'
4320 * @return String XML 'id' name
4322 public function getNamespaceKey( $prepend = 'nstab-' ) {
4324 // Gets the subject namespace if this title
4325 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4326 // Checks if cononical namespace name exists for namespace
4327 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4328 // Uses canonical namespace name
4329 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4331 // Uses text of namespace
4332 $namespaceKey = $this->getSubjectNsText();
4334 // Makes namespace key lowercase
4335 $namespaceKey = $wgContLang->lc( $namespaceKey );
4337 if ( $namespaceKey == '' ) {
4338 $namespaceKey = 'main';
4340 // Changes file to image for backwards compatibility
4341 if ( $namespaceKey == 'file' ) {
4342 $namespaceKey = 'image';
4344 return $prepend . $namespaceKey;
4348 * Get all extant redirects to this Title
4350 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4351 * @return Array of Title redirects to this title
4353 public function getRedirectsHere( $ns = null ) {
4356 $dbr = wfGetDB( DB_SLAVE
);
4358 'rd_namespace' => $this->getNamespace(),
4359 'rd_title' => $this->getDBkey(),
4362 if ( !is_null( $ns ) ) {
4363 $where['page_namespace'] = $ns;
4366 $res = $dbr->select(
4367 array( 'redirect', 'page' ),
4368 array( 'page_namespace', 'page_title' ),
4373 foreach ( $res as $row ) {
4374 $redirs[] = self
::newFromRow( $row );
4380 * Check if this Title is a valid redirect target
4384 public function isValidRedirectTarget() {
4385 global $wgInvalidRedirectTargets;
4387 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4388 if ( $this->isSpecial( 'Userlogout' ) ) {
4392 foreach ( $wgInvalidRedirectTargets as $target ) {
4393 if ( $this->isSpecial( $target ) ) {
4402 * Get a backlink cache object
4404 * @return BacklinkCache
4406 function getBacklinkCache() {
4407 if ( is_null( $this->mBacklinkCache
) ) {
4408 $this->mBacklinkCache
= new BacklinkCache( $this );
4410 return $this->mBacklinkCache
;
4414 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4418 public function canUseNoindex() {
4419 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4421 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4422 ?
$wgContentNamespaces
4423 : $wgExemptFromUserRobotsControl;
4425 return !in_array( $this->mNamespace
, $bannedNamespaces );
4430 * Returns the raw sort key to be used for categories, with the specified
4431 * prefix. This will be fed to Collation::getSortKey() to get a
4432 * binary sortkey that can be used for actual sorting.
4434 * @param $prefix string The prefix to be used, specified using
4435 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4439 public function getCategorySortkey( $prefix = '' ) {
4440 $unprefixed = $this->getText();
4442 // Anything that uses this hook should only depend
4443 // on the Title object passed in, and should probably
4444 // tell the users to run updateCollations.php --force
4445 // in order to re-sort existing category relations.
4446 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4447 if ( $prefix !== '' ) {
4448 # Separate with a line feed, so the unprefixed part is only used as
4449 # a tiebreaker when two pages have the exact same prefix.
4450 # In UCA, tab is the only character that can sort above LF
4451 # so we strip both of them from the original prefix.
4452 $prefix = strtr( $prefix, "\n\t", ' ' );
4453 return "$prefix\n$unprefixed";
4459 * Get the language in which the content of this page is written.
4460 * Defaults to $wgContLang, but in certain cases it can be e.g.
4461 * $wgLang (such as special pages, which are in the user language).
4464 * @return object Language
4466 public function getPageLanguage() {
4468 if ( $this->isSpecialPage() ) {
4469 // special pages are in the user language
4471 } elseif ( $this->isCssOrJsPage() ) {
4472 // css/js should always be LTR and is, in fact, English
4473 return wfGetLangObj( 'en' );
4474 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4475 // Parse mediawiki messages with correct target language
4476 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4477 return wfGetLangObj( $lang );
4480 // If nothing special, it should be in the wiki content language
4481 $pageLang = $wgContLang;
4482 // Hook at the end because we don't want to override the above stuff
4483 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4484 return wfGetLangObj( $pageLang );