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 * @see self::getLocalURL
1400 * @return String the URL
1402 public function getLinkURL( $query = '', $query2 = false ) {
1403 wfProfileIn( __METHOD__
);
1404 if ( $this->isExternal() ) {
1405 $ret = $this->getFullURL( $query, $query2 );
1406 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1407 $ret = $this->getFragmentForURL();
1409 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1411 wfProfileOut( __METHOD__
);
1416 * Get an HTML-escaped version of the URL form, suitable for
1417 * using in a link, without a server name or fragment
1419 * See getLocalURL for the arguments.
1421 * @see self::getLocalURL
1422 * @param $query string
1423 * @param $query2 bool|string
1424 * @return String the URL
1426 public function escapeLocalURL( $query = '', $query2 = false ) {
1427 wfDeprecated( __METHOD__
, '1.19' );
1428 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1432 * Get an HTML-escaped version of the URL form, suitable for
1433 * using in a link, including the server name and fragment
1435 * See getLocalURL for the arguments.
1437 * @see self::getLocalURL
1438 * @return String the URL
1440 public function escapeFullURL( $query = '', $query2 = false ) {
1441 wfDeprecated( __METHOD__
, '1.19' );
1442 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1446 * Get the URL form for an internal link.
1447 * - Used in various Squid-related code, in case we have a different
1448 * internal hostname for the server from the exposed one.
1450 * This uses $wgInternalServer to qualify the path, or $wgServer
1451 * if $wgInternalServer is not set. If the server variable used is
1452 * protocol-relative, the URL will be expanded to http://
1454 * See getLocalURL for the arguments.
1456 * @see self::getLocalURL
1457 * @return String the URL
1459 public function getInternalURL( $query = '', $query2 = false ) {
1460 global $wgInternalServer, $wgServer;
1461 $query = self
::fixUrlQueryArgs( $query, $query2 );
1462 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1463 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1464 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1469 * Get the URL for a canonical link, for use in things like IRC and
1470 * e-mail notifications. Uses $wgCanonicalServer and the
1471 * GetCanonicalURL hook.
1473 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1475 * See getLocalURL for the arguments.
1477 * @see self::getLocalURL
1478 * @return string The URL
1481 public function getCanonicalURL( $query = '', $query2 = false ) {
1482 $query = self
::fixUrlQueryArgs( $query, $query2 );
1483 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1484 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1489 * HTML-escaped version of getCanonicalURL()
1491 * See getLocalURL for the arguments.
1493 * @see self::getLocalURL
1497 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1498 wfDeprecated( __METHOD__
, '1.19' );
1499 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1503 * Get the edit URL for this Title
1505 * @return String the URL, or a null string if this is an
1508 public function getEditURL() {
1509 if ( $this->mInterwiki
!= '' ) {
1512 $s = $this->getLocalURL( 'action=edit' );
1518 * Is $wgUser watching this page?
1520 * @deprecated in 1.20; use User::isWatched() instead.
1523 public function userIsWatching() {
1526 if ( is_null( $this->mWatched
) ) {
1527 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1528 $this->mWatched
= false;
1530 $this->mWatched
= $wgUser->isWatched( $this );
1533 return $this->mWatched
;
1537 * Can $wgUser read this page?
1539 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1541 * @todo fold these checks into userCan()
1543 public function userCanRead() {
1544 wfDeprecated( __METHOD__
, '1.19' );
1545 return $this->userCan( 'read' );
1549 * Can $user perform $action on this page?
1550 * This skips potentially expensive cascading permission checks
1551 * as well as avoids expensive error formatting
1553 * Suitable for use for nonessential UI controls in common cases, but
1554 * _not_ for functional access control.
1556 * May provide false positives, but should never provide a false negative.
1558 * @param $action String action that permission needs to be checked for
1559 * @param $user User to check (since 1.19); $wgUser will be used if not
1563 public function quickUserCan( $action, $user = null ) {
1564 return $this->userCan( $action, $user, false );
1568 * Can $user perform $action on this page?
1570 * @param $action String action that permission needs to be checked for
1571 * @param $user User to check (since 1.19); $wgUser will be used if not
1573 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1574 * unnecessary queries.
1577 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1578 if ( !$user instanceof User
) {
1582 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1586 * Can $user perform $action on this page?
1588 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1590 * @param $action String action that permission needs to be checked for
1591 * @param $user User to check
1592 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1593 * queries by skipping checks for cascading protections and user blocks.
1594 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1595 * whose corresponding errors may be ignored.
1596 * @return Array of arguments to wfMessage to explain permissions problems.
1598 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1599 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1601 // Remove the errors being ignored.
1602 foreach ( $errors as $index => $error ) {
1603 $error_key = is_array( $error ) ?
$error[0] : $error;
1605 if ( in_array( $error_key, $ignoreErrors ) ) {
1606 unset( $errors[$index] );
1614 * Permissions checks that fail most often, and which are easiest to test.
1616 * @param $action String the action to check
1617 * @param $user User user to check
1618 * @param $errors Array list of current errors
1619 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1620 * @param $short Boolean short circuit on first error
1622 * @return Array list of errors
1624 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1625 if ( $action == 'create' ) {
1626 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1627 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1628 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1630 } elseif ( $action == 'move' ) {
1631 if ( !$user->isAllowed( 'move-rootuserpages' )
1632 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1633 // Show user page-specific message only if the user can move other pages
1634 $errors[] = array( 'cant-move-user-page' );
1637 // Check if user is allowed to move files if it's a file
1638 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1639 $errors[] = array( 'movenotallowedfile' );
1642 if ( !$user->isAllowed( 'move' ) ) {
1643 // User can't move anything
1644 global $wgGroupPermissions;
1645 $userCanMove = false;
1646 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1647 $userCanMove = $wgGroupPermissions['user']['move'];
1649 $autoconfirmedCanMove = false;
1650 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1651 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1653 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1654 // custom message if logged-in users without any special rights can move
1655 $errors[] = array( 'movenologintext' );
1657 $errors[] = array( 'movenotallowed' );
1660 } elseif ( $action == 'move-target' ) {
1661 if ( !$user->isAllowed( 'move' ) ) {
1662 // User can't move anything
1663 $errors[] = array( 'movenotallowed' );
1664 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1665 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1666 // Show user page-specific message only if the user can move other pages
1667 $errors[] = array( 'cant-move-to-user-page' );
1669 } elseif ( !$user->isAllowed( $action ) ) {
1670 $errors[] = $this->missingPermissionError( $action, $short );
1677 * Add the resulting error code to the errors array
1679 * @param $errors Array list of current errors
1680 * @param $result Mixed result of errors
1682 * @return Array list of errors
1684 private function resultToError( $errors, $result ) {
1685 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1686 // A single array representing an error
1687 $errors[] = $result;
1688 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1689 // A nested array representing multiple errors
1690 $errors = array_merge( $errors, $result );
1691 } elseif ( $result !== '' && is_string( $result ) ) {
1692 // A string representing a message-id
1693 $errors[] = array( $result );
1694 } elseif ( $result === false ) {
1695 // a generic "We don't want them to do that"
1696 $errors[] = array( 'badaccess-group0' );
1702 * Check various permission hooks
1704 * @param $action String the action to check
1705 * @param $user User user to check
1706 * @param $errors Array list of current errors
1707 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1708 * @param $short Boolean short circuit on first error
1710 * @return Array list of errors
1712 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1713 // Use getUserPermissionsErrors instead
1715 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1716 return $result ?
array() : array( array( 'badaccess-group0' ) );
1718 // Check getUserPermissionsErrors hook
1719 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1720 $errors = $this->resultToError( $errors, $result );
1722 // Check getUserPermissionsErrorsExpensive hook
1723 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1724 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1725 $errors = $this->resultToError( $errors, $result );
1732 * Check permissions on special pages & namespaces
1734 * @param $action String the action to check
1735 * @param $user User user to check
1736 * @param $errors Array list of current errors
1737 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1738 * @param $short Boolean short circuit on first error
1740 * @return Array list of errors
1742 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1743 # Only 'createaccount' and 'execute' can be performed on
1744 # special pages, which don't actually exist in the DB.
1745 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1746 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1747 $errors[] = array( 'ns-specialprotected' );
1750 # Check $wgNamespaceProtection for restricted namespaces
1751 if ( $this->isNamespaceProtected( $user ) ) {
1752 $ns = $this->mNamespace
== NS_MAIN ?
1753 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1754 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1755 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1762 * Check CSS/JS sub-page permissions
1764 * @param $action String the action to check
1765 * @param $user User user to check
1766 * @param $errors Array list of current errors
1767 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1768 * @param $short Boolean short circuit on first error
1770 * @return Array list of errors
1772 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1773 # Protect css/js subpages of user pages
1774 # XXX: this might be better using restrictions
1775 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1776 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1777 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1778 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1779 $errors[] = array( 'customcssprotected' );
1780 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1781 $errors[] = array( 'customjsprotected' );
1789 * Check against page_restrictions table requirements on this
1790 * page. The user must possess all required rights for this
1793 * @param $action String the action to check
1794 * @param $user User user to check
1795 * @param $errors Array list of current errors
1796 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1797 * @param $short Boolean short circuit on first error
1799 * @return Array list of errors
1801 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1802 foreach ( $this->getRestrictions( $action ) as $right ) {
1803 // Backwards compatibility, rewrite sysop -> protect
1804 if ( $right == 'sysop' ) {
1807 if ( $right != '' && !$user->isAllowed( $right ) ) {
1808 // Users with 'editprotected' permission can edit protected pages
1809 // without cascading option turned on.
1810 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1811 ||
$this->mCascadeRestriction
)
1813 $errors[] = array( 'protectedpagetext', $right );
1822 * Check restrictions on cascading pages.
1824 * @param $action String the action to check
1825 * @param $user User to check
1826 * @param $errors Array list of current errors
1827 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1828 * @param $short Boolean short circuit on first error
1830 * @return Array list of errors
1832 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1833 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1834 # We /could/ use the protection level on the source page, but it's
1835 # fairly ugly as we have to establish a precedence hierarchy for pages
1836 # included by multiple cascade-protected pages. So just restrict
1837 # it to people with 'protect' permission, as they could remove the
1838 # protection anyway.
1839 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1840 # Cascading protection depends on more than this page...
1841 # Several cascading protected pages may include this page...
1842 # Check each cascading level
1843 # This is only for protection restrictions, not for all actions
1844 if ( isset( $restrictions[$action] ) ) {
1845 foreach ( $restrictions[$action] as $right ) {
1846 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1847 if ( $right != '' && !$user->isAllowed( $right ) ) {
1849 foreach ( $cascadingSources as $page )
1850 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1851 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1861 * Check action permissions not already checked in checkQuickPermissions
1863 * @param $action String the action to check
1864 * @param $user User to check
1865 * @param $errors Array list of current errors
1866 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1867 * @param $short Boolean short circuit on first error
1869 * @return Array list of errors
1871 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1872 global $wgDeleteRevisionsLimit, $wgLang;
1874 if ( $action == 'protect' ) {
1875 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1876 // If they can't edit, they shouldn't protect.
1877 $errors[] = array( 'protect-cantedit' );
1879 } elseif ( $action == 'create' ) {
1880 $title_protection = $this->getTitleProtection();
1881 if( $title_protection ) {
1882 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1883 $title_protection['pt_create_perm'] = 'protect'; // B/C
1885 if( $title_protection['pt_create_perm'] == '' ||
1886 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1888 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1891 } elseif ( $action == 'move' ) {
1892 // Check for immobile pages
1893 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1894 // Specific message for this case
1895 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1896 } elseif ( !$this->isMovable() ) {
1897 // Less specific message for rarer cases
1898 $errors[] = array( 'immobile-source-page' );
1900 } elseif ( $action == 'move-target' ) {
1901 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1902 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1903 } elseif ( !$this->isMovable() ) {
1904 $errors[] = array( 'immobile-target-page' );
1906 } elseif ( $action == 'delete' ) {
1907 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1908 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1910 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1917 * Check that the user isn't blocked from editting.
1919 * @param $action String the action to check
1920 * @param $user User to check
1921 * @param $errors Array list of current errors
1922 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1923 * @param $short Boolean short circuit on first error
1925 * @return Array list of errors
1927 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1928 // Account creation blocks handled at userlogin.
1929 // Unblocking handled in SpecialUnblock
1930 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1934 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1936 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1937 $errors[] = array( 'confirmedittext' );
1940 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1941 // Don't block the user from editing their own talk page unless they've been
1942 // explicitly blocked from that too.
1943 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1944 $block = $user->getBlock();
1946 // This is from OutputPage::blockedPage
1947 // Copied at r23888 by werdna
1949 $id = $user->blockedBy();
1950 $reason = $user->blockedFor();
1951 if ( $reason == '' ) {
1952 $reason = wfMessage( 'blockednoreason' )->text();
1954 $ip = $user->getRequest()->getIP();
1956 if ( is_numeric( $id ) ) {
1957 $name = User
::whoIs( $id );
1962 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1963 $blockid = $block->getId();
1964 $blockExpiry = $block->getExpiry();
1965 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
1966 if ( $blockExpiry == 'infinity' ) {
1967 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1969 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1972 $intended = strval( $block->getTarget() );
1974 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1975 $blockid, $blockExpiry, $intended, $blockTimestamp );
1982 * Check that the user is allowed to read this page.
1984 * @param $action String the action to check
1985 * @param $user User to check
1986 * @param $errors Array list of current errors
1987 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1988 * @param $short Boolean short circuit on first error
1990 * @return Array list of errors
1992 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1993 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
1994 static $useShortcut = null;
1996 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1997 if ( is_null( $useShortcut ) ) {
1998 $useShortcut = true;
1999 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2000 # Not a public wiki, so no shortcut
2001 $useShortcut = false;
2002 } elseif ( !empty( $wgRevokePermissions ) ) {
2004 * Iterate through each group with permissions being revoked (key not included since we don't care
2005 * what the group name is), then check if the read permission is being revoked. If it is, then
2006 * we don't use the shortcut below since the user might not be able to read, even though anon
2007 * reading is allowed.
2009 foreach ( $wgRevokePermissions as $perms ) {
2010 if ( !empty( $perms['read'] ) ) {
2011 # We might be removing the read right from the user, so no shortcut
2012 $useShortcut = false;
2019 $whitelisted = false;
2020 if ( $useShortcut ) {
2021 # Shortcut for public wikis, allows skipping quite a bit of code
2022 $whitelisted = true;
2023 } elseif ( $user->isAllowed( 'read' ) ) {
2024 # If the user is allowed to read pages, he is allowed to read all pages
2025 $whitelisted = true;
2026 } elseif ( $this->isSpecial( 'Userlogin' )
2027 ||
$this->isSpecial( 'ChangePassword' )
2028 ||
$this->isSpecial( 'PasswordReset' )
2030 # Always grant access to the login page.
2031 # Even anons need to be able to log in.
2032 $whitelisted = true;
2033 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2034 # Time to check the whitelist
2035 # Only do these checks is there's something to check against
2036 $name = $this->getPrefixedText();
2037 $dbName = $this->getPrefixedDBKey();
2039 // Check for explicit whitelisting with and without underscores
2040 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2041 $whitelisted = true;
2042 } elseif ( $this->getNamespace() == NS_MAIN
) {
2043 # Old settings might have the title prefixed with
2044 # a colon for main-namespace pages
2045 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2046 $whitelisted = true;
2048 } elseif ( $this->isSpecialPage() ) {
2049 # If it's a special page, ditch the subpage bit and check again
2050 $name = $this->getDBkey();
2051 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2052 if ( $name !== false ) {
2053 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2054 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2055 $whitelisted = true;
2061 if ( !$whitelisted ) {
2062 # If the title is not whitelisted, give extensions a chance to do so...
2063 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2064 if ( !$whitelisted ) {
2065 $errors[] = $this->missingPermissionError( $action, $short );
2073 * Get a description array when the user doesn't have the right to perform
2074 * $action (i.e. when User::isAllowed() returns false)
2076 * @param $action String the action to check
2077 * @param $short Boolean short circuit on first error
2078 * @return Array list of errors
2080 private function missingPermissionError( $action, $short ) {
2081 // We avoid expensive display logic for quickUserCan's and such
2083 return array( 'badaccess-group0' );
2086 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2087 User
::getGroupsWithPermission( $action ) );
2089 if ( count( $groups ) ) {
2093 $wgLang->commaList( $groups ),
2097 return array( 'badaccess-group0' );
2102 * Can $user perform $action on this page? This is an internal function,
2103 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2104 * checks on wfReadOnly() and blocks)
2106 * @param $action String action that permission needs to be checked for
2107 * @param $user User to check
2108 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2109 * @param $short Bool Set this to true to stop after the first permission error.
2110 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2112 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2113 wfProfileIn( __METHOD__
);
2115 # Read has special handling
2116 if ( $action == 'read' ) {
2118 'checkPermissionHooks',
2119 'checkReadPermissions',
2123 'checkQuickPermissions',
2124 'checkPermissionHooks',
2125 'checkSpecialsAndNSPermissions',
2126 'checkCSSandJSPermissions',
2127 'checkPageRestrictions',
2128 'checkCascadingSourcesRestrictions',
2129 'checkActionPermissions',
2135 while( count( $checks ) > 0 &&
2136 !( $short && count( $errors ) > 0 ) ) {
2137 $method = array_shift( $checks );
2138 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2141 wfProfileOut( __METHOD__
);
2146 * Protect css subpages of user pages: can $wgUser edit
2149 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2152 public function userCanEditCssSubpage() {
2154 wfDeprecated( __METHOD__
, '1.19' );
2155 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2156 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2160 * Protect js subpages of user pages: can $wgUser edit
2163 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2166 public function userCanEditJsSubpage() {
2168 wfDeprecated( __METHOD__
, '1.19' );
2169 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2170 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2174 * Get a filtered list of all restriction types supported by this wiki.
2175 * @param bool $exists True to get all restriction types that apply to
2176 * titles that do exist, False for all restriction types that apply to
2177 * titles that do not exist
2180 public static function getFilteredRestrictionTypes( $exists = true ) {
2181 global $wgRestrictionTypes;
2182 $types = $wgRestrictionTypes;
2184 # Remove the create restriction for existing titles
2185 $types = array_diff( $types, array( 'create' ) );
2187 # Only the create and upload restrictions apply to non-existing titles
2188 $types = array_intersect( $types, array( 'create', 'upload' ) );
2194 * Returns restriction types for the current Title
2196 * @return array applicable restriction types
2198 public function getRestrictionTypes() {
2199 if ( $this->isSpecialPage() ) {
2203 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2205 if ( $this->getNamespace() != NS_FILE
) {
2206 # Remove the upload restriction for non-file titles
2207 $types = array_diff( $types, array( 'upload' ) );
2210 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2212 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2213 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2219 * Is this title subject to title protection?
2220 * Title protection is the one applied against creation of such title.
2222 * @return Mixed An associative array representing any existent title
2223 * protection, or false if there's none.
2225 private function getTitleProtection() {
2226 // Can't protect pages in special namespaces
2227 if ( $this->getNamespace() < 0 ) {
2231 // Can't protect pages that exist.
2232 if ( $this->exists() ) {
2236 if ( !isset( $this->mTitleProtection
) ) {
2237 $dbr = wfGetDB( DB_SLAVE
);
2238 $res = $dbr->select( 'protected_titles', '*',
2239 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2242 // fetchRow returns false if there are no rows.
2243 $this->mTitleProtection
= $dbr->fetchRow( $res );
2245 return $this->mTitleProtection
;
2249 * Update the title protection status
2251 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2252 * @param $create_perm String Permission required for creation
2253 * @param $reason String Reason for protection
2254 * @param $expiry String Expiry timestamp
2255 * @return boolean true
2257 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2258 wfDeprecated( __METHOD__
, '1.19' );
2262 $limit = array( 'create' => $create_perm );
2263 $expiry = array( 'create' => $expiry );
2265 $page = WikiPage
::factory( $this );
2266 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2268 return $status->isOK();
2272 * Remove any title protection due to page existing
2274 public function deleteTitleProtection() {
2275 $dbw = wfGetDB( DB_MASTER
);
2279 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2282 $this->mTitleProtection
= false;
2286 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2288 * @param $action String Action to check (default: edit)
2291 public function isSemiProtected( $action = 'edit' ) {
2292 if ( $this->exists() ) {
2293 $restrictions = $this->getRestrictions( $action );
2294 if ( count( $restrictions ) > 0 ) {
2295 foreach ( $restrictions as $restriction ) {
2296 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2306 # If it doesn't exist, it can't be protected
2312 * Does the title correspond to a protected article?
2314 * @param $action String the action the page is protected from,
2315 * by default checks all actions.
2318 public function isProtected( $action = '' ) {
2319 global $wgRestrictionLevels;
2321 $restrictionTypes = $this->getRestrictionTypes();
2323 # Special pages have inherent protection
2324 if( $this->isSpecialPage() ) {
2328 # Check regular protection levels
2329 foreach ( $restrictionTypes as $type ) {
2330 if ( $action == $type ||
$action == '' ) {
2331 $r = $this->getRestrictions( $type );
2332 foreach ( $wgRestrictionLevels as $level ) {
2333 if ( in_array( $level, $r ) && $level != '' ) {
2344 * Determines if $user is unable to edit this page because it has been protected
2345 * by $wgNamespaceProtection.
2347 * @param $user User object to check permissions
2350 public function isNamespaceProtected( User
$user ) {
2351 global $wgNamespaceProtection;
2353 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2354 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2355 if ( $right != '' && !$user->isAllowed( $right ) ) {
2364 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2366 * @return Bool If the page is subject to cascading restrictions.
2368 public function isCascadeProtected() {
2369 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2370 return ( $sources > 0 );
2374 * Cascading protection: Get the source of any cascading restrictions on this page.
2376 * @param $getPages Bool Whether or not to retrieve the actual pages
2377 * that the restrictions have come from.
2378 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2379 * have come, false for none, or true if such restrictions exist, but $getPages
2380 * was not set. The restriction array is an array of each type, each of which
2381 * contains a array of unique groups.
2383 public function getCascadeProtectionSources( $getPages = true ) {
2385 $pagerestrictions = array();
2387 if ( isset( $this->mCascadeSources
) && $getPages ) {
2388 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2389 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2390 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2393 wfProfileIn( __METHOD__
);
2395 $dbr = wfGetDB( DB_SLAVE
);
2397 if ( $this->getNamespace() == NS_FILE
) {
2398 $tables = array( 'imagelinks', 'page_restrictions' );
2399 $where_clauses = array(
2400 'il_to' => $this->getDBkey(),
2405 $tables = array( 'templatelinks', 'page_restrictions' );
2406 $where_clauses = array(
2407 'tl_namespace' => $this->getNamespace(),
2408 'tl_title' => $this->getDBkey(),
2415 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2416 'pr_expiry', 'pr_type', 'pr_level' );
2417 $where_clauses[] = 'page_id=pr_page';
2420 $cols = array( 'pr_expiry' );
2423 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2425 $sources = $getPages ?
array() : false;
2426 $now = wfTimestampNow();
2427 $purgeExpired = false;
2429 foreach ( $res as $row ) {
2430 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2431 if ( $expiry > $now ) {
2433 $page_id = $row->pr_page
;
2434 $page_ns = $row->page_namespace
;
2435 $page_title = $row->page_title
;
2436 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2437 # Add groups needed for each restriction type if its not already there
2438 # Make sure this restriction type still exists
2440 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2441 $pagerestrictions[$row->pr_type
] = array();
2444 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2445 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2446 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2452 // Trigger lazy purge of expired restrictions from the db
2453 $purgeExpired = true;
2456 if ( $purgeExpired ) {
2457 Title
::purgeExpiredRestrictions();
2461 $this->mCascadeSources
= $sources;
2462 $this->mCascadingRestrictions
= $pagerestrictions;
2464 $this->mHasCascadingRestrictions
= $sources;
2467 wfProfileOut( __METHOD__
);
2468 return array( $sources, $pagerestrictions );
2472 * Accessor/initialisation for mRestrictions
2474 * @param $action String action that permission needs to be checked for
2475 * @return Array of Strings the array of groups allowed to edit this article
2477 public function getRestrictions( $action ) {
2478 if ( !$this->mRestrictionsLoaded
) {
2479 $this->loadRestrictions();
2481 return isset( $this->mRestrictions
[$action] )
2482 ?
$this->mRestrictions
[$action]
2487 * Get the expiry time for the restriction against a given action
2490 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2491 * or not protected at all, or false if the action is not recognised.
2493 public function getRestrictionExpiry( $action ) {
2494 if ( !$this->mRestrictionsLoaded
) {
2495 $this->loadRestrictions();
2497 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2501 * Returns cascading restrictions for the current article
2505 function areRestrictionsCascading() {
2506 if ( !$this->mRestrictionsLoaded
) {
2507 $this->loadRestrictions();
2510 return $this->mCascadeRestriction
;
2514 * Loads a string into mRestrictions array
2516 * @param $res Resource restrictions as an SQL result.
2517 * @param $oldFashionedRestrictions String comma-separated list of page
2518 * restrictions from page table (pre 1.10)
2520 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2523 foreach ( $res as $row ) {
2527 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2531 * Compiles list of active page restrictions from both page table (pre 1.10)
2532 * and page_restrictions table for this existing page.
2533 * Public for usage by LiquidThreads.
2535 * @param $rows array of db result objects
2536 * @param $oldFashionedRestrictions string comma-separated list of page
2537 * restrictions from page table (pre 1.10)
2539 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2541 $dbr = wfGetDB( DB_SLAVE
);
2543 $restrictionTypes = $this->getRestrictionTypes();
2545 foreach ( $restrictionTypes as $type ) {
2546 $this->mRestrictions
[$type] = array();
2547 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2550 $this->mCascadeRestriction
= false;
2552 # Backwards-compatibility: also load the restrictions from the page record (old format).
2554 if ( $oldFashionedRestrictions === null ) {
2555 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2556 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2559 if ( $oldFashionedRestrictions != '' ) {
2561 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2562 $temp = explode( '=', trim( $restrict ) );
2563 if ( count( $temp ) == 1 ) {
2564 // old old format should be treated as edit/move restriction
2565 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2566 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2568 $restriction = trim( $temp[1] );
2569 if( $restriction != '' ) { //some old entries are empty
2570 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2575 $this->mOldRestrictions
= true;
2579 if ( count( $rows ) ) {
2580 # Current system - load second to make them override.
2581 $now = wfTimestampNow();
2582 $purgeExpired = false;
2584 # Cycle through all the restrictions.
2585 foreach ( $rows as $row ) {
2587 // Don't take care of restrictions types that aren't allowed
2588 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2591 // This code should be refactored, now that it's being used more generally,
2592 // But I don't really see any harm in leaving it in Block for now -werdna
2593 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2595 // Only apply the restrictions if they haven't expired!
2596 if ( !$expiry ||
$expiry > $now ) {
2597 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2598 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2600 $this->mCascadeRestriction |
= $row->pr_cascade
;
2602 // Trigger a lazy purge of expired restrictions
2603 $purgeExpired = true;
2607 if ( $purgeExpired ) {
2608 Title
::purgeExpiredRestrictions();
2612 $this->mRestrictionsLoaded
= true;
2616 * Load restrictions from the page_restrictions table
2618 * @param $oldFashionedRestrictions String comma-separated list of page
2619 * restrictions from page table (pre 1.10)
2621 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2623 if ( !$this->mRestrictionsLoaded
) {
2624 if ( $this->exists() ) {
2625 $dbr = wfGetDB( DB_SLAVE
);
2627 $res = $dbr->select(
2628 'page_restrictions',
2630 array( 'pr_page' => $this->getArticleID() ),
2634 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2636 $title_protection = $this->getTitleProtection();
2638 if ( $title_protection ) {
2639 $now = wfTimestampNow();
2640 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2642 if ( !$expiry ||
$expiry > $now ) {
2643 // Apply the restrictions
2644 $this->mRestrictionsExpiry
['create'] = $expiry;
2645 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2646 } else { // Get rid of the old restrictions
2647 Title
::purgeExpiredRestrictions();
2648 $this->mTitleProtection
= false;
2651 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2653 $this->mRestrictionsLoaded
= true;
2659 * Flush the protection cache in this object and force reload from the database.
2660 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2662 public function flushRestrictions() {
2663 $this->mRestrictionsLoaded
= false;
2664 $this->mTitleProtection
= null;
2668 * Purge expired restrictions from the page_restrictions table
2670 static function purgeExpiredRestrictions() {
2671 $dbw = wfGetDB( DB_MASTER
);
2673 'page_restrictions',
2674 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2680 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2686 * Does this have subpages? (Warning, usually requires an extra DB query.)
2690 public function hasSubpages() {
2691 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2696 # We dynamically add a member variable for the purpose of this method
2697 # alone to cache the result. There's no point in having it hanging
2698 # around uninitialized in every Title object; therefore we only add it
2699 # if needed and don't declare it statically.
2700 if ( isset( $this->mHasSubpages
) ) {
2701 return $this->mHasSubpages
;
2704 $subpages = $this->getSubpages( 1 );
2705 if ( $subpages instanceof TitleArray
) {
2706 return $this->mHasSubpages
= (bool)$subpages->count();
2708 return $this->mHasSubpages
= false;
2712 * Get all subpages of this page.
2714 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2715 * @return mixed TitleArray, or empty array if this page's namespace
2716 * doesn't allow subpages
2718 public function getSubpages( $limit = -1 ) {
2719 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2723 $dbr = wfGetDB( DB_SLAVE
);
2724 $conds['page_namespace'] = $this->getNamespace();
2725 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2727 if ( $limit > -1 ) {
2728 $options['LIMIT'] = $limit;
2730 return $this->mSubpages
= TitleArray
::newFromResult(
2731 $dbr->select( 'page',
2732 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2741 * Is there a version of this page in the deletion archive?
2743 * @return Int the number of archived revisions
2745 public function isDeleted() {
2746 if ( $this->getNamespace() < 0 ) {
2749 $dbr = wfGetDB( DB_SLAVE
);
2751 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2752 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2755 if ( $this->getNamespace() == NS_FILE
) {
2756 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2757 array( 'fa_name' => $this->getDBkey() ),
2766 * Is there a version of this page in the deletion archive?
2770 public function isDeletedQuick() {
2771 if ( $this->getNamespace() < 0 ) {
2774 $dbr = wfGetDB( DB_SLAVE
);
2775 $deleted = (bool)$dbr->selectField( 'archive', '1',
2776 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2779 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2780 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2781 array( 'fa_name' => $this->getDBkey() ),
2789 * Get the article ID for this Title from the link cache,
2790 * adding it if necessary
2792 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2794 * @return Int the ID
2796 public function getArticleID( $flags = 0 ) {
2797 if ( $this->getNamespace() < 0 ) {
2798 return $this->mArticleID
= 0;
2800 $linkCache = LinkCache
::singleton();
2801 if ( $flags & self
::GAID_FOR_UPDATE
) {
2802 $oldUpdate = $linkCache->forUpdate( true );
2803 $linkCache->clearLink( $this );
2804 $this->mArticleID
= $linkCache->addLinkObj( $this );
2805 $linkCache->forUpdate( $oldUpdate );
2807 if ( -1 == $this->mArticleID
) {
2808 $this->mArticleID
= $linkCache->addLinkObj( $this );
2811 return $this->mArticleID
;
2815 * Is this an article that is a redirect page?
2816 * Uses link cache, adding it if necessary
2818 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2821 public function isRedirect( $flags = 0 ) {
2822 if ( !is_null( $this->mRedirect
) ) {
2823 return $this->mRedirect
;
2825 # Calling getArticleID() loads the field from cache as needed
2826 if ( !$this->getArticleID( $flags ) ) {
2827 return $this->mRedirect
= false;
2829 $linkCache = LinkCache
::singleton();
2830 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2832 return $this->mRedirect
;
2836 * What is the length of this page?
2837 * Uses link cache, adding it if necessary
2839 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2842 public function getLength( $flags = 0 ) {
2843 if ( $this->mLength
!= -1 ) {
2844 return $this->mLength
;
2846 # Calling getArticleID() loads the field from cache as needed
2847 if ( !$this->getArticleID( $flags ) ) {
2848 return $this->mLength
= 0;
2850 $linkCache = LinkCache
::singleton();
2851 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2853 return $this->mLength
;
2857 * What is the page_latest field for this page?
2859 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2860 * @return Int or 0 if the page doesn't exist
2862 public function getLatestRevID( $flags = 0 ) {
2863 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
2864 return intval( $this->mLatestID
);
2866 # Calling getArticleID() loads the field from cache as needed
2867 if ( !$this->getArticleID( $flags ) ) {
2868 return $this->mLatestID
= 0;
2870 $linkCache = LinkCache
::singleton();
2871 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2873 return $this->mLatestID
;
2877 * This clears some fields in this object, and clears any associated
2878 * keys in the "bad links" section of the link cache.
2880 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2881 * loading of the new page_id. It's also called from
2882 * WikiPage::doDeleteArticleReal()
2884 * @param $newid Int the new Article ID
2886 public function resetArticleID( $newid ) {
2887 $linkCache = LinkCache
::singleton();
2888 $linkCache->clearLink( $this );
2890 if ( $newid === false ) {
2891 $this->mArticleID
= -1;
2893 $this->mArticleID
= intval( $newid );
2895 $this->mRestrictionsLoaded
= false;
2896 $this->mRestrictions
= array();
2897 $this->mRedirect
= null;
2898 $this->mLength
= -1;
2899 $this->mLatestID
= false;
2900 $this->mEstimateRevisions
= null;
2904 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2906 * @param $text String containing title to capitalize
2907 * @param $ns int namespace index, defaults to NS_MAIN
2908 * @return String containing capitalized title
2910 public static function capitalize( $text, $ns = NS_MAIN
) {
2913 if ( MWNamespace
::isCapitalized( $ns ) ) {
2914 return $wgContLang->ucfirst( $text );
2921 * Secure and split - main initialisation function for this object
2923 * Assumes that mDbkeyform has been set, and is urldecoded
2924 * and uses underscores, but not otherwise munged. This function
2925 * removes illegal characters, splits off the interwiki and
2926 * namespace prefixes, sets the other forms, and canonicalizes
2929 * @return Bool true on success
2931 private function secureAndSplit() {
2932 global $wgContLang, $wgLocalInterwiki;
2935 $this->mInterwiki
= $this->mFragment
= '';
2936 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2938 $dbkey = $this->mDbkeyform
;
2940 # Strip Unicode bidi override characters.
2941 # Sometimes they slip into cut-n-pasted page titles, where the
2942 # override chars get included in list displays.
2943 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2945 # Clean up whitespace
2946 # Note: use of the /u option on preg_replace here will cause
2947 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2948 # conveniently disabling them.
2949 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2950 $dbkey = trim( $dbkey, '_' );
2952 if ( $dbkey == '' ) {
2956 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2957 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2961 $this->mDbkeyform
= $dbkey;
2963 # Initial colon indicates main namespace rather than specified default
2964 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2965 if ( ':' == $dbkey[0] ) {
2966 $this->mNamespace
= NS_MAIN
;
2967 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2968 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2971 # Namespace or interwiki prefix
2973 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2976 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2978 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2979 # Ordinary namespace
2981 $this->mNamespace
= $ns;
2982 # For Talk:X pages, check if X has a "namespace" prefix
2983 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2984 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2985 # Disallow Talk:File:x type titles...
2987 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2988 # Disallow Talk:Interwiki:x type titles...
2992 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2993 if ( !$firstPass ) {
2994 # Can't make a local interwiki link to an interwiki link.
2995 # That's just crazy!
3001 $this->mInterwiki
= $wgContLang->lc( $p );
3003 # Redundant interwiki prefix to the local wiki
3004 if ( $wgLocalInterwiki !== false
3005 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3007 if ( $dbkey == '' ) {
3008 # Can't have an empty self-link
3011 $this->mInterwiki
= '';
3013 # Do another namespace split...
3017 # If there's an initial colon after the interwiki, that also
3018 # resets the default namespace
3019 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3020 $this->mNamespace
= NS_MAIN
;
3021 $dbkey = substr( $dbkey, 1 );
3024 # If there's no recognized interwiki or namespace,
3025 # then let the colon expression be part of the title.
3030 # We already know that some pages won't be in the database!
3031 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3032 $this->mArticleID
= 0;
3034 $fragment = strstr( $dbkey, '#' );
3035 if ( false !== $fragment ) {
3036 $this->setFragment( $fragment );
3037 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3038 # remove whitespace again: prevents "Foo_bar_#"
3039 # becoming "Foo_bar_"
3040 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3043 # Reject illegal characters.
3044 $rxTc = self
::getTitleInvalidRegex();
3045 if ( preg_match( $rxTc, $dbkey ) ) {
3049 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3050 # reachable due to the way web browsers deal with 'relative' URLs.
3051 # Also, they conflict with subpage syntax. Forbid them explicitly.
3052 if ( strpos( $dbkey, '.' ) !== false &&
3053 ( $dbkey === '.' ||
$dbkey === '..' ||
3054 strpos( $dbkey, './' ) === 0 ||
3055 strpos( $dbkey, '../' ) === 0 ||
3056 strpos( $dbkey, '/./' ) !== false ||
3057 strpos( $dbkey, '/../' ) !== false ||
3058 substr( $dbkey, -2 ) == '/.' ||
3059 substr( $dbkey, -3 ) == '/..' ) )
3064 # Magic tilde sequences? Nu-uh!
3065 if ( strpos( $dbkey, '~~~' ) !== false ) {
3069 # Limit the size of titles to 255 bytes. This is typically the size of the
3070 # underlying database field. We make an exception for special pages, which
3071 # don't need to be stored in the database, and may edge over 255 bytes due
3072 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3073 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3074 strlen( $dbkey ) > 512 )
3079 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3080 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3081 # other site might be case-sensitive.
3082 $this->mUserCaseDBKey
= $dbkey;
3083 if ( $this->mInterwiki
== '' ) {
3084 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3087 # Can't make a link to a namespace alone... "empty" local links can only be
3088 # self-links with a fragment identifier.
3089 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3093 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3094 // IP names are not allowed for accounts, and can only be referring to
3095 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3096 // there are numerous ways to present the same IP. Having sp:contribs scan
3097 // them all is silly and having some show the edits and others not is
3098 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3099 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3100 ? IP
::sanitizeIP( $dbkey )
3103 // Any remaining initial :s are illegal.
3104 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3109 $this->mDbkeyform
= $dbkey;
3110 $this->mUrlform
= wfUrlencode( $dbkey );
3112 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3118 * Get an array of Title objects linking to this Title
3119 * Also stores the IDs in the link cache.
3121 * WARNING: do not use this function on arbitrary user-supplied titles!
3122 * On heavily-used templates it will max out the memory.
3124 * @param $options Array: may be FOR UPDATE
3125 * @param $table String: table name
3126 * @param $prefix String: fields prefix
3127 * @return Array of Title objects linking here
3129 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3130 if ( count( $options ) > 0 ) {
3131 $db = wfGetDB( DB_MASTER
);
3133 $db = wfGetDB( DB_SLAVE
);
3137 array( 'page', $table ),
3138 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3140 "{$prefix}_from=page_id",
3141 "{$prefix}_namespace" => $this->getNamespace(),
3142 "{$prefix}_title" => $this->getDBkey() ),
3148 if ( $res->numRows() ) {
3149 $linkCache = LinkCache
::singleton();
3150 foreach ( $res as $row ) {
3151 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3153 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3154 $retVal[] = $titleObj;
3162 * Get an array of Title objects using this Title as a template
3163 * Also stores the IDs in the link cache.
3165 * WARNING: do not use this function on arbitrary user-supplied titles!
3166 * On heavily-used templates it will max out the memory.
3168 * @param $options Array: may be FOR UPDATE
3169 * @return Array of Title the Title objects linking here
3171 public function getTemplateLinksTo( $options = array() ) {
3172 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3176 * Get an array of Title objects linked from this Title
3177 * Also stores the IDs in the link cache.
3179 * WARNING: do not use this function on arbitrary user-supplied titles!
3180 * On heavily-used templates it will max out the memory.
3182 * @param $options Array: may be FOR UPDATE
3183 * @param $table String: table name
3184 * @param $prefix String: fields prefix
3185 * @return Array of Title objects linking here
3187 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3188 $id = $this->getArticleID();
3190 # If the page doesn't exist; there can't be any link from this page
3195 if ( count( $options ) > 0 ) {
3196 $db = wfGetDB( DB_MASTER
);
3198 $db = wfGetDB( DB_SLAVE
);
3201 $namespaceFiled = "{$prefix}_namespace";
3202 $titleField = "{$prefix}_title";
3205 array( $table, 'page' ),
3206 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3207 array( "{$prefix}_from" => $id ),
3210 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3214 if ( $res->numRows() ) {
3215 $linkCache = LinkCache
::singleton();
3216 foreach ( $res as $row ) {
3217 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3219 if ( $row->page_id
) {
3220 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3222 $linkCache->addBadLinkObj( $titleObj );
3224 $retVal[] = $titleObj;
3232 * Get an array of Title objects used on this Title as a template
3233 * Also stores the IDs in the link cache.
3235 * WARNING: do not use this function on arbitrary user-supplied titles!
3236 * On heavily-used templates it will max out the memory.
3238 * @param $options Array: may be FOR UPDATE
3239 * @return Array of Title the Title objects used here
3241 public function getTemplateLinksFrom( $options = array() ) {
3242 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3246 * Get an array of Title objects referring to non-existent articles linked from this page
3248 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3249 * @return Array of Title the Title objects
3251 public function getBrokenLinksFrom() {
3252 if ( $this->getArticleID() == 0 ) {
3253 # All links from article ID 0 are false positives
3257 $dbr = wfGetDB( DB_SLAVE
);
3258 $res = $dbr->select(
3259 array( 'page', 'pagelinks' ),
3260 array( 'pl_namespace', 'pl_title' ),
3262 'pl_from' => $this->getArticleID(),
3263 'page_namespace IS NULL'
3265 __METHOD__
, array(),
3269 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3275 foreach ( $res as $row ) {
3276 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3283 * Get a list of URLs to purge from the Squid cache when this
3286 * @return Array of String the URLs
3288 public function getSquidURLs() {
3290 $this->getInternalURL(),
3291 $this->getInternalURL( 'action=history' )
3294 $pageLang = $this->getPageLanguage();
3295 if ( $pageLang->hasVariants() ) {
3296 $variants = $pageLang->getVariants();
3297 foreach ( $variants as $vCode ) {
3298 $urls[] = $this->getInternalURL( '', $vCode );
3306 * Purge all applicable Squid URLs
3308 public function purgeSquid() {
3310 if ( $wgUseSquid ) {
3311 $urls = $this->getSquidURLs();
3312 $u = new SquidUpdate( $urls );
3318 * Move this page without authentication
3320 * @param $nt Title the new page Title
3321 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3323 public function moveNoAuth( &$nt ) {
3324 return $this->moveTo( $nt, false );
3328 * Check whether a given move operation would be valid.
3329 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3331 * @param $nt Title the new title
3332 * @param $auth Bool indicates whether $wgUser's permissions
3334 * @param $reason String is the log summary of the move, used for spam checking
3335 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3337 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3342 // Normally we'd add this to $errors, but we'll get
3343 // lots of syntax errors if $nt is not an object
3344 return array( array( 'badtitletext' ) );
3346 if ( $this->equals( $nt ) ) {
3347 $errors[] = array( 'selfmove' );
3349 if ( !$this->isMovable() ) {
3350 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3352 if ( $nt->getInterwiki() != '' ) {
3353 $errors[] = array( 'immobile-target-namespace-iw' );
3355 if ( !$nt->isMovable() ) {
3356 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3359 $oldid = $this->getArticleID();
3360 $newid = $nt->getArticleID();
3362 if ( strlen( $nt->getDBkey() ) < 1 ) {
3363 $errors[] = array( 'articleexists' );
3365 if ( ( $this->getDBkey() == '' ) ||
3367 ( $nt->getDBkey() == '' ) ) {
3368 $errors[] = array( 'badarticleerror' );
3371 // Image-specific checks
3372 if ( $this->getNamespace() == NS_FILE
) {
3373 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3376 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3377 $errors[] = array( 'nonfile-cannot-move-to-file' );
3381 $errors = wfMergeErrorArrays( $errors,
3382 $this->getUserPermissionsErrors( 'move', $wgUser ),
3383 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3384 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3385 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3388 $match = EditPage
::matchSummarySpamRegex( $reason );
3389 if ( $match !== false ) {
3390 // This is kind of lame, won't display nice
3391 $errors[] = array( 'spamprotectiontext' );
3395 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3396 $errors[] = array( 'hookaborted', $err );
3399 # The move is allowed only if (1) the target doesn't exist, or
3400 # (2) the target is a redirect to the source, and has no history
3401 # (so we can undo bad moves right after they're done).
3403 if ( 0 != $newid ) { # Target exists; check for validity
3404 if ( !$this->isValidMoveTarget( $nt ) ) {
3405 $errors[] = array( 'articleexists' );
3408 $tp = $nt->getTitleProtection();
3409 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3410 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3411 $errors[] = array( 'cantmove-titleprotected' );
3414 if ( empty( $errors ) ) {
3421 * Check if the requested move target is a valid file move target
3422 * @param Title $nt Target title
3423 * @return array List of errors
3425 protected function validateFileMoveOperation( $nt ) {
3430 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3432 $file = wfLocalFile( $this );
3433 if ( $file->exists() ) {
3434 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3435 $errors[] = array( 'imageinvalidfilename' );
3437 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3438 $errors[] = array( 'imagetypemismatch' );
3442 if ( $nt->getNamespace() != NS_FILE
) {
3443 $errors[] = array( 'imagenocrossnamespace' );
3444 // From here we want to do checks on a file object, so if we can't
3445 // create one, we must return.
3449 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3451 $destFile = wfLocalFile( $nt );
3452 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3453 $errors[] = array( 'file-exists-sharedrepo' );
3460 * Move a title to a new location
3462 * @param $nt Title the new title
3463 * @param $auth Bool indicates whether $wgUser's permissions
3465 * @param $reason String the reason for the move
3466 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3467 * Ignored if the user doesn't have the suppressredirect right.
3468 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3470 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3472 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3473 if ( is_array( $err ) ) {
3474 // Auto-block user's IP if the account was "hard" blocked
3475 $wgUser->spreadAnyEditBlock();
3478 // Check suppressredirect permission
3479 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3480 $createRedirect = true;
3483 // If it is a file, move it first.
3484 // It is done before all other moving stuff is done because it's hard to revert.
3485 $dbw = wfGetDB( DB_MASTER
);
3486 if ( $this->getNamespace() == NS_FILE
) {
3487 $file = wfLocalFile( $this );
3488 if ( $file->exists() ) {
3489 $status = $file->move( $nt );
3490 if ( !$status->isOk() ) {
3491 return $status->getErrorsArray();
3494 // Clear RepoGroup process cache
3495 RepoGroup
::singleton()->clearCache( $this );
3496 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3499 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3500 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3501 $protected = $this->isProtected();
3503 // Do the actual move
3504 $this->moveToInternal( $nt, $reason, $createRedirect );
3506 // Refresh the sortkey for this row. Be careful to avoid resetting
3507 // cl_timestamp, which may disturb time-based lists on some sites.
3508 $prefixes = $dbw->select(
3510 array( 'cl_sortkey_prefix', 'cl_to' ),
3511 array( 'cl_from' => $pageid ),
3514 foreach ( $prefixes as $prefixRow ) {
3515 $prefix = $prefixRow->cl_sortkey_prefix
;
3516 $catTo = $prefixRow->cl_to
;
3517 $dbw->update( 'categorylinks',
3519 'cl_sortkey' => Collation
::singleton()->getSortKey(
3520 $nt->getCategorySortkey( $prefix ) ),
3521 'cl_timestamp=cl_timestamp' ),
3523 'cl_from' => $pageid,
3524 'cl_to' => $catTo ),
3529 $redirid = $this->getArticleID();
3532 # Protect the redirect title as the title used to be...
3533 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3535 'pr_page' => $redirid,
3536 'pr_type' => 'pr_type',
3537 'pr_level' => 'pr_level',
3538 'pr_cascade' => 'pr_cascade',
3539 'pr_user' => 'pr_user',
3540 'pr_expiry' => 'pr_expiry'
3542 array( 'pr_page' => $pageid ),
3546 # Update the protection log
3547 $log = new LogPage( 'protect' );
3548 $comment = wfMessage(
3550 $this->getPrefixedText(),
3551 $nt->getPrefixedText()
3552 )->inContentLanguage()->text();
3554 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3556 // @todo FIXME: $params?
3557 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3561 $oldnamespace = $this->getNamespace() & ~
1;
3562 $newnamespace = $nt->getNamespace() & ~
1;
3563 $oldtitle = $this->getDBkey();
3564 $newtitle = $nt->getDBkey();
3566 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3567 WatchedItem
::duplicateEntries( $this, $nt );
3570 $dbw->commit( __METHOD__
);
3572 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3577 * Move page to a title which is either a redirect to the
3578 * source page or nonexistent
3580 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3581 * @param $reason String The reason for the move
3582 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3583 * if the user has the suppressredirect right
3584 * @throws MWException
3586 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3587 global $wgUser, $wgContLang;
3589 if ( $nt->exists() ) {
3590 $moveOverRedirect = true;
3591 $logType = 'move_redir';
3593 $moveOverRedirect = false;
3597 $redirectSuppressed = !$createRedirect;
3599 $logEntry = new ManualLogEntry( 'move', $logType );
3600 $logEntry->setPerformer( $wgUser );
3601 $logEntry->setTarget( $this );
3602 $logEntry->setComment( $reason );
3603 $logEntry->setParameters( array(
3604 '4::target' => $nt->getPrefixedText(),
3605 '5::noredir' => $redirectSuppressed ?
'1': '0',
3608 $formatter = LogFormatter
::newFromEntry( $logEntry );
3609 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3610 $comment = $formatter->getPlainActionText();
3612 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3614 # Truncate for whole multibyte characters.
3615 $comment = $wgContLang->truncate( $comment, 255 );
3617 $oldid = $this->getArticleID();
3619 $dbw = wfGetDB( DB_MASTER
);
3621 $newpage = WikiPage
::factory( $nt );
3623 if ( $moveOverRedirect ) {
3624 $newid = $nt->getArticleID();
3626 # Delete the old redirect. We don't save it to history since
3627 # by definition if we've got here it's rather uninteresting.
3628 # We have to remove it so that the next step doesn't trigger
3629 # a conflict on the unique namespace+title index...
3630 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3632 $newpage->doDeleteUpdates( $newid );
3635 # Save a null revision in the page's history notifying of the move
3636 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3637 if ( !is_object( $nullRevision ) ) {
3638 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3640 $nullRevId = $nullRevision->insertOn( $dbw );
3642 # Change the name of the target page:
3643 $dbw->update( 'page',
3645 'page_namespace' => $nt->getNamespace(),
3646 'page_title' => $nt->getDBkey(),
3648 /* WHERE */ array( 'page_id' => $oldid ),
3652 $this->resetArticleID( 0 );
3653 $nt->resetArticleID( $oldid );
3655 $newpage->updateRevisionOn( $dbw, $nullRevision );
3657 wfRunHooks( 'NewRevisionFromEditComplete',
3658 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3660 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3662 if ( !$moveOverRedirect ) {
3663 WikiPage
::onArticleCreate( $nt );
3666 # Recreate the redirect, this time in the other direction.
3667 if ( $redirectSuppressed ) {
3668 WikiPage
::onArticleDelete( $this );
3670 $mwRedir = MagicWord
::get( 'redirect' );
3671 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3672 $redirectArticle = WikiPage
::factory( $this );
3673 $newid = $redirectArticle->insertOn( $dbw );
3674 if ( $newid ) { // sanity
3675 $redirectRevision = new Revision( array(
3677 'comment' => $comment,
3678 'text' => $redirectText ) );
3679 $redirectRevision->insertOn( $dbw );
3680 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3682 wfRunHooks( 'NewRevisionFromEditComplete',
3683 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3685 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3690 $logid = $logEntry->insert();
3691 $logEntry->publish( $logid );
3695 * Move this page's subpages to be subpages of $nt
3697 * @param $nt Title Move target
3698 * @param $auth bool Whether $wgUser's permissions should be checked
3699 * @param $reason string The reason for the move
3700 * @param $createRedirect bool Whether to create redirects from the old subpages to
3701 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3702 * @return mixed array with old page titles as keys, and strings (new page titles) or
3703 * arrays (errors) as values, or an error array with numeric indices if no pages
3706 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3707 global $wgMaximumMovedPages;
3708 // Check permissions
3709 if ( !$this->userCan( 'move-subpages' ) ) {
3710 return array( 'cant-move-subpages' );
3712 // Do the source and target namespaces support subpages?
3713 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3714 return array( 'namespace-nosubpages',
3715 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3717 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3718 return array( 'namespace-nosubpages',
3719 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3722 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3725 foreach ( $subpages as $oldSubpage ) {
3727 if ( $count > $wgMaximumMovedPages ) {
3728 $retval[$oldSubpage->getPrefixedTitle()] =
3729 array( 'movepage-max-pages',
3730 $wgMaximumMovedPages );
3734 // We don't know whether this function was called before
3735 // or after moving the root page, so check both
3737 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3738 $oldSubpage->getArticleID() == $nt->getArticleID() )
3740 // When moving a page to a subpage of itself,
3741 // don't move it twice
3744 $newPageName = preg_replace(
3745 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3746 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3747 $oldSubpage->getDBkey() );
3748 if ( $oldSubpage->isTalkPage() ) {
3749 $newNs = $nt->getTalkPage()->getNamespace();
3751 $newNs = $nt->getSubjectPage()->getNamespace();
3753 # Bug 14385: we need makeTitleSafe because the new page names may
3754 # be longer than 255 characters.
3755 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3757 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3758 if ( $success === true ) {
3759 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3761 $retval[$oldSubpage->getPrefixedText()] = $success;
3768 * Checks if this page is just a one-rev redirect.
3769 * Adds lock, so don't use just for light purposes.
3773 public function isSingleRevRedirect() {
3774 $dbw = wfGetDB( DB_MASTER
);
3776 $row = $dbw->selectRow( 'page',
3777 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3780 array( 'FOR UPDATE' )
3782 # Cache some fields we may want
3783 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3784 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3785 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3786 if ( !$this->mRedirect
) {
3789 # Does the article have a history?
3790 $row = $dbw->selectField( array( 'page', 'revision' ),
3792 array( 'page_namespace' => $this->getNamespace(),
3793 'page_title' => $this->getDBkey(),
3795 'page_latest != rev_id'
3798 array( 'FOR UPDATE' )
3800 # Return true if there was no history
3801 return ( $row === false );
3805 * Checks if $this can be moved to a given Title
3806 * - Selects for update, so don't call it unless you mean business
3808 * @param $nt Title the new title to check
3811 public function isValidMoveTarget( $nt ) {
3812 # Is it an existing file?
3813 if ( $nt->getNamespace() == NS_FILE
) {
3814 $file = wfLocalFile( $nt );
3815 if ( $file->exists() ) {
3816 wfDebug( __METHOD__
. ": file exists\n" );
3820 # Is it a redirect with no history?
3821 if ( !$nt->isSingleRevRedirect() ) {
3822 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3825 # Get the article text
3826 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3827 if( !is_object( $rev ) ){
3830 $text = $rev->getText();
3831 # Does the redirect point to the source?
3832 # Or is it a broken self-redirect, usually caused by namespace collisions?
3834 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3835 $redirTitle = Title
::newFromText( $m[1] );
3836 if ( !is_object( $redirTitle ) ||
3837 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3838 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3839 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3844 wfDebug( __METHOD__
. ": failsafe\n" );
3851 * Get categories to which this Title belongs and return an array of
3852 * categories' names.
3854 * @return Array of parents in the form:
3855 * $parent => $currentarticle
3857 public function getParentCategories() {
3862 $titleKey = $this->getArticleID();
3864 if ( $titleKey === 0 ) {
3868 $dbr = wfGetDB( DB_SLAVE
);
3870 $res = $dbr->select( 'categorylinks', '*',
3872 'cl_from' => $titleKey,
3878 if ( $dbr->numRows( $res ) > 0 ) {
3879 foreach ( $res as $row ) {
3880 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3881 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3888 * Get a tree of parent categories
3890 * @param $children Array with the children in the keys, to check for circular refs
3891 * @return Array Tree of parent categories
3893 public function getParentCategoryTree( $children = array() ) {
3895 $parents = $this->getParentCategories();
3898 foreach ( $parents as $parent => $current ) {
3899 if ( array_key_exists( $parent, $children ) ) {
3900 # Circular reference
3901 $stack[$parent] = array();
3903 $nt = Title
::newFromText( $parent );
3905 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3915 * Get an associative array for selecting this title from
3918 * @return Array suitable for the $where parameter of DB::select()
3920 public function pageCond() {
3921 if ( $this->mArticleID
> 0 ) {
3922 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3923 return array( 'page_id' => $this->mArticleID
);
3925 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3930 * Get the revision ID of the previous revision
3932 * @param $revId Int Revision ID. Get the revision that was before this one.
3933 * @param $flags Int Title::GAID_FOR_UPDATE
3934 * @return Int|Bool Old revision ID, or FALSE if none exists
3936 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3937 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3938 $revId = $db->selectField( 'revision', 'rev_id',
3940 'rev_page' => $this->getArticleID( $flags ),
3941 'rev_id < ' . intval( $revId )
3944 array( 'ORDER BY' => 'rev_id DESC' )
3947 if ( $revId === false ) {
3950 return intval( $revId );
3955 * Get the revision ID of the next revision
3957 * @param $revId Int Revision ID. Get the revision that was after this one.
3958 * @param $flags Int Title::GAID_FOR_UPDATE
3959 * @return Int|Bool Next revision ID, or FALSE if none exists
3961 public function getNextRevisionID( $revId, $flags = 0 ) {
3962 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3963 $revId = $db->selectField( 'revision', 'rev_id',
3965 'rev_page' => $this->getArticleID( $flags ),
3966 'rev_id > ' . intval( $revId )
3969 array( 'ORDER BY' => 'rev_id' )
3972 if ( $revId === false ) {
3975 return intval( $revId );
3980 * Get the first revision of the page
3982 * @param $flags Int Title::GAID_FOR_UPDATE
3983 * @return Revision|Null if page doesn't exist
3985 public function getFirstRevision( $flags = 0 ) {
3986 $pageId = $this->getArticleID( $flags );
3988 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3989 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3990 array( 'rev_page' => $pageId ),
3992 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3995 return new Revision( $row );
4002 * Get the oldest revision timestamp of this page
4004 * @param $flags Int Title::GAID_FOR_UPDATE
4005 * @return String: MW timestamp
4007 public function getEarliestRevTime( $flags = 0 ) {
4008 $rev = $this->getFirstRevision( $flags );
4009 return $rev ?
$rev->getTimestamp() : null;
4013 * Check if this is a new page
4017 public function isNewPage() {
4018 $dbr = wfGetDB( DB_SLAVE
);
4019 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4023 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4027 public function isBigDeletion() {
4028 global $wgDeleteRevisionsLimit;
4030 if ( !$wgDeleteRevisionsLimit ) {
4034 $revCount = $this->estimateRevisionCount();
4035 return $revCount > $wgDeleteRevisionsLimit;
4039 * Get the approximate revision count of this page.
4043 public function estimateRevisionCount() {
4044 if ( !$this->exists() ) {
4048 if ( $this->mEstimateRevisions
=== null ) {
4049 $dbr = wfGetDB( DB_SLAVE
);
4050 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4051 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4054 return $this->mEstimateRevisions
;
4058 * Get the number of revisions between the given revision.
4059 * Used for diffs and other things that really need it.
4061 * @param $old int|Revision Old revision or rev ID (first before range)
4062 * @param $new int|Revision New revision or rev ID (first after range)
4063 * @return Int Number of revisions between these revisions.
4065 public function countRevisionsBetween( $old, $new ) {
4066 if ( !( $old instanceof Revision
) ) {
4067 $old = Revision
::newFromTitle( $this, (int)$old );
4069 if ( !( $new instanceof Revision
) ) {
4070 $new = Revision
::newFromTitle( $this, (int)$new );
4072 if ( !$old ||
!$new ) {
4073 return 0; // nothing to compare
4075 $dbr = wfGetDB( DB_SLAVE
);
4076 return (int)$dbr->selectField( 'revision', 'count(*)',
4078 'rev_page' => $this->getArticleID(),
4079 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4080 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4087 * Get the number of authors between the given revisions or revision IDs.
4088 * Used for diffs and other things that really need it.
4090 * @param $old int|Revision Old revision or rev ID (first before range by default)
4091 * @param $new int|Revision New revision or rev ID (first after range by default)
4092 * @param $limit int Maximum number of authors
4093 * @param $options string|array (Optional): Single option, or an array of options:
4094 * 'include_old' Include $old in the range; $new is excluded.
4095 * 'include_new' Include $new in the range; $old is excluded.
4096 * 'include_both' Include both $old and $new in the range.
4097 * Unknown option values are ignored.
4098 * @return int Number of revision authors in the range; zero if not both revisions exist
4100 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4101 if ( !( $old instanceof Revision
) ) {
4102 $old = Revision
::newFromTitle( $this, (int)$old );
4104 if ( !( $new instanceof Revision
) ) {
4105 $new = Revision
::newFromTitle( $this, (int)$new );
4107 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4108 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4109 // in the sanity check below?
4110 if ( !$old ||
!$new ) {
4111 return 0; // nothing to compare
4115 $options = (array) $options;
4116 if ( in_array( 'include_old', $options ) ) {
4119 if ( in_array( 'include_new', $options ) ) {
4122 if ( in_array( 'include_both', $options ) ) {
4126 // No DB query needed if $old and $new are the same or successive revisions:
4127 if ( $old->getId() === $new->getId() ) {
4128 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4129 } else if ( $old->getId() === $new->getParentId() ) {
4130 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4131 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4133 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4135 $dbr = wfGetDB( DB_SLAVE
);
4136 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4138 'rev_page' => $this->getArticleID(),
4139 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4140 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4142 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4144 return (int)$dbr->numRows( $res );
4148 * Compare with another title.
4150 * @param $title Title
4153 public function equals( Title
$title ) {
4154 // Note: === is necessary for proper matching of number-like titles.
4155 return $this->getInterwiki() === $title->getInterwiki()
4156 && $this->getNamespace() == $title->getNamespace()
4157 && $this->getDBkey() === $title->getDBkey();
4161 * Check if this title is a subpage of another title
4163 * @param $title Title
4166 public function isSubpageOf( Title
$title ) {
4167 return $this->getInterwiki() === $title->getInterwiki()
4168 && $this->getNamespace() == $title->getNamespace()
4169 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4173 * Check if page exists. For historical reasons, this function simply
4174 * checks for the existence of the title in the page table, and will
4175 * thus return false for interwiki links, special pages and the like.
4176 * If you want to know if a title can be meaningfully viewed, you should
4177 * probably call the isKnown() method instead.
4181 public function exists() {
4182 return $this->getArticleID() != 0;
4186 * Should links to this title be shown as potentially viewable (i.e. as
4187 * "bluelinks"), even if there's no record by this title in the page
4190 * This function is semi-deprecated for public use, as well as somewhat
4191 * misleadingly named. You probably just want to call isKnown(), which
4192 * calls this function internally.
4194 * (ISSUE: Most of these checks are cheap, but the file existence check
4195 * can potentially be quite expensive. Including it here fixes a lot of
4196 * existing code, but we might want to add an optional parameter to skip
4197 * it and any other expensive checks.)
4201 public function isAlwaysKnown() {
4205 * Allows overriding default behaviour for determining if a page exists.
4206 * If $isKnown is kept as null, regular checks happen. If it's
4207 * a boolean, this value is returned by the isKnown method.
4211 * @param Title $title
4212 * @param boolean|null $isKnown
4214 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4216 if ( !is_null( $isKnown ) ) {
4220 if ( $this->mInterwiki
!= '' ) {
4221 return true; // any interwiki link might be viewable, for all we know
4224 switch( $this->mNamespace
) {
4227 // file exists, possibly in a foreign repo
4228 return (bool)wfFindFile( $this );
4230 // valid special page
4231 return SpecialPageFactory
::exists( $this->getDBkey() );
4233 // selflink, possibly with fragment
4234 return $this->mDbkeyform
== '';
4236 // known system message
4237 return $this->hasSourceText() !== false;
4244 * Does this title refer to a page that can (or might) be meaningfully
4245 * viewed? In particular, this function may be used to determine if
4246 * links to the title should be rendered as "bluelinks" (as opposed to
4247 * "redlinks" to non-existent pages).
4248 * Adding something else to this function will cause inconsistency
4249 * since LinkHolderArray calls isAlwaysKnown() and does its own
4250 * page existence check.
4254 public function isKnown() {
4255 return $this->isAlwaysKnown() ||
$this->exists();
4259 * Does this page have source text?
4263 public function hasSourceText() {
4264 if ( $this->exists() ) {
4268 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4269 // If the page doesn't exist but is a known system message, default
4270 // message content will be displayed, same for language subpages-
4271 // Use always content language to avoid loading hundreds of languages
4272 // to get the link color.
4274 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4275 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4276 return $message->exists();
4283 * Get the default message text or false if the message doesn't exist
4285 * @return String or false
4287 public function getDefaultMessageText() {
4290 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4294 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4295 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4297 if ( $message->exists() ) {
4298 return $message->plain();
4305 * Updates page_touched for this page; called from LinksUpdate.php
4307 * @return Bool true if the update succeded
4309 public function invalidateCache() {
4310 if ( wfReadOnly() ) {
4313 $dbw = wfGetDB( DB_MASTER
);
4314 $success = $dbw->update(
4316 array( 'page_touched' => $dbw->timestamp() ),
4320 HTMLFileCache
::clearFileCache( $this );
4325 * Update page_touched timestamps and send squid purge messages for
4326 * pages linking to this title. May be sent to the job queue depending
4327 * on the number of links. Typically called on create and delete.
4329 public function touchLinks() {
4330 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4333 if ( $this->getNamespace() == NS_CATEGORY
) {
4334 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4340 * Get the last touched timestamp
4342 * @param $db DatabaseBase: optional db
4343 * @return String last-touched timestamp
4345 public function getTouched( $db = null ) {
4346 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4347 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4352 * Get the timestamp when this page was updated since the user last saw it.
4355 * @return String|Null
4357 public function getNotificationTimestamp( $user = null ) {
4358 global $wgUser, $wgShowUpdatedMarker;
4359 // Assume current user if none given
4363 // Check cache first
4364 $uid = $user->getId();
4365 // avoid isset here, as it'll return false for null entries
4366 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4367 return $this->mNotificationTimestamp
[$uid];
4369 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4370 return $this->mNotificationTimestamp
[$uid] = false;
4372 // Don't cache too much!
4373 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4374 $this->mNotificationTimestamp
= array();
4376 $dbr = wfGetDB( DB_SLAVE
);
4377 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4378 'wl_notificationtimestamp',
4380 'wl_user' => $user->getId(),
4381 'wl_namespace' => $this->getNamespace(),
4382 'wl_title' => $this->getDBkey(),
4386 return $this->mNotificationTimestamp
[$uid];
4390 * Generate strings used for xml 'id' names in monobook tabs
4392 * @param $prepend string defaults to 'nstab-'
4393 * @return String XML 'id' name
4395 public function getNamespaceKey( $prepend = 'nstab-' ) {
4397 // Gets the subject namespace if this title
4398 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4399 // Checks if cononical namespace name exists for namespace
4400 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4401 // Uses canonical namespace name
4402 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4404 // Uses text of namespace
4405 $namespaceKey = $this->getSubjectNsText();
4407 // Makes namespace key lowercase
4408 $namespaceKey = $wgContLang->lc( $namespaceKey );
4410 if ( $namespaceKey == '' ) {
4411 $namespaceKey = 'main';
4413 // Changes file to image for backwards compatibility
4414 if ( $namespaceKey == 'file' ) {
4415 $namespaceKey = 'image';
4417 return $prepend . $namespaceKey;
4421 * Get all extant redirects to this Title
4423 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4424 * @return Array of Title redirects to this title
4426 public function getRedirectsHere( $ns = null ) {
4429 $dbr = wfGetDB( DB_SLAVE
);
4431 'rd_namespace' => $this->getNamespace(),
4432 'rd_title' => $this->getDBkey(),
4435 if ( $this->isExternal() ) {
4436 $where['rd_interwiki'] = $this->getInterwiki();
4438 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4440 if ( !is_null( $ns ) ) {
4441 $where['page_namespace'] = $ns;
4444 $res = $dbr->select(
4445 array( 'redirect', 'page' ),
4446 array( 'page_namespace', 'page_title' ),
4451 foreach ( $res as $row ) {
4452 $redirs[] = self
::newFromRow( $row );
4458 * Check if this Title is a valid redirect target
4462 public function isValidRedirectTarget() {
4463 global $wgInvalidRedirectTargets;
4465 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4466 if ( $this->isSpecial( 'Userlogout' ) ) {
4470 foreach ( $wgInvalidRedirectTargets as $target ) {
4471 if ( $this->isSpecial( $target ) ) {
4480 * Get a backlink cache object
4482 * @return BacklinkCache
4484 public function getBacklinkCache() {
4485 return BacklinkCache
::get( $this );
4489 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4493 public function canUseNoindex() {
4494 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4496 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4497 ?
$wgContentNamespaces
4498 : $wgExemptFromUserRobotsControl;
4500 return !in_array( $this->mNamespace
, $bannedNamespaces );
4505 * Returns the raw sort key to be used for categories, with the specified
4506 * prefix. This will be fed to Collation::getSortKey() to get a
4507 * binary sortkey that can be used for actual sorting.
4509 * @param $prefix string The prefix to be used, specified using
4510 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4514 public function getCategorySortkey( $prefix = '' ) {
4515 $unprefixed = $this->getText();
4517 // Anything that uses this hook should only depend
4518 // on the Title object passed in, and should probably
4519 // tell the users to run updateCollations.php --force
4520 // in order to re-sort existing category relations.
4521 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4522 if ( $prefix !== '' ) {
4523 # Separate with a line feed, so the unprefixed part is only used as
4524 # a tiebreaker when two pages have the exact same prefix.
4525 # In UCA, tab is the only character that can sort above LF
4526 # so we strip both of them from the original prefix.
4527 $prefix = strtr( $prefix, "\n\t", ' ' );
4528 return "$prefix\n$unprefixed";
4534 * Get the language in which the content of this page is written in
4535 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4536 * e.g. $wgLang (such as special pages, which are in the user language).
4541 public function getPageLanguage() {
4543 if ( $this->isSpecialPage() ) {
4544 // special pages are in the user language
4546 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4547 // css/js should always be LTR and is, in fact, English
4548 return wfGetLangObj( 'en' );
4549 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4550 // Parse mediawiki messages with correct target language
4551 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4552 return wfGetLangObj( $lang );
4555 // If nothing special, it should be in the wiki content language
4556 $pageLang = $wgContLang;
4557 // Hook at the end because we don't want to override the above stuff
4558 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4559 return wfGetLangObj( $pageLang );
4563 * Get the language in which the content of this page is written when
4564 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4565 * e.g. $wgLang (such as special pages, which are in the user language).
4570 public function getPageViewLanguage() {
4571 $pageLang = $this->getPageLanguage();
4572 // If this is nothing special (so the content is converted when viewed)
4573 if ( !$this->isSpecialPage()
4574 && !$this->isCssOrJsPage() && !$this->isCssJsSubpage()
4575 && $this->getNamespace() !== NS_MEDIAWIKI
4577 // If the user chooses a variant, the content is actually
4578 // in a language whose code is the variant code.
4579 $variant = $pageLang->getPreferredVariant();
4580 if ( $pageLang->getCode() !== $variant ) {
4581 $pageLang = Language
::factory( $variant );