3 * Representation a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
31 * @internal documentation reviewed 15 Mar 2010
34 /** @name Static cache variables */
36 static private $titleCache = array();
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
69 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
70 var $mOldRestrictions = false;
71 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
72 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
73 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
74 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
75 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
76 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
77 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
78 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
79 # Don't change the following default, NS_MAIN is hardcoded in several
80 # places. See bug 696.
81 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
82 # Zero except in {{transclusion}} tags
83 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
84 var $mLength = -1; // /< The page length, 0 for special pages
85 var $mRedirect = null; // /< Is the article at this title a redirect?
86 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
87 var $mHasSubpage; // /< Whether a page has any subpages
94 /*protected*/ function __construct() { }
97 * Create a new Title from a prefixed DB key
99 * @param $key String the database key, which has underscores
100 * instead of spaces, possibly including namespace and
102 * @return Title, or NULL on an error
104 public static function newFromDBkey( $key ) {
106 $t->mDbkeyform
= $key;
107 if ( $t->secureAndSplit() ) {
115 * Create a new Title from text, such as what one would find in a link. De-
116 * codes any HTML entities in the text.
118 * @param $text String the link text; spaces, prefixes, and an
119 * initial ':' indicating the main namespace are accepted.
120 * @param $defaultNamespace Int the namespace to use if none is speci-
121 * fied by a prefix. If you want to force a specific namespace even if
122 * $text might begin with a namespace prefix, use makeTitle() or
124 * @throws MWException
125 * @return Title|null - Title or null on an error.
127 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
128 if ( is_object( $text ) ) {
129 throw new MWException( 'Title::newFromText given an object' );
133 * Wiki pages often contain multiple links to the same page.
134 * Title normalization and parsing can become expensive on
135 * pages with many links, so we can save a little time by
138 * In theory these are value objects and won't get changed...
140 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
141 return Title
::$titleCache[$text];
144 # Convert things like é ā or 〗 into normalized (bug 14952) text
145 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
148 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
149 $t->mDefaultNamespace
= $defaultNamespace;
151 static $cachedcount = 0 ;
152 if ( $t->secureAndSplit() ) {
153 if ( $defaultNamespace == NS_MAIN
) {
154 if ( $cachedcount >= self
::CACHE_MAX
) {
155 # Avoid memory leaks on mass operations...
156 Title
::$titleCache = array();
160 Title
::$titleCache[$text] =& $t;
170 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
172 * Example of wrong and broken code:
173 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
175 * Example of right code:
176 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
178 * Create a new Title from URL-encoded text. Ensures that
179 * the given title's length does not exceed the maximum.
181 * @param $url String the title, as might be taken from a URL
182 * @return Title the new object, or NULL on an error
184 public static function newFromURL( $url ) {
187 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
188 # but some URLs used it as a space replacement and they still come
189 # from some external search tools.
190 if ( strpos( self
::legalChars(), '+' ) === false ) {
191 $url = str_replace( '+', ' ', $url );
194 $t->mDbkeyform
= str_replace( ' ', '_', $url );
195 if ( $t->secureAndSplit() ) {
203 * Create a new Title from an article ID
205 * @param $id Int the page_id corresponding to the Title to create
206 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
207 * @return Title the new object, or NULL on an error
209 public static function newFromID( $id, $flags = 0 ) {
210 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
211 $row = $db->selectRow(
214 'page_namespace', 'page_title', 'page_id',
215 'page_len', 'page_is_redirect', 'page_latest',
217 array( 'page_id' => $id ),
220 if ( $row !== false ) {
221 $title = Title
::newFromRow( $row );
229 * Make an array of titles from an array of IDs
231 * @param $ids Array of Int Array of IDs
232 * @return Array of Titles
234 public static function newFromIDs( $ids ) {
235 if ( !count( $ids ) ) {
238 $dbr = wfGetDB( DB_SLAVE
);
243 'page_namespace', 'page_title', 'page_id',
244 'page_len', 'page_is_redirect', 'page_latest',
246 array( 'page_id' => $ids ),
251 foreach ( $res as $row ) {
252 $titles[] = Title
::newFromRow( $row );
258 * Make a Title object from a DB row
260 * @param $row Object database row (needs at least page_title,page_namespace)
261 * @return Title corresponding Title
263 public static function newFromRow( $row ) {
264 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
265 $t->loadFromRow( $row );
270 * Load Title object fields from a DB row.
271 * If false is given, the title will be treated as non-existing.
273 * @param $row Object|bool database row
275 public function loadFromRow( $row ) {
276 if ( $row ) { // page found
277 if ( isset( $row->page_id
) )
278 $this->mArticleID
= (int)$row->page_id
;
279 if ( isset( $row->page_len
) )
280 $this->mLength
= (int)$row->page_len
;
281 if ( isset( $row->page_is_redirect
) )
282 $this->mRedirect
= (bool)$row->page_is_redirect
;
283 if ( isset( $row->page_latest
) )
284 $this->mLatestID
= (int)$row->page_latest
;
285 } else { // page not found
286 $this->mArticleID
= 0;
288 $this->mRedirect
= false;
289 $this->mLatestID
= 0;
294 * Create a new Title from a namespace index and a DB key.
295 * It's assumed that $ns and $title are *valid*, for instance when
296 * they came directly from the database or a special page name.
297 * For convenience, spaces are converted to underscores so that
298 * eg user_text fields can be used directly.
300 * @param $ns Int the namespace of the article
301 * @param $title String the unprefixed database key form
302 * @param $fragment String the link fragment (after the "#")
303 * @param $interwiki String the interwiki prefix
304 * @return Title the new object
306 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
308 $t->mInterwiki
= $interwiki;
309 $t->mFragment
= $fragment;
310 $t->mNamespace
= $ns = intval( $ns );
311 $t->mDbkeyform
= str_replace( ' ', '_', $title );
312 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
313 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
314 $t->mTextform
= str_replace( '_', ' ', $title );
319 * Create a new Title from a namespace index and a DB key.
320 * The parameters will be checked for validity, which is a bit slower
321 * than makeTitle() but safer for user-provided data.
323 * @param $ns Int the namespace of the article
324 * @param $title String database key form
325 * @param $fragment String the link fragment (after the "#")
326 * @param $interwiki String interwiki prefix
327 * @return Title the new object, or NULL on an error
329 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
330 if ( !MWNamespace
::exists( $ns ) ) {
335 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
336 if ( $t->secureAndSplit() ) {
344 * Create a new Title for the Main Page
346 * @return Title the new object
348 public static function newMainPage() {
349 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
350 // Don't give fatal errors if the message is broken
352 $title = Title
::newFromText( 'Main Page' );
358 * Extract a redirect destination from a string and return the
359 * Title, or null if the text doesn't contain a valid redirect
360 * This will only return the very next target, useful for
361 * the redirect table and other checks that don't need full recursion
363 * @param $text String: Text with possible redirect
364 * @return Title: The corresponding Title
366 public static function newFromRedirect( $text ) {
367 return self
::newFromRedirectInternal( $text );
371 * Extract a redirect destination from a string and return the
372 * Title, or null if the text doesn't contain a valid redirect
373 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
374 * in order to provide (hopefully) the Title of the final destination instead of another redirect
376 * @param $text String Text with possible redirect
379 public static function newFromRedirectRecurse( $text ) {
380 $titles = self
::newFromRedirectArray( $text );
381 return $titles ?
array_pop( $titles ) : null;
385 * Extract a redirect destination from a string and return an
386 * array of Titles, or null if the text doesn't contain a valid redirect
387 * The last element in the array is the final destination after all redirects
388 * have been resolved (up to $wgMaxRedirects times)
390 * @param $text String Text with possible redirect
391 * @return Array of Titles, with the destination last
393 public static function newFromRedirectArray( $text ) {
394 global $wgMaxRedirects;
395 $title = self
::newFromRedirectInternal( $text );
396 if ( is_null( $title ) ) {
399 // recursive check to follow double redirects
400 $recurse = $wgMaxRedirects;
401 $titles = array( $title );
402 while ( --$recurse > 0 ) {
403 if ( $title->isRedirect() ) {
404 $page = WikiPage
::factory( $title );
405 $newtitle = $page->getRedirectTarget();
409 // Redirects to some special pages are not permitted
410 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
411 // the new title passes the checks, so make that our current title so that further recursion can be checked
413 $titles[] = $newtitle;
422 * Really extract the redirect destination
423 * Do not call this function directly, use one of the newFromRedirect* functions above
425 * @param $text String Text with possible redirect
428 protected static function newFromRedirectInternal( $text ) {
429 global $wgMaxRedirects;
430 if ( $wgMaxRedirects < 1 ) {
431 //redirects are disabled, so quit early
434 $redir = MagicWord
::get( 'redirect' );
435 $text = trim( $text );
436 if ( $redir->matchStartAndRemove( $text ) ) {
437 // Extract the first link and see if it's usable
438 // Ensure that it really does come directly after #REDIRECT
439 // Some older redirects included a colon, so don't freak about that!
441 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
442 // Strip preceding colon used to "escape" categories, etc.
443 // and URL-decode links
444 if ( strpos( $m[1], '%' ) !== false ) {
445 // Match behavior of inline link parsing here;
446 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
448 $title = Title
::newFromText( $m[1] );
449 // If the title is a redirect to bad special pages or is invalid, return null
450 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
460 * Get the prefixed DB key associated with an ID
462 * @param $id Int the page_id of the article
463 * @return Title an object representing the article, or NULL if no such article was found
465 public static function nameOf( $id ) {
466 $dbr = wfGetDB( DB_SLAVE
);
468 $s = $dbr->selectRow(
470 array( 'page_namespace', 'page_title' ),
471 array( 'page_id' => $id ),
474 if ( $s === false ) {
478 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
483 * Get a regex character class describing the legal characters in a link
485 * @return String the list of characters, not delimited
487 public static function legalChars() {
488 global $wgLegalTitleChars;
489 return $wgLegalTitleChars;
493 * Returns a simple regex that will match on characters and sequences invalid in titles.
494 * Note that this doesn't pick up many things that could be wrong with titles, but that
495 * replacing this regex with something valid will make many titles valid.
497 * @return String regex string
499 static function getTitleInvalidRegex() {
500 static $rxTc = false;
502 # Matching titles will be held as illegal.
504 # Any character not allowed is forbidden...
505 '[^' . self
::legalChars() . ']' .
506 # URL percent encoding sequences interfere with the ability
507 # to round-trip titles -- you can't link to them consistently.
509 # XML/HTML character references produce similar issues.
510 '|&[A-Za-z0-9\x80-\xff]+;' .
512 '|&#x[0-9A-Fa-f]+;' .
520 * Get a string representation of a title suitable for
521 * including in a search index
523 * @param $ns Int a namespace index
524 * @param $title String text-form main part
525 * @return String a stripped-down title string ready for the search index
527 public static function indexTitle( $ns, $title ) {
530 $lc = SearchEngine
::legalSearchChars() . '&#;';
531 $t = $wgContLang->normalizeForSearch( $title );
532 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
533 $t = $wgContLang->lc( $t );
536 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
537 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
539 $t = preg_replace( "/\\s+/", ' ', $t );
541 if ( $ns == NS_FILE
) {
542 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
548 * Make a prefixed DB key from a DB key and a namespace index
550 * @param $ns Int numerical representation of the namespace
551 * @param $title String the DB key form the title
552 * @param $fragment String The link fragment (after the "#")
553 * @param $interwiki String The interwiki prefix
554 * @return String the prefixed form of the title
556 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
559 $namespace = $wgContLang->getNsText( $ns );
560 $name = $namespace == '' ?
$title : "$namespace:$title";
561 if ( strval( $interwiki ) != '' ) {
562 $name = "$interwiki:$name";
564 if ( strval( $fragment ) != '' ) {
565 $name .= '#' . $fragment;
571 * Escape a text fragment, say from a link, for a URL
573 * @param $fragment string containing a URL or link fragment (after the "#")
574 * @return String: escaped string
576 static function escapeFragmentForURL( $fragment ) {
577 # Note that we don't urlencode the fragment. urlencoded Unicode
578 # fragments appear not to work in IE (at least up to 7) or in at least
579 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
580 # to care if they aren't encoded.
581 return Sanitizer
::escapeId( $fragment, 'noninitial' );
585 * Callback for usort() to do title sorts by (namespace, title)
590 * @return Integer: result of string comparison, or namespace comparison
592 public static function compare( $a, $b ) {
593 if ( $a->getNamespace() == $b->getNamespace() ) {
594 return strcmp( $a->getText(), $b->getText() );
596 return $a->getNamespace() - $b->getNamespace();
601 * Determine whether the object refers to a page within
604 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
606 public function isLocal() {
607 if ( $this->mInterwiki
!= '' ) {
608 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
615 * Is this Title interwiki?
619 public function isExternal() {
620 return ( $this->mInterwiki
!= '' );
624 * Get the interwiki prefix (or null string)
626 * @return String Interwiki prefix
628 public function getInterwiki() {
629 return $this->mInterwiki
;
633 * Determine whether the object refers to a page within
634 * this project and is transcludable.
636 * @return Bool TRUE if this is transcludable
638 public function isTrans() {
639 if ( $this->mInterwiki
== '' ) {
643 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
647 * Returns the DB name of the distant wiki which owns the object.
649 * @return String the DB name
651 public function getTransWikiID() {
652 if ( $this->mInterwiki
== '' ) {
656 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
660 * Get the text form (spaces not underscores) of the main part
662 * @return String Main part of the title
664 public function getText() {
665 return $this->mTextform
;
669 * Get the URL-encoded form of the main part
671 * @return String Main part of the title, URL-encoded
673 public function getPartialURL() {
674 return $this->mUrlform
;
678 * Get the main part with underscores
680 * @return String: Main part of the title, with underscores
682 public function getDBkey() {
683 return $this->mDbkeyform
;
687 * Get the DB key with the initial letter case as specified by the user
689 * @return String DB key
691 function getUserCaseDBKey() {
692 return $this->mUserCaseDBKey
;
696 * Get the namespace index, i.e. one of the NS_xxxx constants.
698 * @return Integer: Namespace index
700 public function getNamespace() {
701 return $this->mNamespace
;
705 * Get the namespace text
707 * @return String: Namespace text
709 public function getNsText() {
712 if ( $this->mInterwiki
!= '' ) {
713 // This probably shouldn't even happen. ohh man, oh yuck.
714 // But for interwiki transclusion it sometimes does.
715 // Shit. Shit shit shit.
717 // Use the canonical namespaces if possible to try to
718 // resolve a foreign namespace.
719 if ( MWNamespace
::exists( $this->mNamespace
) ) {
720 return MWNamespace
::getCanonicalName( $this->mNamespace
);
724 if ( $wgContLang->needsGenderDistinction() &&
725 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
726 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
727 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
730 return $wgContLang->getNsText( $this->mNamespace
);
734 * Get the namespace text of the subject (rather than talk) page
736 * @return String Namespace text
738 public function getSubjectNsText() {
740 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
744 * Get the namespace text of the talk page
746 * @return String Namespace text
748 public function getTalkNsText() {
750 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
754 * Could this title have a corresponding talk page?
756 * @return Bool TRUE or FALSE
758 public function canTalk() {
759 return( MWNamespace
::canTalk( $this->mNamespace
) );
763 * Is this in a namespace that allows actual pages?
766 * @internal note -- uses hardcoded namespace index instead of constants
768 public function canExist() {
769 return $this->mNamespace
>= NS_MAIN
;
773 * Can this title be added to a user's watchlist?
775 * @return Bool TRUE or FALSE
777 public function isWatchable() {
778 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
782 * Returns true if this is a special page.
786 public function isSpecialPage() {
787 return $this->getNamespace() == NS_SPECIAL
;
791 * Returns true if this title resolves to the named special page
793 * @param $name String The special page name
796 public function isSpecial( $name ) {
797 if ( $this->isSpecialPage() ) {
798 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
799 if ( $name == $thisName ) {
807 * If the Title refers to a special page alias which is not the local default, resolve
808 * the alias, and localise the name as necessary. Otherwise, return $this
812 public function fixSpecialName() {
813 if ( $this->isSpecialPage() ) {
814 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
815 if ( $canonicalName ) {
816 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
817 if ( $localName != $this->mDbkeyform
) {
818 return Title
::makeTitle( NS_SPECIAL
, $localName );
826 * Returns true if the title is inside the specified namespace.
828 * Please make use of this instead of comparing to getNamespace()
829 * This function is much more resistant to changes we may make
830 * to namespaces than code that makes direct comparisons.
831 * @param $ns int The namespace
835 public function inNamespace( $ns ) {
836 return MWNamespace
::equals( $this->getNamespace(), $ns );
840 * Returns true if the title is inside one of the specified namespaces.
842 * @param ...$namespaces The namespaces to check for
846 public function inNamespaces( /* ... */ ) {
847 $namespaces = func_get_args();
848 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
849 $namespaces = $namespaces[0];
852 foreach ( $namespaces as $ns ) {
853 if ( $this->inNamespace( $ns ) ) {
862 * Returns true if the title has the same subject namespace as the
863 * namespace specified.
864 * For example this method will take NS_USER and return true if namespace
865 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
866 * as their subject namespace.
868 * This is MUCH simpler than individually testing for equivilance
869 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
874 public function hasSubjectNamespace( $ns ) {
875 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
879 * Is this Title in a namespace which contains content?
880 * In other words, is this a content page, for the purposes of calculating
885 public function isContentPage() {
886 return MWNamespace
::isContent( $this->getNamespace() );
890 * Would anybody with sufficient privileges be able to move this page?
891 * Some pages just aren't movable.
893 * @return Bool TRUE or FALSE
895 public function isMovable() {
896 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
897 // Interwiki title or immovable namespace. Hooks don't get to override here
902 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
907 * Is this the mainpage?
908 * @note Title::newFromText seams to be sufficiently optimized by the title
909 * cache that we don't need to over-optimize by doing direct comparisons and
910 * acidentally creating new bugs where $title->equals( Title::newFromText() )
911 * ends up reporting something differently than $title->isMainPage();
916 public function isMainPage() {
917 return $this->equals( Title
::newMainPage() );
925 public function isSubpage() {
926 return MWNamespace
::hasSubpages( $this->mNamespace
)
927 ?
strpos( $this->getText(), '/' ) !== false
932 * Is this a conversion table for the LanguageConverter?
936 public function isConversionTable() {
937 return $this->getNamespace() == NS_MEDIAWIKI
&&
938 strpos( $this->getText(), 'Conversiontable/' ) === 0;
942 * Does that page contain wikitext, or it is JS, CSS or whatever?
946 public function isWikitextPage() {
947 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
948 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
953 * Could this page contain custom CSS or JavaScript, based
958 public function isCssOrJsPage() {
959 $retval = $this->mNamespace
== NS_MEDIAWIKI
960 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
961 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
966 * Is this a .css or .js subpage of a user page?
969 public function isCssJsSubpage() {
970 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
974 * Trim down a .css or .js subpage title to get the corresponding skin name
976 * @return string containing skin name from .css or .js subpage title
978 public function getSkinFromCssJsSubpage() {
979 $subpage = explode( '/', $this->mTextform
);
980 $subpage = $subpage[ count( $subpage ) - 1 ];
981 $lastdot = strrpos( $subpage, '.' );
982 if ( $lastdot === false )
983 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
984 return substr( $subpage, 0, $lastdot );
988 * Is this a .css subpage of a user page?
992 public function isCssSubpage() {
993 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
997 * Is this a .js subpage of a user page?
1001 public function isJsSubpage() {
1002 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1006 * Is this a talk page of some sort?
1010 public function isTalkPage() {
1011 return MWNamespace
::isTalk( $this->getNamespace() );
1015 * Get a Title object associated with the talk page of this article
1017 * @return Title the object for the talk page
1019 public function getTalkPage() {
1020 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1024 * Get a title object associated with the subject page of this
1027 * @return Title the object for the subject page
1029 public function getSubjectPage() {
1030 // Is this the same title?
1031 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1032 if ( $this->getNamespace() == $subjectNS ) {
1035 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1039 * Get the default namespace index, for when there is no namespace
1041 * @return Int Default namespace index
1043 public function getDefaultNamespace() {
1044 return $this->mDefaultNamespace
;
1048 * Get title for search index
1050 * @return String a stripped-down title string ready for the
1053 public function getIndexTitle() {
1054 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1058 * Get the Title fragment (i.e.\ the bit after the #) in text form
1060 * @return String Title fragment
1062 public function getFragment() {
1063 return $this->mFragment
;
1067 * Get the fragment in URL form, including the "#" character if there is one
1068 * @return String Fragment in URL form
1070 public function getFragmentForURL() {
1071 if ( $this->mFragment
== '' ) {
1074 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1079 * Set the fragment for this title. Removes the first character from the
1080 * specified fragment before setting, so it assumes you're passing it with
1083 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1084 * Still in active use privately.
1086 * @param $fragment String text
1088 public function setFragment( $fragment ) {
1089 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1093 * Prefix some arbitrary text with the namespace or interwiki prefix
1096 * @param $name String the text
1097 * @return String the prefixed text
1100 private function prefix( $name ) {
1102 if ( $this->mInterwiki
!= '' ) {
1103 $p = $this->mInterwiki
. ':';
1106 if ( 0 != $this->mNamespace
) {
1107 $p .= $this->getNsText() . ':';
1113 * Get the prefixed database key form
1115 * @return String the prefixed title, with underscores and
1116 * any interwiki and namespace prefixes
1118 public function getPrefixedDBkey() {
1119 $s = $this->prefix( $this->mDbkeyform
);
1120 $s = str_replace( ' ', '_', $s );
1125 * Get the prefixed title with spaces.
1126 * This is the form usually used for display
1128 * @return String the prefixed title, with spaces
1130 public function getPrefixedText() {
1131 // @todo FIXME: Bad usage of empty() ?
1132 if ( empty( $this->mPrefixedText
) ) {
1133 $s = $this->prefix( $this->mTextform
);
1134 $s = str_replace( '_', ' ', $s );
1135 $this->mPrefixedText
= $s;
1137 return $this->mPrefixedText
;
1141 * Return a string representation of this title
1143 * @return String representation of this title
1145 public function __toString() {
1146 return $this->getPrefixedText();
1150 * Get the prefixed title with spaces, plus any fragment
1151 * (part beginning with '#')
1153 * @return String the prefixed title, with spaces and the fragment, including '#'
1155 public function getFullText() {
1156 $text = $this->getPrefixedText();
1157 if ( $this->mFragment
!= '' ) {
1158 $text .= '#' . $this->mFragment
;
1164 * Get the base page name, i.e. the leftmost part before any slashes
1166 * @return String Base name
1168 public function getBaseText() {
1169 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1170 return $this->getText();
1173 $parts = explode( '/', $this->getText() );
1174 # Don't discard the real title if there's no subpage involved
1175 if ( count( $parts ) > 1 ) {
1176 unset( $parts[count( $parts ) - 1] );
1178 return implode( '/', $parts );
1182 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1184 * @return String Subpage name
1186 public function getSubpageText() {
1187 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1188 return( $this->mTextform
);
1190 $parts = explode( '/', $this->mTextform
);
1191 return( $parts[count( $parts ) - 1] );
1195 * Get the HTML-escaped displayable text form.
1196 * Used for the title field in <a> tags.
1198 * @return String the text, including any prefixes
1200 public function getEscapedText() {
1201 wfDeprecated( __METHOD__
, '1.19' );
1202 return htmlspecialchars( $this->getPrefixedText() );
1206 * Get a URL-encoded form of the subpage text
1208 * @return String URL-encoded subpage name
1210 public function getSubpageUrlForm() {
1211 $text = $this->getSubpageText();
1212 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1217 * Get a URL-encoded title (not an actual URL) including interwiki
1219 * @return String the URL-encoded form
1221 public function getPrefixedURL() {
1222 $s = $this->prefix( $this->mDbkeyform
);
1223 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1228 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1229 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1230 * second argument named variant. This was deprecated in favor
1231 * of passing an array of option with a "variant" key
1232 * Once $query2 is removed for good, this helper can be dropped
1233 * andthe wfArrayToCGI moved to getLocalURL();
1235 * @since 1.19 (r105919)
1237 * @param $query2 bool
1240 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1241 if( $query2 !== false ) {
1242 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" );
1244 if ( is_array( $query ) ) {
1245 $query = wfArrayToCGI( $query );
1248 if ( is_string( $query2 ) ) {
1249 // $query2 is a string, we will consider this to be
1250 // a deprecated $variant argument and add it to the query
1251 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1253 $query2 = wfArrayToCGI( $query2 );
1255 // If we have $query content add a & to it first
1259 // Now append the queries together
1266 * Get a real URL referring to this title, with interwiki link and
1269 * See getLocalURL for the arguments.
1271 * @see self::getLocalURL
1273 * @param $proto Protocol type to use in URL
1274 * @return String the URL
1276 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1277 $query = self
::fixUrlQueryArgs( $query, $query2 );
1279 # Hand off all the decisions on urls to getLocalURL
1280 $url = $this->getLocalURL( $query );
1282 # Expand the url to make it a full url. Note that getLocalURL has the
1283 # potential to output full urls for a variety of reasons, so we use
1284 # wfExpandUrl instead of simply prepending $wgServer
1285 $url = wfExpandUrl( $url, $proto );
1287 # Finally, add the fragment.
1288 $url .= $this->getFragmentForURL();
1290 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1295 * Get a URL with no fragment or server name. If this page is generated
1296 * with action=render, $wgServer is prepended.
1299 * @param $query string|array an optional query string,
1300 * not used for interwiki links. Can be specified as an associative array as well,
1301 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1302 * Some query patterns will trigger various shorturl path replacements.
1303 * @param $query2 Mixed: An optional secondary query array. This one MUST
1304 * be an array. If a string is passed it will be interpreted as a deprecated
1305 * variant argument and urlencoded into a variant= argument.
1306 * This second query argument will be added to the $query
1307 * The second parameter is deprecated since 1.19. Pass it as a key,value
1308 * pair in the first parameter array instead.
1310 * @return String the URL
1312 public function getLocalURL( $query = '', $query2 = false ) {
1313 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1315 $query = self
::fixUrlQueryArgs( $query, $query2 );
1317 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1319 $namespace = $this->getNsText();
1320 if ( $namespace != '' ) {
1321 # Can this actually happen? Interwikis shouldn't be parsed.
1322 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1325 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1326 $url = wfAppendQuery( $url, $query );
1328 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1329 if ( $query == '' ) {
1330 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1331 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1333 global $wgVariantArticlePath, $wgActionPaths;
1337 if ( !empty( $wgActionPaths ) &&
1338 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1340 $action = urldecode( $matches[2] );
1341 if ( isset( $wgActionPaths[$action] ) ) {
1342 $query = $matches[1];
1343 if ( isset( $matches[4] ) ) {
1344 $query .= $matches[4];
1346 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1347 if ( $query != '' ) {
1348 $url = wfAppendQuery( $url, $query );
1353 if ( $url === false &&
1354 $wgVariantArticlePath &&
1355 $this->getPageLanguage()->hasVariants() &&
1356 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1358 $variant = urldecode( $matches[1] );
1359 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1360 // Only do the variant replacement if the given variant is a valid
1361 // variant for the page's language.
1362 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1363 $url = str_replace( '$1', $dbkey, $url );
1367 if ( $url === false ) {
1368 if ( $query == '-' ) {
1371 $url = "{$wgScript}?title={$dbkey}&{$query}";
1375 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1377 // @todo FIXME: This causes breakage in various places when we
1378 // actually expected a local URL and end up with dupe prefixes.
1379 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1380 $url = $wgServer . $url;
1383 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1388 * Get a URL that's the simplest URL that will be valid to link, locally,
1389 * to the current Title. It includes the fragment, but does not include
1390 * the server unless action=render is used (or the link is external). If
1391 * there's a fragment but the prefixed text is empty, we just return a link
1394 * The result obviously should not be URL-escaped, but does need to be
1395 * HTML-escaped if it's being output in HTML.
1397 * See getLocalURL for the arguments.
1399 * @param $proto Protocol to use; setting this will cause a full URL to be used
1400 * @see self::getLocalURL
1401 * @return String the URL
1403 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1404 wfProfileIn( __METHOD__
);
1405 if ( $this->isExternal() ||
$proto != PROTO_RELATIVE
) {
1406 $ret = $this->getFullURL( $query, $query2, $proto );
1407 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1408 $ret = $this->getFragmentForURL();
1410 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1412 wfProfileOut( __METHOD__
);
1417 * Get an HTML-escaped version of the URL form, suitable for
1418 * using in a link, without a server name or fragment
1420 * See getLocalURL for the arguments.
1422 * @see self::getLocalURL
1423 * @param $query string
1424 * @param $query2 bool|string
1425 * @return String the URL
1427 public function escapeLocalURL( $query = '', $query2 = false ) {
1428 wfDeprecated( __METHOD__
, '1.19' );
1429 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1433 * Get an HTML-escaped version of the URL form, suitable for
1434 * using in a link, including the server name and fragment
1436 * See getLocalURL for the arguments.
1438 * @see self::getLocalURL
1439 * @return String the URL
1441 public function escapeFullURL( $query = '', $query2 = false ) {
1442 wfDeprecated( __METHOD__
, '1.19' );
1443 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1447 * Get the URL form for an internal link.
1448 * - Used in various Squid-related code, in case we have a different
1449 * internal hostname for the server from the exposed one.
1451 * This uses $wgInternalServer to qualify the path, or $wgServer
1452 * if $wgInternalServer is not set. If the server variable used is
1453 * protocol-relative, the URL will be expanded to http://
1455 * See getLocalURL for the arguments.
1457 * @see self::getLocalURL
1458 * @return String the URL
1460 public function getInternalURL( $query = '', $query2 = false ) {
1461 global $wgInternalServer, $wgServer;
1462 $query = self
::fixUrlQueryArgs( $query, $query2 );
1463 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1464 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1465 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1470 * Get the URL for a canonical link, for use in things like IRC and
1471 * e-mail notifications. Uses $wgCanonicalServer and the
1472 * GetCanonicalURL hook.
1474 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1476 * See getLocalURL for the arguments.
1478 * @see self::getLocalURL
1479 * @return string The URL
1482 public function getCanonicalURL( $query = '', $query2 = false ) {
1483 $query = self
::fixUrlQueryArgs( $query, $query2 );
1484 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1485 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1490 * HTML-escaped version of getCanonicalURL()
1492 * See getLocalURL for the arguments.
1494 * @see self::getLocalURL
1498 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1499 wfDeprecated( __METHOD__
, '1.19' );
1500 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1504 * Get the edit URL for this Title
1506 * @return String the URL, or a null string if this is an
1509 public function getEditURL() {
1510 if ( $this->mInterwiki
!= '' ) {
1513 $s = $this->getLocalURL( 'action=edit' );
1519 * Is $wgUser watching this page?
1521 * @deprecated in 1.20; use User::isWatched() instead.
1524 public function userIsWatching() {
1527 if ( is_null( $this->mWatched
) ) {
1528 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1529 $this->mWatched
= false;
1531 $this->mWatched
= $wgUser->isWatched( $this );
1534 return $this->mWatched
;
1538 * Can $wgUser read this page?
1540 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1542 * @todo fold these checks into userCan()
1544 public function userCanRead() {
1545 wfDeprecated( __METHOD__
, '1.19' );
1546 return $this->userCan( 'read' );
1550 * Can $user perform $action on this page?
1551 * This skips potentially expensive cascading permission checks
1552 * as well as avoids expensive error formatting
1554 * Suitable for use for nonessential UI controls in common cases, but
1555 * _not_ for functional access control.
1557 * May provide false positives, but should never provide a false negative.
1559 * @param $action String action that permission needs to be checked for
1560 * @param $user User to check (since 1.19); $wgUser will be used if not
1564 public function quickUserCan( $action, $user = null ) {
1565 return $this->userCan( $action, $user, false );
1569 * Can $user perform $action on this page?
1571 * @param $action String action that permission needs to be checked for
1572 * @param $user User to check (since 1.19); $wgUser will be used if not
1574 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1575 * unnecessary queries.
1578 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1579 if ( !$user instanceof User
) {
1583 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1587 * Can $user perform $action on this page?
1589 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1591 * @param $action String action that permission needs to be checked for
1592 * @param $user User to check
1593 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1594 * queries by skipping checks for cascading protections and user blocks.
1595 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1596 * whose corresponding errors may be ignored.
1597 * @return Array of arguments to wfMessage to explain permissions problems.
1599 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1600 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1602 // Remove the errors being ignored.
1603 foreach ( $errors as $index => $error ) {
1604 $error_key = is_array( $error ) ?
$error[0] : $error;
1606 if ( in_array( $error_key, $ignoreErrors ) ) {
1607 unset( $errors[$index] );
1615 * Permissions checks that fail most often, and which are easiest to test.
1617 * @param $action String the action to check
1618 * @param $user User user to check
1619 * @param $errors Array list of current errors
1620 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1621 * @param $short Boolean short circuit on first error
1623 * @return Array list of errors
1625 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1626 if ( $action == 'create' ) {
1627 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1628 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1629 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1631 } elseif ( $action == 'move' ) {
1632 if ( !$user->isAllowed( 'move-rootuserpages' )
1633 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1634 // Show user page-specific message only if the user can move other pages
1635 $errors[] = array( 'cant-move-user-page' );
1638 // Check if user is allowed to move files if it's a file
1639 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1640 $errors[] = array( 'movenotallowedfile' );
1643 if ( !$user->isAllowed( 'move' ) ) {
1644 // User can't move anything
1645 global $wgGroupPermissions;
1646 $userCanMove = false;
1647 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1648 $userCanMove = $wgGroupPermissions['user']['move'];
1650 $autoconfirmedCanMove = false;
1651 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1652 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1654 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1655 // custom message if logged-in users without any special rights can move
1656 $errors[] = array( 'movenologintext' );
1658 $errors[] = array( 'movenotallowed' );
1661 } elseif ( $action == 'move-target' ) {
1662 if ( !$user->isAllowed( 'move' ) ) {
1663 // User can't move anything
1664 $errors[] = array( 'movenotallowed' );
1665 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1666 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1667 // Show user page-specific message only if the user can move other pages
1668 $errors[] = array( 'cant-move-to-user-page' );
1670 } elseif ( !$user->isAllowed( $action ) ) {
1671 $errors[] = $this->missingPermissionError( $action, $short );
1678 * Add the resulting error code to the errors array
1680 * @param $errors Array list of current errors
1681 * @param $result Mixed result of errors
1683 * @return Array list of errors
1685 private function resultToError( $errors, $result ) {
1686 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1687 // A single array representing an error
1688 $errors[] = $result;
1689 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1690 // A nested array representing multiple errors
1691 $errors = array_merge( $errors, $result );
1692 } elseif ( $result !== '' && is_string( $result ) ) {
1693 // A string representing a message-id
1694 $errors[] = array( $result );
1695 } elseif ( $result === false ) {
1696 // a generic "We don't want them to do that"
1697 $errors[] = array( 'badaccess-group0' );
1703 * Check various permission hooks
1705 * @param $action String the action to check
1706 * @param $user User user to check
1707 * @param $errors Array list of current errors
1708 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1709 * @param $short Boolean short circuit on first error
1711 * @return Array list of errors
1713 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1714 // Use getUserPermissionsErrors instead
1716 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1717 return $result ?
array() : array( array( 'badaccess-group0' ) );
1719 // Check getUserPermissionsErrors hook
1720 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1721 $errors = $this->resultToError( $errors, $result );
1723 // Check getUserPermissionsErrorsExpensive hook
1724 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1725 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1726 $errors = $this->resultToError( $errors, $result );
1733 * Check permissions on special pages & namespaces
1735 * @param $action String the action to check
1736 * @param $user User user to check
1737 * @param $errors Array list of current errors
1738 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1739 * @param $short Boolean short circuit on first error
1741 * @return Array list of errors
1743 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1744 # Only 'createaccount' and 'execute' can be performed on
1745 # special pages, which don't actually exist in the DB.
1746 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1747 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1748 $errors[] = array( 'ns-specialprotected' );
1751 # Check $wgNamespaceProtection for restricted namespaces
1752 if ( $this->isNamespaceProtected( $user ) ) {
1753 $ns = $this->mNamespace
== NS_MAIN ?
1754 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1755 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1756 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1763 * Check CSS/JS sub-page permissions
1765 * @param $action String the action to check
1766 * @param $user User user to check
1767 * @param $errors Array list of current errors
1768 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1769 * @param $short Boolean short circuit on first error
1771 * @return Array list of errors
1773 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1774 # Protect css/js subpages of user pages
1775 # XXX: this might be better using restrictions
1776 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1777 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1778 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1779 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1780 $errors[] = array( 'customcssprotected' );
1781 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1782 $errors[] = array( 'customjsprotected' );
1790 * Check against page_restrictions table requirements on this
1791 * page. The user must possess all required rights for this
1794 * @param $action String the action to check
1795 * @param $user User user to check
1796 * @param $errors Array list of current errors
1797 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1798 * @param $short Boolean short circuit on first error
1800 * @return Array list of errors
1802 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1803 foreach ( $this->getRestrictions( $action ) as $right ) {
1804 // Backwards compatibility, rewrite sysop -> protect
1805 if ( $right == 'sysop' ) {
1808 if ( $right != '' && !$user->isAllowed( $right ) ) {
1809 // Users with 'editprotected' permission can edit protected pages
1810 // without cascading option turned on.
1811 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1812 ||
$this->mCascadeRestriction
)
1814 $errors[] = array( 'protectedpagetext', $right );
1823 * Check restrictions on cascading pages.
1825 * @param $action String the action to check
1826 * @param $user User to check
1827 * @param $errors Array list of current errors
1828 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1829 * @param $short Boolean short circuit on first error
1831 * @return Array list of errors
1833 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1834 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1835 # We /could/ use the protection level on the source page, but it's
1836 # fairly ugly as we have to establish a precedence hierarchy for pages
1837 # included by multiple cascade-protected pages. So just restrict
1838 # it to people with 'protect' permission, as they could remove the
1839 # protection anyway.
1840 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1841 # Cascading protection depends on more than this page...
1842 # Several cascading protected pages may include this page...
1843 # Check each cascading level
1844 # This is only for protection restrictions, not for all actions
1845 if ( isset( $restrictions[$action] ) ) {
1846 foreach ( $restrictions[$action] as $right ) {
1847 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1848 if ( $right != '' && !$user->isAllowed( $right ) ) {
1850 foreach ( $cascadingSources as $page )
1851 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1852 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1862 * Check action permissions not already checked in checkQuickPermissions
1864 * @param $action String the action to check
1865 * @param $user User to check
1866 * @param $errors Array list of current errors
1867 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1868 * @param $short Boolean short circuit on first error
1870 * @return Array list of errors
1872 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1873 global $wgDeleteRevisionsLimit, $wgLang;
1875 if ( $action == 'protect' ) {
1876 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1877 // If they can't edit, they shouldn't protect.
1878 $errors[] = array( 'protect-cantedit' );
1880 } elseif ( $action == 'create' ) {
1881 $title_protection = $this->getTitleProtection();
1882 if( $title_protection ) {
1883 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1884 $title_protection['pt_create_perm'] = 'protect'; // B/C
1886 if( $title_protection['pt_create_perm'] == '' ||
1887 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1889 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1892 } elseif ( $action == 'move' ) {
1893 // Check for immobile pages
1894 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1895 // Specific message for this case
1896 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1897 } elseif ( !$this->isMovable() ) {
1898 // Less specific message for rarer cases
1899 $errors[] = array( 'immobile-source-page' );
1901 } elseif ( $action == 'move-target' ) {
1902 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1903 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1904 } elseif ( !$this->isMovable() ) {
1905 $errors[] = array( 'immobile-target-page' );
1907 } elseif ( $action == 'delete' ) {
1908 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1909 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1911 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1918 * Check that the user isn't blocked from editting.
1920 * @param $action String the action to check
1921 * @param $user User to check
1922 * @param $errors Array list of current errors
1923 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1924 * @param $short Boolean short circuit on first error
1926 * @return Array list of errors
1928 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1929 // Account creation blocks handled at userlogin.
1930 // Unblocking handled in SpecialUnblock
1931 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1935 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1937 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1938 $errors[] = array( 'confirmedittext' );
1941 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1942 // Don't block the user from editing their own talk page unless they've been
1943 // explicitly blocked from that too.
1944 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1945 $block = $user->getBlock();
1947 // This is from OutputPage::blockedPage
1948 // Copied at r23888 by werdna
1950 $id = $user->blockedBy();
1951 $reason = $user->blockedFor();
1952 if ( $reason == '' ) {
1953 $reason = wfMessage( 'blockednoreason' )->text();
1955 $ip = $user->getRequest()->getIP();
1957 if ( is_numeric( $id ) ) {
1958 $name = User
::whoIs( $id );
1963 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1964 $blockid = $block->getId();
1965 $blockExpiry = $block->getExpiry();
1966 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1967 if ( $blockExpiry == 'infinity' ) {
1968 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1970 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1973 $intended = strval( $block->getTarget() );
1975 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1976 $blockid, $blockExpiry, $intended, $blockTimestamp );
1983 * Check that the user is allowed to read this page.
1985 * @param $action String the action to check
1986 * @param $user User to check
1987 * @param $errors Array list of current errors
1988 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1989 * @param $short Boolean short circuit on first error
1991 * @return Array list of errors
1993 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1994 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1995 static $useShortcut = null;
1997 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1998 if ( is_null( $useShortcut ) ) {
1999 $useShortcut = true;
2000 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2001 # Not a public wiki, so no shortcut
2002 $useShortcut = false;
2003 } elseif ( !empty( $wgRevokePermissions ) ) {
2005 * Iterate through each group with permissions being revoked (key not included since we don't care
2006 * what the group name is), then check if the read permission is being revoked. If it is, then
2007 * we don't use the shortcut below since the user might not be able to read, even though anon
2008 * reading is allowed.
2010 foreach ( $wgRevokePermissions as $perms ) {
2011 if ( !empty( $perms['read'] ) ) {
2012 # We might be removing the read right from the user, so no shortcut
2013 $useShortcut = false;
2020 $whitelisted = false;
2021 if ( $useShortcut ) {
2022 # Shortcut for public wikis, allows skipping quite a bit of code
2023 $whitelisted = true;
2024 } elseif ( $user->isAllowed( 'read' ) ) {
2025 # If the user is allowed to read pages, he is allowed to read all pages
2026 $whitelisted = true;
2027 } elseif ( $this->isSpecial( 'Userlogin' )
2028 ||
$this->isSpecial( 'ChangePassword' )
2029 ||
$this->isSpecial( 'PasswordReset' )
2031 # Always grant access to the login page.
2032 # Even anons need to be able to log in.
2033 $whitelisted = true;
2034 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2035 # Time to check the whitelist
2036 # Only do these checks is there's something to check against
2037 $name = $this->getPrefixedText();
2038 $dbName = $this->getPrefixedDBKey();
2040 // Check for explicit whitelisting with and without underscores
2041 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2042 $whitelisted = true;
2043 } elseif ( $this->getNamespace() == NS_MAIN
) {
2044 # Old settings might have the title prefixed with
2045 # a colon for main-namespace pages
2046 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2047 $whitelisted = true;
2049 } elseif ( $this->isSpecialPage() ) {
2050 # If it's a special page, ditch the subpage bit and check again
2051 $name = $this->getDBkey();
2052 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2053 if ( $name !== false ) {
2054 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2055 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2056 $whitelisted = true;
2062 if ( !$whitelisted ) {
2063 # If the title is not whitelisted, give extensions a chance to do so...
2064 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2065 if ( !$whitelisted ) {
2066 $errors[] = $this->missingPermissionError( $action, $short );
2074 * Get a description array when the user doesn't have the right to perform
2075 * $action (i.e. when User::isAllowed() returns false)
2077 * @param $action String the action to check
2078 * @param $short Boolean short circuit on first error
2079 * @return Array list of errors
2081 private function missingPermissionError( $action, $short ) {
2082 // We avoid expensive display logic for quickUserCan's and such
2084 return array( 'badaccess-group0' );
2087 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2088 User
::getGroupsWithPermission( $action ) );
2090 if ( count( $groups ) ) {
2094 $wgLang->commaList( $groups ),
2098 return array( 'badaccess-group0' );
2103 * Can $user perform $action on this page? This is an internal function,
2104 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2105 * checks on wfReadOnly() and blocks)
2107 * @param $action String action that permission needs to be checked for
2108 * @param $user User to check
2109 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2110 * @param $short Bool Set this to true to stop after the first permission error.
2111 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2113 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2114 wfProfileIn( __METHOD__
);
2116 # Read has special handling
2117 if ( $action == 'read' ) {
2119 'checkPermissionHooks',
2120 'checkReadPermissions',
2124 'checkQuickPermissions',
2125 'checkPermissionHooks',
2126 'checkSpecialsAndNSPermissions',
2127 'checkCSSandJSPermissions',
2128 'checkPageRestrictions',
2129 'checkCascadingSourcesRestrictions',
2130 'checkActionPermissions',
2136 while( count( $checks ) > 0 &&
2137 !( $short && count( $errors ) > 0 ) ) {
2138 $method = array_shift( $checks );
2139 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2142 wfProfileOut( __METHOD__
);
2147 * Protect css subpages of user pages: can $wgUser edit
2150 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2153 public function userCanEditCssSubpage() {
2155 wfDeprecated( __METHOD__
, '1.19' );
2156 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2157 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2161 * Protect js subpages of user pages: can $wgUser edit
2164 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2167 public function userCanEditJsSubpage() {
2169 wfDeprecated( __METHOD__
, '1.19' );
2170 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2171 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2175 * Get a filtered list of all restriction types supported by this wiki.
2176 * @param bool $exists True to get all restriction types that apply to
2177 * titles that do exist, False for all restriction types that apply to
2178 * titles that do not exist
2181 public static function getFilteredRestrictionTypes( $exists = true ) {
2182 global $wgRestrictionTypes;
2183 $types = $wgRestrictionTypes;
2185 # Remove the create restriction for existing titles
2186 $types = array_diff( $types, array( 'create' ) );
2188 # Only the create and upload restrictions apply to non-existing titles
2189 $types = array_intersect( $types, array( 'create', 'upload' ) );
2195 * Returns restriction types for the current Title
2197 * @return array applicable restriction types
2199 public function getRestrictionTypes() {
2200 if ( $this->isSpecialPage() ) {
2204 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2206 if ( $this->getNamespace() != NS_FILE
) {
2207 # Remove the upload restriction for non-file titles
2208 $types = array_diff( $types, array( 'upload' ) );
2211 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2213 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2214 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2220 * Is this title subject to title protection?
2221 * Title protection is the one applied against creation of such title.
2223 * @return Mixed An associative array representing any existent title
2224 * protection, or false if there's none.
2226 private function getTitleProtection() {
2227 // Can't protect pages in special namespaces
2228 if ( $this->getNamespace() < 0 ) {
2232 // Can't protect pages that exist.
2233 if ( $this->exists() ) {
2237 if ( !isset( $this->mTitleProtection
) ) {
2238 $dbr = wfGetDB( DB_SLAVE
);
2239 $res = $dbr->select( 'protected_titles', '*',
2240 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2243 // fetchRow returns false if there are no rows.
2244 $this->mTitleProtection
= $dbr->fetchRow( $res );
2246 return $this->mTitleProtection
;
2250 * Update the title protection status
2252 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2253 * @param $create_perm String Permission required for creation
2254 * @param $reason String Reason for protection
2255 * @param $expiry String Expiry timestamp
2256 * @return boolean true
2258 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2259 wfDeprecated( __METHOD__
, '1.19' );
2263 $limit = array( 'create' => $create_perm );
2264 $expiry = array( 'create' => $expiry );
2266 $page = WikiPage
::factory( $this );
2267 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2269 return $status->isOK();
2273 * Remove any title protection due to page existing
2275 public function deleteTitleProtection() {
2276 $dbw = wfGetDB( DB_MASTER
);
2280 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2283 $this->mTitleProtection
= false;
2287 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2289 * @param $action String Action to check (default: edit)
2292 public function isSemiProtected( $action = 'edit' ) {
2293 if ( $this->exists() ) {
2294 $restrictions = $this->getRestrictions( $action );
2295 if ( count( $restrictions ) > 0 ) {
2296 foreach ( $restrictions as $restriction ) {
2297 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2307 # If it doesn't exist, it can't be protected
2313 * Does the title correspond to a protected article?
2315 * @param $action String the action the page is protected from,
2316 * by default checks all actions.
2319 public function isProtected( $action = '' ) {
2320 global $wgRestrictionLevels;
2322 $restrictionTypes = $this->getRestrictionTypes();
2324 # Special pages have inherent protection
2325 if( $this->isSpecialPage() ) {
2329 # Check regular protection levels
2330 foreach ( $restrictionTypes as $type ) {
2331 if ( $action == $type ||
$action == '' ) {
2332 $r = $this->getRestrictions( $type );
2333 foreach ( $wgRestrictionLevels as $level ) {
2334 if ( in_array( $level, $r ) && $level != '' ) {
2345 * Determines if $user is unable to edit this page because it has been protected
2346 * by $wgNamespaceProtection.
2348 * @param $user User object to check permissions
2351 public function isNamespaceProtected( User
$user ) {
2352 global $wgNamespaceProtection;
2354 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2355 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2356 if ( $right != '' && !$user->isAllowed( $right ) ) {
2365 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2367 * @return Bool If the page is subject to cascading restrictions.
2369 public function isCascadeProtected() {
2370 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2371 return ( $sources > 0 );
2375 * Cascading protection: Get the source of any cascading restrictions on this page.
2377 * @param $getPages Bool Whether or not to retrieve the actual pages
2378 * that the restrictions have come from.
2379 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2380 * have come, false for none, or true if such restrictions exist, but $getPages
2381 * was not set. The restriction array is an array of each type, each of which
2382 * contains a array of unique groups.
2384 public function getCascadeProtectionSources( $getPages = true ) {
2386 $pagerestrictions = array();
2388 if ( isset( $this->mCascadeSources
) && $getPages ) {
2389 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2390 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2391 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2394 wfProfileIn( __METHOD__
);
2396 $dbr = wfGetDB( DB_SLAVE
);
2398 if ( $this->getNamespace() == NS_FILE
) {
2399 $tables = array( 'imagelinks', 'page_restrictions' );
2400 $where_clauses = array(
2401 'il_to' => $this->getDBkey(),
2406 $tables = array( 'templatelinks', 'page_restrictions' );
2407 $where_clauses = array(
2408 'tl_namespace' => $this->getNamespace(),
2409 'tl_title' => $this->getDBkey(),
2416 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2417 'pr_expiry', 'pr_type', 'pr_level' );
2418 $where_clauses[] = 'page_id=pr_page';
2421 $cols = array( 'pr_expiry' );
2424 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2426 $sources = $getPages ?
array() : false;
2427 $now = wfTimestampNow();
2428 $purgeExpired = false;
2430 foreach ( $res as $row ) {
2431 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2432 if ( $expiry > $now ) {
2434 $page_id = $row->pr_page
;
2435 $page_ns = $row->page_namespace
;
2436 $page_title = $row->page_title
;
2437 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2438 # Add groups needed for each restriction type if its not already there
2439 # Make sure this restriction type still exists
2441 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2442 $pagerestrictions[$row->pr_type
] = array();
2445 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2446 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2447 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2453 // Trigger lazy purge of expired restrictions from the db
2454 $purgeExpired = true;
2457 if ( $purgeExpired ) {
2458 Title
::purgeExpiredRestrictions();
2462 $this->mCascadeSources
= $sources;
2463 $this->mCascadingRestrictions
= $pagerestrictions;
2465 $this->mHasCascadingRestrictions
= $sources;
2468 wfProfileOut( __METHOD__
);
2469 return array( $sources, $pagerestrictions );
2473 * Accessor/initialisation for mRestrictions
2475 * @param $action String action that permission needs to be checked for
2476 * @return Array of Strings the array of groups allowed to edit this article
2478 public function getRestrictions( $action ) {
2479 if ( !$this->mRestrictionsLoaded
) {
2480 $this->loadRestrictions();
2482 return isset( $this->mRestrictions
[$action] )
2483 ?
$this->mRestrictions
[$action]
2488 * Get the expiry time for the restriction against a given action
2491 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2492 * or not protected at all, or false if the action is not recognised.
2494 public function getRestrictionExpiry( $action ) {
2495 if ( !$this->mRestrictionsLoaded
) {
2496 $this->loadRestrictions();
2498 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2502 * Returns cascading restrictions for the current article
2506 function areRestrictionsCascading() {
2507 if ( !$this->mRestrictionsLoaded
) {
2508 $this->loadRestrictions();
2511 return $this->mCascadeRestriction
;
2515 * Loads a string into mRestrictions array
2517 * @param $res Resource restrictions as an SQL result.
2518 * @param $oldFashionedRestrictions String comma-separated list of page
2519 * restrictions from page table (pre 1.10)
2521 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2524 foreach ( $res as $row ) {
2528 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2532 * Compiles list of active page restrictions from both page table (pre 1.10)
2533 * and page_restrictions table for this existing page.
2534 * Public for usage by LiquidThreads.
2536 * @param $rows array of db result objects
2537 * @param $oldFashionedRestrictions string comma-separated list of page
2538 * restrictions from page table (pre 1.10)
2540 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2542 $dbr = wfGetDB( DB_SLAVE
);
2544 $restrictionTypes = $this->getRestrictionTypes();
2546 foreach ( $restrictionTypes as $type ) {
2547 $this->mRestrictions
[$type] = array();
2548 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2551 $this->mCascadeRestriction
= false;
2553 # Backwards-compatibility: also load the restrictions from the page record (old format).
2555 if ( $oldFashionedRestrictions === null ) {
2556 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2557 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2560 if ( $oldFashionedRestrictions != '' ) {
2562 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2563 $temp = explode( '=', trim( $restrict ) );
2564 if ( count( $temp ) == 1 ) {
2565 // old old format should be treated as edit/move restriction
2566 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2567 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2569 $restriction = trim( $temp[1] );
2570 if( $restriction != '' ) { //some old entries are empty
2571 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2576 $this->mOldRestrictions
= true;
2580 if ( count( $rows ) ) {
2581 # Current system - load second to make them override.
2582 $now = wfTimestampNow();
2583 $purgeExpired = false;
2585 # Cycle through all the restrictions.
2586 foreach ( $rows as $row ) {
2588 // Don't take care of restrictions types that aren't allowed
2589 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2592 // This code should be refactored, now that it's being used more generally,
2593 // But I don't really see any harm in leaving it in Block for now -werdna
2594 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2596 // Only apply the restrictions if they haven't expired!
2597 if ( !$expiry ||
$expiry > $now ) {
2598 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2599 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2601 $this->mCascadeRestriction |
= $row->pr_cascade
;
2603 // Trigger a lazy purge of expired restrictions
2604 $purgeExpired = true;
2608 if ( $purgeExpired ) {
2609 Title
::purgeExpiredRestrictions();
2613 $this->mRestrictionsLoaded
= true;
2617 * Load restrictions from the page_restrictions table
2619 * @param $oldFashionedRestrictions String comma-separated list of page
2620 * restrictions from page table (pre 1.10)
2622 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2624 if ( !$this->mRestrictionsLoaded
) {
2625 if ( $this->exists() ) {
2626 $dbr = wfGetDB( DB_SLAVE
);
2628 $res = $dbr->select(
2629 'page_restrictions',
2631 array( 'pr_page' => $this->getArticleID() ),
2635 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2637 $title_protection = $this->getTitleProtection();
2639 if ( $title_protection ) {
2640 $now = wfTimestampNow();
2641 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2643 if ( !$expiry ||
$expiry > $now ) {
2644 // Apply the restrictions
2645 $this->mRestrictionsExpiry
['create'] = $expiry;
2646 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2647 } else { // Get rid of the old restrictions
2648 Title
::purgeExpiredRestrictions();
2649 $this->mTitleProtection
= false;
2652 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2654 $this->mRestrictionsLoaded
= true;
2660 * Flush the protection cache in this object and force reload from the database.
2661 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2663 public function flushRestrictions() {
2664 $this->mRestrictionsLoaded
= false;
2665 $this->mTitleProtection
= null;
2669 * Purge expired restrictions from the page_restrictions table
2671 static function purgeExpiredRestrictions() {
2672 $dbw = wfGetDB( DB_MASTER
);
2674 'page_restrictions',
2675 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2681 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2687 * Does this have subpages? (Warning, usually requires an extra DB query.)
2691 public function hasSubpages() {
2692 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2697 # We dynamically add a member variable for the purpose of this method
2698 # alone to cache the result. There's no point in having it hanging
2699 # around uninitialized in every Title object; therefore we only add it
2700 # if needed and don't declare it statically.
2701 if ( isset( $this->mHasSubpages
) ) {
2702 return $this->mHasSubpages
;
2705 $subpages = $this->getSubpages( 1 );
2706 if ( $subpages instanceof TitleArray
) {
2707 return $this->mHasSubpages
= (bool)$subpages->count();
2709 return $this->mHasSubpages
= false;
2713 * Get all subpages of this page.
2715 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2716 * @return mixed TitleArray, or empty array if this page's namespace
2717 * doesn't allow subpages
2719 public function getSubpages( $limit = -1 ) {
2720 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2724 $dbr = wfGetDB( DB_SLAVE
);
2725 $conds['page_namespace'] = $this->getNamespace();
2726 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2728 if ( $limit > -1 ) {
2729 $options['LIMIT'] = $limit;
2731 return $this->mSubpages
= TitleArray
::newFromResult(
2732 $dbr->select( 'page',
2733 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2742 * Is there a version of this page in the deletion archive?
2744 * @return Int the number of archived revisions
2746 public function isDeleted() {
2747 if ( $this->getNamespace() < 0 ) {
2750 $dbr = wfGetDB( DB_SLAVE
);
2752 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2753 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2756 if ( $this->getNamespace() == NS_FILE
) {
2757 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2758 array( 'fa_name' => $this->getDBkey() ),
2767 * Is there a version of this page in the deletion archive?
2771 public function isDeletedQuick() {
2772 if ( $this->getNamespace() < 0 ) {
2775 $dbr = wfGetDB( DB_SLAVE
);
2776 $deleted = (bool)$dbr->selectField( 'archive', '1',
2777 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2780 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2781 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2782 array( 'fa_name' => $this->getDBkey() ),
2790 * Get the article ID for this Title from the link cache,
2791 * adding it if necessary
2793 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2795 * @return Int the ID
2797 public function getArticleID( $flags = 0 ) {
2798 if ( $this->getNamespace() < 0 ) {
2799 return $this->mArticleID
= 0;
2801 $linkCache = LinkCache
::singleton();
2802 if ( $flags & self
::GAID_FOR_UPDATE
) {
2803 $oldUpdate = $linkCache->forUpdate( true );
2804 $linkCache->clearLink( $this );
2805 $this->mArticleID
= $linkCache->addLinkObj( $this );
2806 $linkCache->forUpdate( $oldUpdate );
2808 if ( -1 == $this->mArticleID
) {
2809 $this->mArticleID
= $linkCache->addLinkObj( $this );
2812 return $this->mArticleID
;
2816 * Is this an article that is a redirect page?
2817 * Uses link cache, adding it if necessary
2819 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2822 public function isRedirect( $flags = 0 ) {
2823 if ( !is_null( $this->mRedirect
) ) {
2824 return $this->mRedirect
;
2826 # Calling getArticleID() loads the field from cache as needed
2827 if ( !$this->getArticleID( $flags ) ) {
2828 return $this->mRedirect
= false;
2830 $linkCache = LinkCache
::singleton();
2831 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2833 return $this->mRedirect
;
2837 * What is the length of this page?
2838 * Uses link cache, adding it if necessary
2840 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2843 public function getLength( $flags = 0 ) {
2844 if ( $this->mLength
!= -1 ) {
2845 return $this->mLength
;
2847 # Calling getArticleID() loads the field from cache as needed
2848 if ( !$this->getArticleID( $flags ) ) {
2849 return $this->mLength
= 0;
2851 $linkCache = LinkCache
::singleton();
2852 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2854 return $this->mLength
;
2858 * What is the page_latest field for this page?
2860 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2861 * @return Int or 0 if the page doesn't exist
2863 public function getLatestRevID( $flags = 0 ) {
2864 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
2865 return intval( $this->mLatestID
);
2867 # Calling getArticleID() loads the field from cache as needed
2868 if ( !$this->getArticleID( $flags ) ) {
2869 return $this->mLatestID
= 0;
2871 $linkCache = LinkCache
::singleton();
2872 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2874 return $this->mLatestID
;
2878 * This clears some fields in this object, and clears any associated
2879 * keys in the "bad links" section of the link cache.
2881 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2882 * loading of the new page_id. It's also called from
2883 * WikiPage::doDeleteArticleReal()
2885 * @param $newid Int the new Article ID
2887 public function resetArticleID( $newid ) {
2888 $linkCache = LinkCache
::singleton();
2889 $linkCache->clearLink( $this );
2891 if ( $newid === false ) {
2892 $this->mArticleID
= -1;
2894 $this->mArticleID
= intval( $newid );
2896 $this->mRestrictionsLoaded
= false;
2897 $this->mRestrictions
= array();
2898 $this->mRedirect
= null;
2899 $this->mLength
= -1;
2900 $this->mLatestID
= false;
2901 $this->mEstimateRevisions
= null;
2905 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2907 * @param $text String containing title to capitalize
2908 * @param $ns int namespace index, defaults to NS_MAIN
2909 * @return String containing capitalized title
2911 public static function capitalize( $text, $ns = NS_MAIN
) {
2914 if ( MWNamespace
::isCapitalized( $ns ) ) {
2915 return $wgContLang->ucfirst( $text );
2922 * Secure and split - main initialisation function for this object
2924 * Assumes that mDbkeyform has been set, and is urldecoded
2925 * and uses underscores, but not otherwise munged. This function
2926 * removes illegal characters, splits off the interwiki and
2927 * namespace prefixes, sets the other forms, and canonicalizes
2930 * @return Bool true on success
2932 private function secureAndSplit() {
2933 global $wgContLang, $wgLocalInterwiki;
2936 $this->mInterwiki
= $this->mFragment
= '';
2937 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2939 $dbkey = $this->mDbkeyform
;
2941 # Strip Unicode bidi override characters.
2942 # Sometimes they slip into cut-n-pasted page titles, where the
2943 # override chars get included in list displays.
2944 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2946 # Clean up whitespace
2947 # Note: use of the /u option on preg_replace here will cause
2948 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2949 # conveniently disabling them.
2950 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2951 $dbkey = trim( $dbkey, '_' );
2953 if ( $dbkey == '' ) {
2957 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2958 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2962 $this->mDbkeyform
= $dbkey;
2964 # Initial colon indicates main namespace rather than specified default
2965 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2966 if ( ':' == $dbkey[0] ) {
2967 $this->mNamespace
= NS_MAIN
;
2968 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2969 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2972 # Namespace or interwiki prefix
2974 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2977 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2979 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2980 # Ordinary namespace
2982 $this->mNamespace
= $ns;
2983 # For Talk:X pages, check if X has a "namespace" prefix
2984 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2985 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2986 # Disallow Talk:File:x type titles...
2988 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2989 # Disallow Talk:Interwiki:x type titles...
2993 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2994 if ( !$firstPass ) {
2995 # Can't make a local interwiki link to an interwiki link.
2996 # That's just crazy!
3002 $this->mInterwiki
= $wgContLang->lc( $p );
3004 # Redundant interwiki prefix to the local wiki
3005 if ( $wgLocalInterwiki !== false
3006 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3008 if ( $dbkey == '' ) {
3009 # Can't have an empty self-link
3012 $this->mInterwiki
= '';
3014 # Do another namespace split...
3018 # If there's an initial colon after the interwiki, that also
3019 # resets the default namespace
3020 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3021 $this->mNamespace
= NS_MAIN
;
3022 $dbkey = substr( $dbkey, 1 );
3025 # If there's no recognized interwiki or namespace,
3026 # then let the colon expression be part of the title.
3031 # We already know that some pages won't be in the database!
3032 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3033 $this->mArticleID
= 0;
3035 $fragment = strstr( $dbkey, '#' );
3036 if ( false !== $fragment ) {
3037 $this->setFragment( $fragment );
3038 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3039 # remove whitespace again: prevents "Foo_bar_#"
3040 # becoming "Foo_bar_"
3041 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3044 # Reject illegal characters.
3045 $rxTc = self
::getTitleInvalidRegex();
3046 if ( preg_match( $rxTc, $dbkey ) ) {
3050 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3051 # reachable due to the way web browsers deal with 'relative' URLs.
3052 # Also, they conflict with subpage syntax. Forbid them explicitly.
3053 if ( strpos( $dbkey, '.' ) !== false &&
3054 ( $dbkey === '.' ||
$dbkey === '..' ||
3055 strpos( $dbkey, './' ) === 0 ||
3056 strpos( $dbkey, '../' ) === 0 ||
3057 strpos( $dbkey, '/./' ) !== false ||
3058 strpos( $dbkey, '/../' ) !== false ||
3059 substr( $dbkey, -2 ) == '/.' ||
3060 substr( $dbkey, -3 ) == '/..' ) )
3065 # Magic tilde sequences? Nu-uh!
3066 if ( strpos( $dbkey, '~~~' ) !== false ) {
3070 # Limit the size of titles to 255 bytes. This is typically the size of the
3071 # underlying database field. We make an exception for special pages, which
3072 # don't need to be stored in the database, and may edge over 255 bytes due
3073 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3074 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3075 strlen( $dbkey ) > 512 )
3080 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3081 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3082 # other site might be case-sensitive.
3083 $this->mUserCaseDBKey
= $dbkey;
3084 if ( $this->mInterwiki
== '' ) {
3085 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3088 # Can't make a link to a namespace alone... "empty" local links can only be
3089 # self-links with a fragment identifier.
3090 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3094 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3095 // IP names are not allowed for accounts, and can only be referring to
3096 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3097 // there are numerous ways to present the same IP. Having sp:contribs scan
3098 // them all is silly and having some show the edits and others not is
3099 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3100 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3101 ? IP
::sanitizeIP( $dbkey )
3104 // Any remaining initial :s are illegal.
3105 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3110 $this->mDbkeyform
= $dbkey;
3111 $this->mUrlform
= wfUrlencode( $dbkey );
3113 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3119 * Get an array of Title objects linking to this Title
3120 * Also stores the IDs in the link cache.
3122 * WARNING: do not use this function on arbitrary user-supplied titles!
3123 * On heavily-used templates it will max out the memory.
3125 * @param $options Array: may be FOR UPDATE
3126 * @param $table String: table name
3127 * @param $prefix String: fields prefix
3128 * @return Array of Title objects linking here
3130 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3131 if ( count( $options ) > 0 ) {
3132 $db = wfGetDB( DB_MASTER
);
3134 $db = wfGetDB( DB_SLAVE
);
3138 array( 'page', $table ),
3139 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3141 "{$prefix}_from=page_id",
3142 "{$prefix}_namespace" => $this->getNamespace(),
3143 "{$prefix}_title" => $this->getDBkey() ),
3149 if ( $res->numRows() ) {
3150 $linkCache = LinkCache
::singleton();
3151 foreach ( $res as $row ) {
3152 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3154 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3155 $retVal[] = $titleObj;
3163 * Get an array of Title objects using this Title as a template
3164 * Also stores the IDs in the link cache.
3166 * WARNING: do not use this function on arbitrary user-supplied titles!
3167 * On heavily-used templates it will max out the memory.
3169 * @param $options Array: may be FOR UPDATE
3170 * @return Array of Title the Title objects linking here
3172 public function getTemplateLinksTo( $options = array() ) {
3173 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3177 * Get an array of Title objects linked from this Title
3178 * Also stores the IDs in the link cache.
3180 * WARNING: do not use this function on arbitrary user-supplied titles!
3181 * On heavily-used templates it will max out the memory.
3183 * @param $options Array: may be FOR UPDATE
3184 * @param $table String: table name
3185 * @param $prefix String: fields prefix
3186 * @return Array of Title objects linking here
3188 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3189 $id = $this->getArticleID();
3191 # If the page doesn't exist; there can't be any link from this page
3196 if ( count( $options ) > 0 ) {
3197 $db = wfGetDB( DB_MASTER
);
3199 $db = wfGetDB( DB_SLAVE
);
3202 $namespaceFiled = "{$prefix}_namespace";
3203 $titleField = "{$prefix}_title";
3206 array( $table, 'page' ),
3207 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3208 array( "{$prefix}_from" => $id ),
3211 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3215 if ( $res->numRows() ) {
3216 $linkCache = LinkCache
::singleton();
3217 foreach ( $res as $row ) {
3218 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3220 if ( $row->page_id
) {
3221 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3223 $linkCache->addBadLinkObj( $titleObj );
3225 $retVal[] = $titleObj;
3233 * Get an array of Title objects used on this Title as a template
3234 * Also stores the IDs in the link cache.
3236 * WARNING: do not use this function on arbitrary user-supplied titles!
3237 * On heavily-used templates it will max out the memory.
3239 * @param $options Array: may be FOR UPDATE
3240 * @return Array of Title the Title objects used here
3242 public function getTemplateLinksFrom( $options = array() ) {
3243 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3247 * Get an array of Title objects referring to non-existent articles linked from this page
3249 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3250 * @return Array of Title the Title objects
3252 public function getBrokenLinksFrom() {
3253 if ( $this->getArticleID() == 0 ) {
3254 # All links from article ID 0 are false positives
3258 $dbr = wfGetDB( DB_SLAVE
);
3259 $res = $dbr->select(
3260 array( 'page', 'pagelinks' ),
3261 array( 'pl_namespace', 'pl_title' ),
3263 'pl_from' => $this->getArticleID(),
3264 'page_namespace IS NULL'
3266 __METHOD__
, array(),
3270 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3276 foreach ( $res as $row ) {
3277 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3284 * Get a list of URLs to purge from the Squid cache when this
3287 * @return Array of String the URLs
3289 public function getSquidURLs() {
3291 $this->getInternalURL(),
3292 $this->getInternalURL( 'action=history' )
3295 $pageLang = $this->getPageLanguage();
3296 if ( $pageLang->hasVariants() ) {
3297 $variants = $pageLang->getVariants();
3298 foreach ( $variants as $vCode ) {
3299 $urls[] = $this->getInternalURL( '', $vCode );
3307 * Purge all applicable Squid URLs
3309 public function purgeSquid() {
3311 if ( $wgUseSquid ) {
3312 $urls = $this->getSquidURLs();
3313 $u = new SquidUpdate( $urls );
3319 * Move this page without authentication
3321 * @param $nt Title the new page Title
3322 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3324 public function moveNoAuth( &$nt ) {
3325 return $this->moveTo( $nt, false );
3329 * Check whether a given move operation would be valid.
3330 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3332 * @param $nt Title the new title
3333 * @param $auth Bool indicates whether $wgUser's permissions
3335 * @param $reason String is the log summary of the move, used for spam checking
3336 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3338 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3343 // Normally we'd add this to $errors, but we'll get
3344 // lots of syntax errors if $nt is not an object
3345 return array( array( 'badtitletext' ) );
3347 if ( $this->equals( $nt ) ) {
3348 $errors[] = array( 'selfmove' );
3350 if ( !$this->isMovable() ) {
3351 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3353 if ( $nt->getInterwiki() != '' ) {
3354 $errors[] = array( 'immobile-target-namespace-iw' );
3356 if ( !$nt->isMovable() ) {
3357 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3360 $oldid = $this->getArticleID();
3361 $newid = $nt->getArticleID();
3363 if ( strlen( $nt->getDBkey() ) < 1 ) {
3364 $errors[] = array( 'articleexists' );
3366 if ( ( $this->getDBkey() == '' ) ||
3368 ( $nt->getDBkey() == '' ) ) {
3369 $errors[] = array( 'badarticleerror' );
3372 // Image-specific checks
3373 if ( $this->getNamespace() == NS_FILE
) {
3374 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3377 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3378 $errors[] = array( 'nonfile-cannot-move-to-file' );
3382 $errors = wfMergeErrorArrays( $errors,
3383 $this->getUserPermissionsErrors( 'move', $wgUser ),
3384 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3385 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3386 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3389 $match = EditPage
::matchSummarySpamRegex( $reason );
3390 if ( $match !== false ) {
3391 // This is kind of lame, won't display nice
3392 $errors[] = array( 'spamprotectiontext' );
3396 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3397 $errors[] = array( 'hookaborted', $err );
3400 # The move is allowed only if (1) the target doesn't exist, or
3401 # (2) the target is a redirect to the source, and has no history
3402 # (so we can undo bad moves right after they're done).
3404 if ( 0 != $newid ) { # Target exists; check for validity
3405 if ( !$this->isValidMoveTarget( $nt ) ) {
3406 $errors[] = array( 'articleexists' );
3409 $tp = $nt->getTitleProtection();
3410 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3411 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3412 $errors[] = array( 'cantmove-titleprotected' );
3415 if ( empty( $errors ) ) {
3422 * Check if the requested move target is a valid file move target
3423 * @param Title $nt Target title
3424 * @return array List of errors
3426 protected function validateFileMoveOperation( $nt ) {
3431 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3433 $file = wfLocalFile( $this );
3434 if ( $file->exists() ) {
3435 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3436 $errors[] = array( 'imageinvalidfilename' );
3438 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3439 $errors[] = array( 'imagetypemismatch' );
3443 if ( $nt->getNamespace() != NS_FILE
) {
3444 $errors[] = array( 'imagenocrossnamespace' );
3445 // From here we want to do checks on a file object, so if we can't
3446 // create one, we must return.
3450 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3452 $destFile = wfLocalFile( $nt );
3453 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3454 $errors[] = array( 'file-exists-sharedrepo' );
3461 * Move a title to a new location
3463 * @param $nt Title the new title
3464 * @param $auth Bool indicates whether $wgUser's permissions
3466 * @param $reason String the reason for the move
3467 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3468 * Ignored if the user doesn't have the suppressredirect right.
3469 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3471 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3473 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3474 if ( is_array( $err ) ) {
3475 // Auto-block user's IP if the account was "hard" blocked
3476 $wgUser->spreadAnyEditBlock();
3479 // Check suppressredirect permission
3480 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3481 $createRedirect = true;
3484 // If it is a file, move it first.
3485 // It is done before all other moving stuff is done because it's hard to revert.
3486 $dbw = wfGetDB( DB_MASTER
);
3487 if ( $this->getNamespace() == NS_FILE
) {
3488 $file = wfLocalFile( $this );
3489 if ( $file->exists() ) {
3490 $status = $file->move( $nt );
3491 if ( !$status->isOk() ) {
3492 return $status->getErrorsArray();
3495 // Clear RepoGroup process cache
3496 RepoGroup
::singleton()->clearCache( $this );
3497 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3500 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3501 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3502 $protected = $this->isProtected();
3504 // Do the actual move
3505 $this->moveToInternal( $nt, $reason, $createRedirect );
3507 // Refresh the sortkey for this row. Be careful to avoid resetting
3508 // cl_timestamp, which may disturb time-based lists on some sites.
3509 $prefixes = $dbw->select(
3511 array( 'cl_sortkey_prefix', 'cl_to' ),
3512 array( 'cl_from' => $pageid ),
3515 foreach ( $prefixes as $prefixRow ) {
3516 $prefix = $prefixRow->cl_sortkey_prefix
;
3517 $catTo = $prefixRow->cl_to
;
3518 $dbw->update( 'categorylinks',
3520 'cl_sortkey' => Collation
::singleton()->getSortKey(
3521 $nt->getCategorySortkey( $prefix ) ),
3522 'cl_timestamp=cl_timestamp' ),
3524 'cl_from' => $pageid,
3525 'cl_to' => $catTo ),
3530 $redirid = $this->getArticleID();
3533 # Protect the redirect title as the title used to be...
3534 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3536 'pr_page' => $redirid,
3537 'pr_type' => 'pr_type',
3538 'pr_level' => 'pr_level',
3539 'pr_cascade' => 'pr_cascade',
3540 'pr_user' => 'pr_user',
3541 'pr_expiry' => 'pr_expiry'
3543 array( 'pr_page' => $pageid ),
3547 # Update the protection log
3548 $log = new LogPage( 'protect' );
3549 $comment = wfMessage(
3551 $this->getPrefixedText(),
3552 $nt->getPrefixedText()
3553 )->inContentLanguage()->text();
3555 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3557 // @todo FIXME: $params?
3558 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3562 $oldnamespace = $this->getNamespace() & ~
1;
3563 $newnamespace = $nt->getNamespace() & ~
1;
3564 $oldtitle = $this->getDBkey();
3565 $newtitle = $nt->getDBkey();
3567 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3568 WatchedItem
::duplicateEntries( $this, $nt );
3571 $dbw->commit( __METHOD__
);
3573 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3578 * Move page to a title which is either a redirect to the
3579 * source page or nonexistent
3581 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3582 * @param $reason String The reason for the move
3583 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3584 * if the user has the suppressredirect right
3585 * @throws MWException
3587 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3588 global $wgUser, $wgContLang;
3590 if ( $nt->exists() ) {
3591 $moveOverRedirect = true;
3592 $logType = 'move_redir';
3594 $moveOverRedirect = false;
3598 $redirectSuppressed = !$createRedirect;
3600 $logEntry = new ManualLogEntry( 'move', $logType );
3601 $logEntry->setPerformer( $wgUser );
3602 $logEntry->setTarget( $this );
3603 $logEntry->setComment( $reason );
3604 $logEntry->setParameters( array(
3605 '4::target' => $nt->getPrefixedText(),
3606 '5::noredir' => $redirectSuppressed ?
'1': '0',
3609 $formatter = LogFormatter
::newFromEntry( $logEntry );
3610 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3611 $comment = $formatter->getPlainActionText();
3613 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3615 # Truncate for whole multibyte characters.
3616 $comment = $wgContLang->truncate( $comment, 255 );
3618 $oldid = $this->getArticleID();
3620 $dbw = wfGetDB( DB_MASTER
);
3622 $newpage = WikiPage
::factory( $nt );
3624 if ( $moveOverRedirect ) {
3625 $newid = $nt->getArticleID();
3627 # Delete the old redirect. We don't save it to history since
3628 # by definition if we've got here it's rather uninteresting.
3629 # We have to remove it so that the next step doesn't trigger
3630 # a conflict on the unique namespace+title index...
3631 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3633 $newpage->doDeleteUpdates( $newid );
3636 # Save a null revision in the page's history notifying of the move
3637 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3638 if ( !is_object( $nullRevision ) ) {
3639 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3641 $nullRevId = $nullRevision->insertOn( $dbw );
3643 # Change the name of the target page:
3644 $dbw->update( 'page',
3646 'page_namespace' => $nt->getNamespace(),
3647 'page_title' => $nt->getDBkey(),
3649 /* WHERE */ array( 'page_id' => $oldid ),
3653 $this->resetArticleID( 0 );
3654 $nt->resetArticleID( $oldid );
3656 $newpage->updateRevisionOn( $dbw, $nullRevision );
3658 wfRunHooks( 'NewRevisionFromEditComplete',
3659 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3661 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3663 if ( !$moveOverRedirect ) {
3664 WikiPage
::onArticleCreate( $nt );
3667 # Recreate the redirect, this time in the other direction.
3668 if ( $redirectSuppressed ) {
3669 WikiPage
::onArticleDelete( $this );
3671 $mwRedir = MagicWord
::get( 'redirect' );
3672 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3673 $redirectArticle = WikiPage
::factory( $this );
3674 $newid = $redirectArticle->insertOn( $dbw );
3675 if ( $newid ) { // sanity
3676 $redirectRevision = new Revision( array(
3678 'comment' => $comment,
3679 'text' => $redirectText ) );
3680 $redirectRevision->insertOn( $dbw );
3681 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3683 wfRunHooks( 'NewRevisionFromEditComplete',
3684 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3686 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3691 $logid = $logEntry->insert();
3692 $logEntry->publish( $logid );
3696 * Move this page's subpages to be subpages of $nt
3698 * @param $nt Title Move target
3699 * @param $auth bool Whether $wgUser's permissions should be checked
3700 * @param $reason string The reason for the move
3701 * @param $createRedirect bool Whether to create redirects from the old subpages to
3702 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3703 * @return mixed array with old page titles as keys, and strings (new page titles) or
3704 * arrays (errors) as values, or an error array with numeric indices if no pages
3707 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3708 global $wgMaximumMovedPages;
3709 // Check permissions
3710 if ( !$this->userCan( 'move-subpages' ) ) {
3711 return array( 'cant-move-subpages' );
3713 // Do the source and target namespaces support subpages?
3714 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3715 return array( 'namespace-nosubpages',
3716 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3718 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3719 return array( 'namespace-nosubpages',
3720 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3723 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3726 foreach ( $subpages as $oldSubpage ) {
3728 if ( $count > $wgMaximumMovedPages ) {
3729 $retval[$oldSubpage->getPrefixedTitle()] =
3730 array( 'movepage-max-pages',
3731 $wgMaximumMovedPages );
3735 // We don't know whether this function was called before
3736 // or after moving the root page, so check both
3738 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3739 $oldSubpage->getArticleID() == $nt->getArticleID() )
3741 // When moving a page to a subpage of itself,
3742 // don't move it twice
3745 $newPageName = preg_replace(
3746 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3747 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3748 $oldSubpage->getDBkey() );
3749 if ( $oldSubpage->isTalkPage() ) {
3750 $newNs = $nt->getTalkPage()->getNamespace();
3752 $newNs = $nt->getSubjectPage()->getNamespace();
3754 # Bug 14385: we need makeTitleSafe because the new page names may
3755 # be longer than 255 characters.
3756 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3758 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3759 if ( $success === true ) {
3760 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3762 $retval[$oldSubpage->getPrefixedText()] = $success;
3769 * Checks if this page is just a one-rev redirect.
3770 * Adds lock, so don't use just for light purposes.
3774 public function isSingleRevRedirect() {
3775 $dbw = wfGetDB( DB_MASTER
);
3777 $row = $dbw->selectRow( 'page',
3778 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3781 array( 'FOR UPDATE' )
3783 # Cache some fields we may want
3784 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3785 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3786 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3787 if ( !$this->mRedirect
) {
3790 # Does the article have a history?
3791 $row = $dbw->selectField( array( 'page', 'revision' ),
3793 array( 'page_namespace' => $this->getNamespace(),
3794 'page_title' => $this->getDBkey(),
3796 'page_latest != rev_id'
3799 array( 'FOR UPDATE' )
3801 # Return true if there was no history
3802 return ( $row === false );
3806 * Checks if $this can be moved to a given Title
3807 * - Selects for update, so don't call it unless you mean business
3809 * @param $nt Title the new title to check
3812 public function isValidMoveTarget( $nt ) {
3813 # Is it an existing file?
3814 if ( $nt->getNamespace() == NS_FILE
) {
3815 $file = wfLocalFile( $nt );
3816 if ( $file->exists() ) {
3817 wfDebug( __METHOD__
. ": file exists\n" );
3821 # Is it a redirect with no history?
3822 if ( !$nt->isSingleRevRedirect() ) {
3823 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3826 # Get the article text
3827 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3828 if( !is_object( $rev ) ){
3831 $text = $rev->getText();
3832 # Does the redirect point to the source?
3833 # Or is it a broken self-redirect, usually caused by namespace collisions?
3835 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3836 $redirTitle = Title
::newFromText( $m[1] );
3837 if ( !is_object( $redirTitle ) ||
3838 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3839 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3840 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3845 wfDebug( __METHOD__
. ": failsafe\n" );
3852 * Get categories to which this Title belongs and return an array of
3853 * categories' names.
3855 * @return Array of parents in the form:
3856 * $parent => $currentarticle
3858 public function getParentCategories() {
3863 $titleKey = $this->getArticleID();
3865 if ( $titleKey === 0 ) {
3869 $dbr = wfGetDB( DB_SLAVE
);
3871 $res = $dbr->select( 'categorylinks', '*',
3873 'cl_from' => $titleKey,
3879 if ( $dbr->numRows( $res ) > 0 ) {
3880 foreach ( $res as $row ) {
3881 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3882 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3889 * Get a tree of parent categories
3891 * @param $children Array with the children in the keys, to check for circular refs
3892 * @return Array Tree of parent categories
3894 public function getParentCategoryTree( $children = array() ) {
3896 $parents = $this->getParentCategories();
3899 foreach ( $parents as $parent => $current ) {
3900 if ( array_key_exists( $parent, $children ) ) {
3901 # Circular reference
3902 $stack[$parent] = array();
3904 $nt = Title
::newFromText( $parent );
3906 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3916 * Get an associative array for selecting this title from
3919 * @return Array suitable for the $where parameter of DB::select()
3921 public function pageCond() {
3922 if ( $this->mArticleID
> 0 ) {
3923 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3924 return array( 'page_id' => $this->mArticleID
);
3926 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3931 * Get the revision ID of the previous revision
3933 * @param $revId Int Revision ID. Get the revision that was before this one.
3934 * @param $flags Int Title::GAID_FOR_UPDATE
3935 * @return Int|Bool Old revision ID, or FALSE if none exists
3937 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3938 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3939 $revId = $db->selectField( 'revision', 'rev_id',
3941 'rev_page' => $this->getArticleID( $flags ),
3942 'rev_id < ' . intval( $revId )
3945 array( 'ORDER BY' => 'rev_id DESC' )
3948 if ( $revId === false ) {
3951 return intval( $revId );
3956 * Get the revision ID of the next revision
3958 * @param $revId Int Revision ID. Get the revision that was after this one.
3959 * @param $flags Int Title::GAID_FOR_UPDATE
3960 * @return Int|Bool Next revision ID, or FALSE if none exists
3962 public function getNextRevisionID( $revId, $flags = 0 ) {
3963 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3964 $revId = $db->selectField( 'revision', 'rev_id',
3966 'rev_page' => $this->getArticleID( $flags ),
3967 'rev_id > ' . intval( $revId )
3970 array( 'ORDER BY' => 'rev_id' )
3973 if ( $revId === false ) {
3976 return intval( $revId );
3981 * Get the first revision of the page
3983 * @param $flags Int Title::GAID_FOR_UPDATE
3984 * @return Revision|Null if page doesn't exist
3986 public function getFirstRevision( $flags = 0 ) {
3987 $pageId = $this->getArticleID( $flags );
3989 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3990 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3991 array( 'rev_page' => $pageId ),
3993 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3996 return new Revision( $row );
4003 * Get the oldest revision timestamp of this page
4005 * @param $flags Int Title::GAID_FOR_UPDATE
4006 * @return String: MW timestamp
4008 public function getEarliestRevTime( $flags = 0 ) {
4009 $rev = $this->getFirstRevision( $flags );
4010 return $rev ?
$rev->getTimestamp() : null;
4014 * Check if this is a new page
4018 public function isNewPage() {
4019 $dbr = wfGetDB( DB_SLAVE
);
4020 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4024 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4028 public function isBigDeletion() {
4029 global $wgDeleteRevisionsLimit;
4031 if ( !$wgDeleteRevisionsLimit ) {
4035 $revCount = $this->estimateRevisionCount();
4036 return $revCount > $wgDeleteRevisionsLimit;
4040 * Get the approximate revision count of this page.
4044 public function estimateRevisionCount() {
4045 if ( !$this->exists() ) {
4049 if ( $this->mEstimateRevisions
=== null ) {
4050 $dbr = wfGetDB( DB_SLAVE
);
4051 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4052 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4055 return $this->mEstimateRevisions
;
4059 * Get the number of revisions between the given revision.
4060 * Used for diffs and other things that really need it.
4062 * @param $old int|Revision Old revision or rev ID (first before range)
4063 * @param $new int|Revision New revision or rev ID (first after range)
4064 * @return Int Number of revisions between these revisions.
4066 public function countRevisionsBetween( $old, $new ) {
4067 if ( !( $old instanceof Revision
) ) {
4068 $old = Revision
::newFromTitle( $this, (int)$old );
4070 if ( !( $new instanceof Revision
) ) {
4071 $new = Revision
::newFromTitle( $this, (int)$new );
4073 if ( !$old ||
!$new ) {
4074 return 0; // nothing to compare
4076 $dbr = wfGetDB( DB_SLAVE
);
4077 return (int)$dbr->selectField( 'revision', 'count(*)',
4079 'rev_page' => $this->getArticleID(),
4080 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4081 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4088 * Get the number of authors between the given revisions or revision IDs.
4089 * Used for diffs and other things that really need it.
4091 * @param $old int|Revision Old revision or rev ID (first before range by default)
4092 * @param $new int|Revision New revision or rev ID (first after range by default)
4093 * @param $limit int Maximum number of authors
4094 * @param $options string|array (Optional): Single option, or an array of options:
4095 * 'include_old' Include $old in the range; $new is excluded.
4096 * 'include_new' Include $new in the range; $old is excluded.
4097 * 'include_both' Include both $old and $new in the range.
4098 * Unknown option values are ignored.
4099 * @return int Number of revision authors in the range; zero if not both revisions exist
4101 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4102 if ( !( $old instanceof Revision
) ) {
4103 $old = Revision
::newFromTitle( $this, (int)$old );
4105 if ( !( $new instanceof Revision
) ) {
4106 $new = Revision
::newFromTitle( $this, (int)$new );
4108 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4109 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4110 // in the sanity check below?
4111 if ( !$old ||
!$new ) {
4112 return 0; // nothing to compare
4116 $options = (array) $options;
4117 if ( in_array( 'include_old', $options ) ) {
4120 if ( in_array( 'include_new', $options ) ) {
4123 if ( in_array( 'include_both', $options ) ) {
4127 // No DB query needed if $old and $new are the same or successive revisions:
4128 if ( $old->getId() === $new->getId() ) {
4129 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4130 } else if ( $old->getId() === $new->getParentId() ) {
4131 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4132 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4134 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4136 $dbr = wfGetDB( DB_SLAVE
);
4137 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4139 'rev_page' => $this->getArticleID(),
4140 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4141 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4143 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4145 return (int)$dbr->numRows( $res );
4149 * Compare with another title.
4151 * @param $title Title
4154 public function equals( Title
$title ) {
4155 // Note: === is necessary for proper matching of number-like titles.
4156 return $this->getInterwiki() === $title->getInterwiki()
4157 && $this->getNamespace() == $title->getNamespace()
4158 && $this->getDBkey() === $title->getDBkey();
4162 * Check if this title is a subpage of another title
4164 * @param $title Title
4167 public function isSubpageOf( Title
$title ) {
4168 return $this->getInterwiki() === $title->getInterwiki()
4169 && $this->getNamespace() == $title->getNamespace()
4170 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4174 * Check if page exists. For historical reasons, this function simply
4175 * checks for the existence of the title in the page table, and will
4176 * thus return false for interwiki links, special pages and the like.
4177 * If you want to know if a title can be meaningfully viewed, you should
4178 * probably call the isKnown() method instead.
4182 public function exists() {
4183 return $this->getArticleID() != 0;
4187 * Should links to this title be shown as potentially viewable (i.e. as
4188 * "bluelinks"), even if there's no record by this title in the page
4191 * This function is semi-deprecated for public use, as well as somewhat
4192 * misleadingly named. You probably just want to call isKnown(), which
4193 * calls this function internally.
4195 * (ISSUE: Most of these checks are cheap, but the file existence check
4196 * can potentially be quite expensive. Including it here fixes a lot of
4197 * existing code, but we might want to add an optional parameter to skip
4198 * it and any other expensive checks.)
4202 public function isAlwaysKnown() {
4206 * Allows overriding default behaviour for determining if a page exists.
4207 * If $isKnown is kept as null, regular checks happen. If it's
4208 * a boolean, this value is returned by the isKnown method.
4212 * @param Title $title
4213 * @param boolean|null $isKnown
4215 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4217 if ( !is_null( $isKnown ) ) {
4221 if ( $this->mInterwiki
!= '' ) {
4222 return true; // any interwiki link might be viewable, for all we know
4225 switch( $this->mNamespace
) {
4228 // file exists, possibly in a foreign repo
4229 return (bool)wfFindFile( $this );
4231 // valid special page
4232 return SpecialPageFactory
::exists( $this->getDBkey() );
4234 // selflink, possibly with fragment
4235 return $this->mDbkeyform
== '';
4237 // known system message
4238 return $this->hasSourceText() !== false;
4245 * Does this title refer to a page that can (or might) be meaningfully
4246 * viewed? In particular, this function may be used to determine if
4247 * links to the title should be rendered as "bluelinks" (as opposed to
4248 * "redlinks" to non-existent pages).
4249 * Adding something else to this function will cause inconsistency
4250 * since LinkHolderArray calls isAlwaysKnown() and does its own
4251 * page existence check.
4255 public function isKnown() {
4256 return $this->isAlwaysKnown() ||
$this->exists();
4260 * Does this page have source text?
4264 public function hasSourceText() {
4265 if ( $this->exists() ) {
4269 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4270 // If the page doesn't exist but is a known system message, default
4271 // message content will be displayed, same for language subpages-
4272 // Use always content language to avoid loading hundreds of languages
4273 // to get the link color.
4275 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4276 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4277 return $message->exists();
4284 * Get the default message text or false if the message doesn't exist
4286 * @return String or false
4288 public function getDefaultMessageText() {
4291 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4295 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4296 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4298 if ( $message->exists() ) {
4299 return $message->plain();
4306 * Updates page_touched for this page; called from LinksUpdate.php
4308 * @return Bool true if the update succeded
4310 public function invalidateCache() {
4311 if ( wfReadOnly() ) {
4314 $dbw = wfGetDB( DB_MASTER
);
4315 $success = $dbw->update(
4317 array( 'page_touched' => $dbw->timestamp() ),
4321 HTMLFileCache
::clearFileCache( $this );
4326 * Update page_touched timestamps and send squid purge messages for
4327 * pages linking to this title. May be sent to the job queue depending
4328 * on the number of links. Typically called on create and delete.
4330 public function touchLinks() {
4331 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4334 if ( $this->getNamespace() == NS_CATEGORY
) {
4335 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4341 * Get the last touched timestamp
4343 * @param $db DatabaseBase: optional db
4344 * @return String last-touched timestamp
4346 public function getTouched( $db = null ) {
4347 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4348 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4353 * Get the timestamp when this page was updated since the user last saw it.
4356 * @return String|Null
4358 public function getNotificationTimestamp( $user = null ) {
4359 global $wgUser, $wgShowUpdatedMarker;
4360 // Assume current user if none given
4364 // Check cache first
4365 $uid = $user->getId();
4366 // avoid isset here, as it'll return false for null entries
4367 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4368 return $this->mNotificationTimestamp
[$uid];
4370 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4371 return $this->mNotificationTimestamp
[$uid] = false;
4373 // Don't cache too much!
4374 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4375 $this->mNotificationTimestamp
= array();
4377 $dbr = wfGetDB( DB_SLAVE
);
4378 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4379 'wl_notificationtimestamp',
4381 'wl_user' => $user->getId(),
4382 'wl_namespace' => $this->getNamespace(),
4383 'wl_title' => $this->getDBkey(),
4387 return $this->mNotificationTimestamp
[$uid];
4391 * Generate strings used for xml 'id' names in monobook tabs
4393 * @param $prepend string defaults to 'nstab-'
4394 * @return String XML 'id' name
4396 public function getNamespaceKey( $prepend = 'nstab-' ) {
4398 // Gets the subject namespace if this title
4399 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4400 // Checks if cononical namespace name exists for namespace
4401 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4402 // Uses canonical namespace name
4403 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4405 // Uses text of namespace
4406 $namespaceKey = $this->getSubjectNsText();
4408 // Makes namespace key lowercase
4409 $namespaceKey = $wgContLang->lc( $namespaceKey );
4411 if ( $namespaceKey == '' ) {
4412 $namespaceKey = 'main';
4414 // Changes file to image for backwards compatibility
4415 if ( $namespaceKey == 'file' ) {
4416 $namespaceKey = 'image';
4418 return $prepend . $namespaceKey;
4422 * Get all extant redirects to this Title
4424 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4425 * @return Array of Title redirects to this title
4427 public function getRedirectsHere( $ns = null ) {
4430 $dbr = wfGetDB( DB_SLAVE
);
4432 'rd_namespace' => $this->getNamespace(),
4433 'rd_title' => $this->getDBkey(),
4436 if ( $this->isExternal() ) {
4437 $where['rd_interwiki'] = $this->getInterwiki();
4439 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4441 if ( !is_null( $ns ) ) {
4442 $where['page_namespace'] = $ns;
4445 $res = $dbr->select(
4446 array( 'redirect', 'page' ),
4447 array( 'page_namespace', 'page_title' ),
4452 foreach ( $res as $row ) {
4453 $redirs[] = self
::newFromRow( $row );
4459 * Check if this Title is a valid redirect target
4463 public function isValidRedirectTarget() {
4464 global $wgInvalidRedirectTargets;
4466 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4467 if ( $this->isSpecial( 'Userlogout' ) ) {
4471 foreach ( $wgInvalidRedirectTargets as $target ) {
4472 if ( $this->isSpecial( $target ) ) {
4481 * Get a backlink cache object
4483 * @return BacklinkCache
4485 public function getBacklinkCache() {
4486 return BacklinkCache
::get( $this );
4490 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4494 public function canUseNoindex() {
4495 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4497 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4498 ?
$wgContentNamespaces
4499 : $wgExemptFromUserRobotsControl;
4501 return !in_array( $this->mNamespace
, $bannedNamespaces );
4506 * Returns the raw sort key to be used for categories, with the specified
4507 * prefix. This will be fed to Collation::getSortKey() to get a
4508 * binary sortkey that can be used for actual sorting.
4510 * @param $prefix string The prefix to be used, specified using
4511 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4515 public function getCategorySortkey( $prefix = '' ) {
4516 $unprefixed = $this->getText();
4518 // Anything that uses this hook should only depend
4519 // on the Title object passed in, and should probably
4520 // tell the users to run updateCollations.php --force
4521 // in order to re-sort existing category relations.
4522 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4523 if ( $prefix !== '' ) {
4524 # Separate with a line feed, so the unprefixed part is only used as
4525 # a tiebreaker when two pages have the exact same prefix.
4526 # In UCA, tab is the only character that can sort above LF
4527 # so we strip both of them from the original prefix.
4528 $prefix = strtr( $prefix, "\n\t", ' ' );
4529 return "$prefix\n$unprefixed";
4535 * Get the language in which the content of this page is written in
4536 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4537 * e.g. $wgLang (such as special pages, which are in the user language).
4542 public function getPageLanguage() {
4544 if ( $this->isSpecialPage() ) {
4545 // special pages are in the user language
4547 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4548 // css/js should always be LTR and is, in fact, English
4549 return wfGetLangObj( 'en' );
4550 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4551 // Parse mediawiki messages with correct target language
4552 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4553 return wfGetLangObj( $lang );
4556 // If nothing special, it should be in the wiki content language
4557 $pageLang = $wgContLang;
4558 // Hook at the end because we don't want to override the above stuff
4559 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4560 return wfGetLangObj( $pageLang );
4564 * Get the language in which the content of this page is written when
4565 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4566 * e.g. $wgLang (such as special pages, which are in the user language).
4571 public function getPageViewLanguage() {
4572 $pageLang = $this->getPageLanguage();
4573 // If this is nothing special (so the content is converted when viewed)
4574 if ( !$this->isSpecialPage()
4575 && !$this->isCssOrJsPage() && !$this->isCssJsSubpage()
4576 && $this->getNamespace() !== NS_MEDIAWIKI
4578 // If the user chooses a variant, the content is actually
4579 // in a language whose code is the variant code.
4580 $variant = $pageLang->getPreferredVariant();
4581 if ( $pageLang->getCode() !== $variant ) {
4582 $pageLang = Language
::factory( $variant );