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 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
83 # Zero except in {{transclusion}} tags
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mBacklinkCache = null; // /< Cache of links to this title
89 var $mHasSubpage; // /< Whether a page has any subpages
96 /*protected*/ function __construct() { }
99 * Create a new Title from a prefixed DB key
101 * @param $key String the database key, which has underscores
102 * instead of spaces, possibly including namespace and
104 * @return Title, or NULL on an error
106 public static function newFromDBkey( $key ) {
108 $t->mDbkeyform
= $key;
109 if ( $t->secureAndSplit() ) {
117 * Create a new Title from text, such as what one would find in a link. De-
118 * codes any HTML entities in the text.
120 * @param $text String the link text; spaces, prefixes, and an
121 * initial ':' indicating the main namespace are accepted.
122 * @param $defaultNamespace Int the namespace to use if none is speci-
123 * fied by a prefix. If you want to force a specific namespace even if
124 * $text might begin with a namespace prefix, use makeTitle() or
126 * @throws MWException
127 * @return Title|null - Title or null on an error.
129 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
130 if ( is_object( $text ) ) {
131 throw new MWException( 'Title::newFromText given an object' );
135 * Wiki pages often contain multiple links to the same page.
136 * Title normalization and parsing can become expensive on
137 * pages with many links, so we can save a little time by
140 * In theory these are value objects and won't get changed...
142 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
143 return Title
::$titleCache[$text];
146 # Convert things like é ā or 〗 into normalized (bug 14952) text
147 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
150 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
151 $t->mDefaultNamespace
= $defaultNamespace;
153 static $cachedcount = 0 ;
154 if ( $t->secureAndSplit() ) {
155 if ( $defaultNamespace == NS_MAIN
) {
156 if ( $cachedcount >= self
::CACHE_MAX
) {
157 # Avoid memory leaks on mass operations...
158 Title
::$titleCache = array();
162 Title
::$titleCache[$text] =& $t;
172 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
174 * Example of wrong and broken code:
175 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
177 * Example of right code:
178 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
180 * Create a new Title from URL-encoded text. Ensures that
181 * the given title's length does not exceed the maximum.
183 * @param $url String the title, as might be taken from a URL
184 * @return Title the new object, or NULL on an error
186 public static function newFromURL( $url ) {
189 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
190 # but some URLs used it as a space replacement and they still come
191 # from some external search tools.
192 if ( strpos( self
::legalChars(), '+' ) === false ) {
193 $url = str_replace( '+', ' ', $url );
196 $t->mDbkeyform
= str_replace( ' ', '_', $url );
197 if ( $t->secureAndSplit() ) {
205 * Create a new Title from an article ID
207 * @param $id Int the page_id corresponding to the Title to create
208 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
209 * @return Title the new object, or NULL on an error
211 public static function newFromID( $id, $flags = 0 ) {
212 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
213 $row = $db->selectRow(
216 'page_namespace', 'page_title', 'page_id',
217 'page_len', 'page_is_redirect', 'page_latest',
219 array( 'page_id' => $id ),
222 if ( $row !== false ) {
223 $title = Title
::newFromRow( $row );
231 * Make an array of titles from an array of IDs
233 * @param $ids Array of Int Array of IDs
234 * @return Array of Titles
236 public static function newFromIDs( $ids ) {
237 if ( !count( $ids ) ) {
240 $dbr = wfGetDB( DB_SLAVE
);
245 'page_namespace', 'page_title', 'page_id',
246 'page_len', 'page_is_redirect', 'page_latest',
248 array( 'page_id' => $ids ),
253 foreach ( $res as $row ) {
254 $titles[] = Title
::newFromRow( $row );
260 * Make a Title object from a DB row
262 * @param $row Object database row (needs at least page_title,page_namespace)
263 * @return Title corresponding Title
265 public static function newFromRow( $row ) {
266 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
267 $t->loadFromRow( $row );
272 * Load Title object fields from a DB row.
273 * If false is given, the title will be treated as non-existing.
275 * @param $row Object|bool database row
277 public function loadFromRow( $row ) {
278 if ( $row ) { // page found
279 if ( isset( $row->page_id
) )
280 $this->mArticleID
= (int)$row->page_id
;
281 if ( isset( $row->page_len
) )
282 $this->mLength
= (int)$row->page_len
;
283 if ( isset( $row->page_is_redirect
) )
284 $this->mRedirect
= (bool)$row->page_is_redirect
;
285 if ( isset( $row->page_latest
) )
286 $this->mLatestID
= (int)$row->page_latest
; # FIXME: whene3ver page_latest is updated, also update page_content_model
287 if ( isset( $row->page_content_model
) )
288 $this->mContentModel
= intval( $row->page_content_model
);
290 $this->mContentModel
= null; # initialized lazily in getContentModel()
291 } else { // page not found
292 $this->mArticleID
= 0;
294 $this->mRedirect
= false;
295 $this->mLatestID
= 0;
296 $this->mContentModel
= null; # initialized lazily in getContentModel()
301 * Create a new Title from a namespace index and a DB key.
302 * It's assumed that $ns and $title are *valid*, for instance when
303 * they came directly from the database or a special page name.
304 * For convenience, spaces are converted to underscores so that
305 * eg user_text fields can be used directly.
307 * @param $ns Int the namespace of the article
308 * @param $title String the unprefixed database key form
309 * @param $fragment String the link fragment (after the "#")
310 * @param $interwiki String the interwiki prefix
311 * @return Title the new object
313 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
315 $t->mInterwiki
= $interwiki;
316 $t->mFragment
= $fragment;
317 $t->mNamespace
= $ns = intval( $ns );
318 $t->mDbkeyform
= str_replace( ' ', '_', $title );
319 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
320 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
321 $t->mTextform
= str_replace( '_', ' ', $title );
322 $t->mContentModel
= null; # initialized lazily in getContentModel()
327 * Create a new Title from a namespace index and a DB key.
328 * The parameters will be checked for validity, which is a bit slower
329 * than makeTitle() but safer for user-provided data.
331 * @param $ns Int the namespace of the article
332 * @param $title String database key form
333 * @param $fragment String the link fragment (after the "#")
334 * @param $interwiki String interwiki prefix
335 * @return Title the new object, or NULL on an error
337 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
338 if ( !MWNamespace
::exists( $ns ) ) {
343 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
344 if ( $t->secureAndSplit() ) {
352 * Create a new Title for the Main Page
354 * @return Title the new object
356 public static function newMainPage() {
357 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
358 // Don't give fatal errors if the message is broken
360 $title = Title
::newFromText( 'Main Page' );
366 * Extract a redirect destination from a string and return the
367 * Title, or null if the text doesn't contain a valid redirect
368 * This will only return the very next target, useful for
369 * the redirect table and other checks that don't need full recursion
371 * @param $text String: Text with possible redirect
372 * @return Title: The corresponding Title
374 public static function newFromRedirect( $text ) { #TODO: move to Content class, deprecate here.
375 return self
::newFromRedirectInternal( $text );
379 * Extract a redirect destination from a string and return the
380 * Title, or null if the text doesn't contain a valid redirect
381 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
382 * in order to provide (hopefully) the Title of the final destination instead of another redirect
384 * @param $text String Text with possible redirect
387 public static function newFromRedirectRecurse( $text ) {
388 $titles = self
::newFromRedirectArray( $text );
389 return $titles ?
array_pop( $titles ) : null;
393 * Extract a redirect destination from a string and return an
394 * array of Titles, or null if the text doesn't contain a valid redirect
395 * The last element in the array is the final destination after all redirects
396 * have been resolved (up to $wgMaxRedirects times)
398 * @param $text String Text with possible redirect
399 * @return Array of Titles, with the destination last
400 * @todo: migrate this logic into WikitextContent!
402 public static function newFromRedirectArray( $text ) {
403 global $wgMaxRedirects;
404 $title = self
::newFromRedirectInternal( $text );
405 if ( is_null( $title ) ) {
408 // recursive check to follow double redirects
409 $recurse = $wgMaxRedirects;
410 $titles = array( $title );
411 while ( --$recurse > 0 ) {
412 if ( $title->isRedirect() ) {
413 $page = WikiPage
::factory( $title );
414 $newtitle = $page->getRedirectTarget();
418 // Redirects to some special pages are not permitted
419 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
420 // the new title passes the checks, so make that our current title so that further recursion can be checked
422 $titles[] = $newtitle;
431 * Really extract the redirect destination
432 * Do not call this function directly, use one of the newFromRedirect* functions above
434 * @param $text String Text with possible redirect
437 protected static function newFromRedirectInternal( $text ) {
438 global $wgMaxRedirects;
439 if ( $wgMaxRedirects < 1 ) {
440 //redirects are disabled, so quit early
443 $redir = MagicWord
::get( 'redirect' );
444 $text = trim( $text );
445 if ( $redir->matchStartAndRemove( $text ) ) {
446 // Extract the first link and see if it's usable
447 // Ensure that it really does come directly after #REDIRECT
448 // Some older redirects included a colon, so don't freak about that!
450 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
451 // Strip preceding colon used to "escape" categories, etc.
452 // and URL-decode links
453 if ( strpos( $m[1], '%' ) !== false ) {
454 // Match behavior of inline link parsing here;
455 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
457 $title = Title
::newFromText( $m[1] );
458 // If the title is a redirect to bad special pages or is invalid, return null
459 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
469 * Get the prefixed DB key associated with an ID
471 * @param $id Int the page_id of the article
472 * @return Title an object representing the article, or NULL if no such article was found
474 public static function nameOf( $id ) {
475 $dbr = wfGetDB( DB_SLAVE
);
477 $s = $dbr->selectRow(
479 array( 'page_namespace', 'page_title' ),
480 array( 'page_id' => $id ),
483 if ( $s === false ) {
487 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
492 * Get a regex character class describing the legal characters in a link
494 * @return String the list of characters, not delimited
496 public static function legalChars() {
497 global $wgLegalTitleChars;
498 return $wgLegalTitleChars;
502 * Returns a simple regex that will match on characters and sequences invalid in titles.
503 * Note that this doesn't pick up many things that could be wrong with titles, but that
504 * replacing this regex with something valid will make many titles valid.
506 * @return String regex string
508 static function getTitleInvalidRegex() {
509 static $rxTc = false;
511 # Matching titles will be held as illegal.
513 # Any character not allowed is forbidden...
514 '[^' . self
::legalChars() . ']' .
515 # URL percent encoding sequences interfere with the ability
516 # to round-trip titles -- you can't link to them consistently.
518 # XML/HTML character references produce similar issues.
519 '|&[A-Za-z0-9\x80-\xff]+;' .
521 '|&#x[0-9A-Fa-f]+;' .
529 * Get a string representation of a title suitable for
530 * including in a search index
532 * @param $ns Int a namespace index
533 * @param $title String text-form main part
534 * @return String a stripped-down title string ready for the search index
536 public static function indexTitle( $ns, $title ) {
539 $lc = SearchEngine
::legalSearchChars() . '&#;';
540 $t = $wgContLang->normalizeForSearch( $title );
541 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
542 $t = $wgContLang->lc( $t );
545 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
546 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
548 $t = preg_replace( "/\\s+/", ' ', $t );
550 if ( $ns == NS_FILE
) {
551 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
557 * Make a prefixed DB key from a DB key and a namespace index
559 * @param $ns Int numerical representation of the namespace
560 * @param $title String the DB key form the title
561 * @param $fragment String The link fragment (after the "#")
562 * @param $interwiki String The interwiki prefix
563 * @return String the prefixed form of the title
565 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
568 $namespace = $wgContLang->getNsText( $ns );
569 $name = $namespace == '' ?
$title : "$namespace:$title";
570 if ( strval( $interwiki ) != '' ) {
571 $name = "$interwiki:$name";
573 if ( strval( $fragment ) != '' ) {
574 $name .= '#' . $fragment;
580 * Escape a text fragment, say from a link, for a URL
582 * @param $fragment string containing a URL or link fragment (after the "#")
583 * @return String: escaped string
585 static function escapeFragmentForURL( $fragment ) {
586 # Note that we don't urlencode the fragment. urlencoded Unicode
587 # fragments appear not to work in IE (at least up to 7) or in at least
588 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
589 # to care if they aren't encoded.
590 return Sanitizer
::escapeId( $fragment, 'noninitial' );
594 * Callback for usort() to do title sorts by (namespace, title)
599 * @return Integer: result of string comparison, or namespace comparison
601 public static function compare( $a, $b ) {
602 if ( $a->getNamespace() == $b->getNamespace() ) {
603 return strcmp( $a->getText(), $b->getText() );
605 return $a->getNamespace() - $b->getNamespace();
610 * Determine whether the object refers to a page within
613 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
615 public function isLocal() {
616 if ( $this->mInterwiki
!= '' ) {
617 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
624 * Is this Title interwiki?
628 public function isExternal() {
629 return ( $this->mInterwiki
!= '' );
633 * Get the interwiki prefix (or null string)
635 * @return String Interwiki prefix
637 public function getInterwiki() {
638 return $this->mInterwiki
;
642 * Determine whether the object refers to a page within
643 * this project and is transcludable.
645 * @return Bool TRUE if this is transcludable
647 public function isTrans() {
648 if ( $this->mInterwiki
== '' ) {
652 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
656 * Returns the DB name of the distant wiki which owns the object.
658 * @return String the DB name
660 public function getTransWikiID() {
661 if ( $this->mInterwiki
== '' ) {
665 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
669 * Get the text form (spaces not underscores) of the main part
671 * @return String Main part of the title
673 public function getText() {
674 return $this->mTextform
;
678 * Get the URL-encoded form of the main part
680 * @return String Main part of the title, URL-encoded
682 public function getPartialURL() {
683 return $this->mUrlform
;
687 * Get the main part with underscores
689 * @return String: Main part of the title, with underscores
691 public function getDBkey() {
692 return $this->mDbkeyform
;
696 * Get the DB key with the initial letter case as specified by the user
698 * @return String DB key
700 function getUserCaseDBKey() {
701 return $this->mUserCaseDBKey
;
705 * Get the namespace index, i.e. one of the NS_xxxx constants.
707 * @return Integer: Namespace index
709 public function getNamespace() {
710 return $this->mNamespace
;
714 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
716 * @return Integer: Content model id
718 public function getContentModel() {
719 if ( empty( $this->mContentModel
) ) {
720 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
723 assert( !empty( $this->mContentModel
) );
724 return $this->mContentModel
;
728 * Convenience method for checking a title's content model name
731 * @return true if $this->getContentModel() == $id
733 public function hasContentModel( $id ) {
734 return $this->getContentModel() == $id;
738 * Get the namespace text
740 * @return String: Namespace text
742 public function getNsText() {
745 if ( $this->mInterwiki
!= '' ) {
746 // This probably shouldn't even happen. ohh man, oh yuck.
747 // But for interwiki transclusion it sometimes does.
748 // Shit. Shit shit shit.
750 // Use the canonical namespaces if possible to try to
751 // resolve a foreign namespace.
752 if ( MWNamespace
::exists( $this->mNamespace
) ) {
753 return MWNamespace
::getCanonicalName( $this->mNamespace
);
757 if ( $wgContLang->needsGenderDistinction() &&
758 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
759 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
760 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
763 return $wgContLang->getNsText( $this->mNamespace
);
767 * Get the namespace text of the subject (rather than talk) page
769 * @return String Namespace text
771 public function getSubjectNsText() {
773 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
777 * Get the namespace text of the talk page
779 * @return String Namespace text
781 public function getTalkNsText() {
783 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
787 * Could this title have a corresponding talk page?
789 * @return Bool TRUE or FALSE
791 public function canTalk() {
792 return( MWNamespace
::canTalk( $this->mNamespace
) );
796 * Is this in a namespace that allows actual pages?
799 * @internal note -- uses hardcoded namespace index instead of constants
801 public function canExist() {
802 return $this->mNamespace
>= NS_MAIN
;
806 * Can this title be added to a user's watchlist?
808 * @return Bool TRUE or FALSE
810 public function isWatchable() {
811 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
815 * Returns true if this is a special page.
819 public function isSpecialPage() {
820 return $this->getNamespace() == NS_SPECIAL
;
824 * Returns true if this title resolves to the named special page
826 * @param $name String The special page name
829 public function isSpecial( $name ) {
830 if ( $this->isSpecialPage() ) {
831 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
832 if ( $name == $thisName ) {
840 * If the Title refers to a special page alias which is not the local default, resolve
841 * the alias, and localise the name as necessary. Otherwise, return $this
845 public function fixSpecialName() {
846 if ( $this->isSpecialPage() ) {
847 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
848 if ( $canonicalName ) {
849 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
850 if ( $localName != $this->mDbkeyform
) {
851 return Title
::makeTitle( NS_SPECIAL
, $localName );
859 * Returns true if the title is inside the specified namespace.
861 * Please make use of this instead of comparing to getNamespace()
862 * This function is much more resistant to changes we may make
863 * to namespaces than code that makes direct comparisons.
864 * @param $ns int The namespace
868 public function inNamespace( $ns ) {
869 return MWNamespace
::equals( $this->getNamespace(), $ns );
873 * Returns true if the title is inside one of the specified namespaces.
875 * @param ...$namespaces The namespaces to check for
879 public function inNamespaces( /* ... */ ) {
880 $namespaces = func_get_args();
881 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
882 $namespaces = $namespaces[0];
885 foreach ( $namespaces as $ns ) {
886 if ( $this->inNamespace( $ns ) ) {
895 * Returns true if the title has the same subject namespace as the
896 * namespace specified.
897 * For example this method will take NS_USER and return true if namespace
898 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
899 * as their subject namespace.
901 * This is MUCH simpler than individually testing for equivilance
902 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
907 public function hasSubjectNamespace( $ns ) {
908 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
912 * Is this Title in a namespace which contains content?
913 * In other words, is this a content page, for the purposes of calculating
918 public function isContentPage() {
919 return MWNamespace
::isContent( $this->getNamespace() );
923 * Would anybody with sufficient privileges be able to move this page?
924 * Some pages just aren't movable.
926 * @return Bool TRUE or FALSE
928 public function isMovable() {
929 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
930 // Interwiki title or immovable namespace. Hooks don't get to override here
935 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
940 * Is this the mainpage?
941 * @note Title::newFromText seams to be sufficiently optimized by the title
942 * cache that we don't need to over-optimize by doing direct comparisons and
943 * acidentally creating new bugs where $title->equals( Title::newFromText() )
944 * ends up reporting something differently than $title->isMainPage();
949 public function isMainPage() {
950 return $this->equals( Title
::newMainPage() );
958 public function isSubpage() {
959 return MWNamespace
::hasSubpages( $this->mNamespace
)
960 ?
strpos( $this->getText(), '/' ) !== false
965 * Is this a conversion table for the LanguageConverter?
969 public function isConversionTable() {
970 return $this->getNamespace() == NS_MEDIAWIKI
&&
971 strpos( $this->getText(), 'Conversiontable' ) !== false;
975 * Does that page contain wikitext, or it is JS, CSS or whatever?
979 public function isWikitextPage() {
980 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
984 * Could this page contain custom CSS or JavaScript for the global UI.
985 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
986 * or CONTENT_MODEL_JAVASCRIPT.
988 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
990 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
994 public function isCssOrJsPage() {
995 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
996 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
997 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
999 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
1000 # hook funktions can force this method to return true even outside the mediawiki namespace.
1002 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1004 return $isCssOrJsPage;
1008 * Is this a .css or .js subpage of a user page?
1011 public function isCssJsSubpage() {
1012 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1013 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1014 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1018 * Trim down a .css or .js subpage title to get the corresponding skin name
1020 * @return string containing skin name from .css or .js subpage title
1022 public function getSkinFromCssJsSubpage() {
1023 $subpage = explode( '/', $this->mTextform
);
1024 $subpage = $subpage[ count( $subpage ) - 1 ];
1025 $lastdot = strrpos( $subpage, '.' );
1026 if ( $lastdot === false )
1027 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1028 return substr( $subpage, 0, $lastdot );
1032 * Is this a .css subpage of a user page?
1036 public function isCssSubpage() {
1037 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1038 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1042 * Is this a .js subpage of a user page?
1046 public function isJsSubpage() {
1047 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1048 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1052 * Is this a talk page of some sort?
1056 public function isTalkPage() {
1057 return MWNamespace
::isTalk( $this->getNamespace() );
1061 * Get a Title object associated with the talk page of this article
1063 * @return Title the object for the talk page
1065 public function getTalkPage() {
1066 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1070 * Get a title object associated with the subject page of this
1073 * @return Title the object for the subject page
1075 public function getSubjectPage() {
1076 // Is this the same title?
1077 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1078 if ( $this->getNamespace() == $subjectNS ) {
1081 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1085 * Get the default namespace index, for when there is no namespace
1087 * @return Int Default namespace index
1089 public function getDefaultNamespace() {
1090 return $this->mDefaultNamespace
;
1094 * Get title for search index
1096 * @return String a stripped-down title string ready for the
1099 public function getIndexTitle() {
1100 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1104 * Get the Title fragment (i.e.\ the bit after the #) in text form
1106 * @return String Title fragment
1108 public function getFragment() {
1109 return $this->mFragment
;
1113 * Get the fragment in URL form, including the "#" character if there is one
1114 * @return String Fragment in URL form
1116 public function getFragmentForURL() {
1117 if ( $this->mFragment
== '' ) {
1120 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1125 * Set the fragment for this title. Removes the first character from the
1126 * specified fragment before setting, so it assumes you're passing it with
1129 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1130 * Still in active use privately.
1132 * @param $fragment String text
1134 public function setFragment( $fragment ) {
1135 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1139 * Prefix some arbitrary text with the namespace or interwiki prefix
1142 * @param $name String the text
1143 * @return String the prefixed text
1146 private function prefix( $name ) {
1148 if ( $this->mInterwiki
!= '' ) {
1149 $p = $this->mInterwiki
. ':';
1152 if ( 0 != $this->mNamespace
) {
1153 $p .= $this->getNsText() . ':';
1159 * Get the prefixed database key form
1161 * @return String the prefixed title, with underscores and
1162 * any interwiki and namespace prefixes
1164 public function getPrefixedDBkey() {
1165 $s = $this->prefix( $this->mDbkeyform
);
1166 $s = str_replace( ' ', '_', $s );
1171 * Get the prefixed title with spaces.
1172 * This is the form usually used for display
1174 * @return String the prefixed title, with spaces
1176 public function getPrefixedText() {
1177 // @todo FIXME: Bad usage of empty() ?
1178 if ( empty( $this->mPrefixedText
) ) {
1179 $s = $this->prefix( $this->mTextform
);
1180 $s = str_replace( '_', ' ', $s );
1181 $this->mPrefixedText
= $s;
1183 return $this->mPrefixedText
;
1187 * Return a string representation of this title
1189 * @return String representation of this title
1191 public function __toString() {
1192 return $this->getPrefixedText();
1196 * Get the prefixed title with spaces, plus any fragment
1197 * (part beginning with '#')
1199 * @return String the prefixed title, with spaces and the fragment, including '#'
1201 public function getFullText() {
1202 $text = $this->getPrefixedText();
1203 if ( $this->mFragment
!= '' ) {
1204 $text .= '#' . $this->mFragment
;
1210 * Get the base page name, i.e. the leftmost part before any slashes
1212 * @return String Base name
1214 public function getBaseText() {
1215 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1216 return $this->getText();
1219 $parts = explode( '/', $this->getText() );
1220 # Don't discard the real title if there's no subpage involved
1221 if ( count( $parts ) > 1 ) {
1222 unset( $parts[count( $parts ) - 1] );
1224 return implode( '/', $parts );
1228 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1230 * @return String Subpage name
1232 public function getSubpageText() {
1233 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1234 return( $this->mTextform
);
1236 $parts = explode( '/', $this->mTextform
);
1237 return( $parts[count( $parts ) - 1] );
1241 * Get the HTML-escaped displayable text form.
1242 * Used for the title field in <a> tags.
1244 * @return String the text, including any prefixes
1246 public function getEscapedText() {
1247 wfDeprecated( __METHOD__
, '1.19' );
1248 return htmlspecialchars( $this->getPrefixedText() );
1252 * Get a URL-encoded form of the subpage text
1254 * @return String URL-encoded subpage name
1256 public function getSubpageUrlForm() {
1257 $text = $this->getSubpageText();
1258 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1263 * Get a URL-encoded title (not an actual URL) including interwiki
1265 * @return String the URL-encoded form
1267 public function getPrefixedURL() {
1268 $s = $this->prefix( $this->mDbkeyform
);
1269 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1274 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1275 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1276 * second argument named variant. This was deprecated in favor
1277 * of passing an array of option with a "variant" key
1278 * Once $query2 is removed for good, this helper can be dropped
1279 * andthe wfArrayToCGI moved to getLocalURL();
1281 * @since 1.19 (r105919)
1283 * @param $query2 bool
1286 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1287 if( $query2 !== false ) {
1288 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" );
1290 if ( is_array( $query ) ) {
1291 $query = wfArrayToCGI( $query );
1294 if ( is_string( $query2 ) ) {
1295 // $query2 is a string, we will consider this to be
1296 // a deprecated $variant argument and add it to the query
1297 $query2 = wfArrayToCGI( array( 'variant' => $query2 ) );
1299 $query2 = wfArrayToCGI( $query2 );
1301 // If we have $query content add a & to it first
1305 // Now append the queries together
1312 * Get a real URL referring to this title, with interwiki link and
1315 * See getLocalURL for the arguments.
1317 * @see self::getLocalURL
1318 * @return String the URL
1320 public function getFullURL( $query = '', $query2 = false ) {
1321 $query = self
::fixUrlQueryArgs( $query, $query2 );
1323 # Hand off all the decisions on urls to getLocalURL
1324 $url = $this->getLocalURL( $query );
1326 # Expand the url to make it a full url. Note that getLocalURL has the
1327 # potential to output full urls for a variety of reasons, so we use
1328 # wfExpandUrl instead of simply prepending $wgServer
1329 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
1331 # Finally, add the fragment.
1332 $url .= $this->getFragmentForURL();
1334 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1339 * Get a URL with no fragment or server name. If this page is generated
1340 * with action=render, $wgServer is prepended.
1343 * @param $query string|array an optional query string,
1344 * not used for interwiki links. Can be specified as an associative array as well,
1345 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1346 * Some query patterns will trigger various shorturl path replacements.
1347 * @param $query2 Mixed: An optional secondary query array. This one MUST
1348 * be an array. If a string is passed it will be interpreted as a deprecated
1349 * variant argument and urlencoded into a variant= argument.
1350 * This second query argument will be added to the $query
1351 * The second parameter is deprecated since 1.19. Pass it as a key,value
1352 * pair in the first parameter array instead.
1354 * @return String the URL
1356 public function getLocalURL( $query = '', $query2 = false ) {
1357 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1359 $query = self
::fixUrlQueryArgs( $query, $query2 );
1361 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1363 $namespace = $this->getNsText();
1364 if ( $namespace != '' ) {
1365 # Can this actually happen? Interwikis shouldn't be parsed.
1366 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1369 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1370 $url = wfAppendQuery( $url, $query );
1372 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1373 if ( $query == '' ) {
1374 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1375 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1377 global $wgVariantArticlePath, $wgActionPaths;
1381 if ( !empty( $wgActionPaths ) &&
1382 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1384 $action = urldecode( $matches[2] );
1385 if ( isset( $wgActionPaths[$action] ) ) {
1386 $query = $matches[1];
1387 if ( isset( $matches[4] ) ) {
1388 $query .= $matches[4];
1390 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1391 if ( $query != '' ) {
1392 $url = wfAppendQuery( $url, $query );
1397 if ( $url === false &&
1398 $wgVariantArticlePath &&
1399 $this->getPageLanguage()->hasVariants() &&
1400 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1402 $variant = urldecode( $matches[1] );
1403 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1404 // Only do the variant replacement if the given variant is a valid
1405 // variant for the page's language.
1406 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1407 $url = str_replace( '$1', $dbkey, $url );
1411 if ( $url === false ) {
1412 if ( $query == '-' ) {
1415 $url = "{$wgScript}?title={$dbkey}&{$query}";
1419 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1421 // @todo FIXME: This causes breakage in various places when we
1422 // actually expected a local URL and end up with dupe prefixes.
1423 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1424 $url = $wgServer . $url;
1427 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1432 * Get a URL that's the simplest URL that will be valid to link, locally,
1433 * to the current Title. It includes the fragment, but does not include
1434 * the server unless action=render is used (or the link is external). If
1435 * there's a fragment but the prefixed text is empty, we just return a link
1438 * The result obviously should not be URL-escaped, but does need to be
1439 * HTML-escaped if it's being output in HTML.
1441 * See getLocalURL for the arguments.
1443 * @see self::getLocalURL
1444 * @return String the URL
1446 public function getLinkURL( $query = '', $query2 = false ) {
1447 wfProfileIn( __METHOD__
);
1448 if ( $this->isExternal() ) {
1449 $ret = $this->getFullURL( $query, $query2 );
1450 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1451 $ret = $this->getFragmentForURL();
1453 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1455 wfProfileOut( __METHOD__
);
1460 * Get an HTML-escaped version of the URL form, suitable for
1461 * using in a link, without a server name or fragment
1463 * See getLocalURL for the arguments.
1465 * @see self::getLocalURL
1466 * @param $query string
1467 * @param $query2 bool|string
1468 * @return String the URL
1470 public function escapeLocalURL( $query = '', $query2 = false ) {
1471 wfDeprecated( __METHOD__
, '1.19' );
1472 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1476 * Get an HTML-escaped version of the URL form, suitable for
1477 * using in a link, including the server name and fragment
1479 * See getLocalURL for the arguments.
1481 * @see self::getLocalURL
1482 * @return String the URL
1484 public function escapeFullURL( $query = '', $query2 = false ) {
1485 wfDeprecated( __METHOD__
, '1.19' );
1486 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1490 * Get the URL form for an internal link.
1491 * - Used in various Squid-related code, in case we have a different
1492 * internal hostname for the server from the exposed one.
1494 * This uses $wgInternalServer to qualify the path, or $wgServer
1495 * if $wgInternalServer is not set. If the server variable used is
1496 * protocol-relative, the URL will be expanded to http://
1498 * See getLocalURL for the arguments.
1500 * @see self::getLocalURL
1501 * @return String the URL
1503 public function getInternalURL( $query = '', $query2 = false ) {
1504 global $wgInternalServer, $wgServer;
1505 $query = self
::fixUrlQueryArgs( $query, $query2 );
1506 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1507 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1508 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1513 * Get the URL for a canonical link, for use in things like IRC and
1514 * e-mail notifications. Uses $wgCanonicalServer and the
1515 * GetCanonicalURL hook.
1517 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1519 * See getLocalURL for the arguments.
1521 * @see self::getLocalURL
1522 * @return string The URL
1525 public function getCanonicalURL( $query = '', $query2 = false ) {
1526 $query = self
::fixUrlQueryArgs( $query, $query2 );
1527 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1528 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1533 * HTML-escaped version of getCanonicalURL()
1535 * See getLocalURL for the arguments.
1537 * @see self::getLocalURL
1541 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1542 wfDeprecated( __METHOD__
, '1.19' );
1543 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1547 * Get the edit URL for this Title
1549 * @return String the URL, or a null string if this is an
1552 public function getEditURL() {
1553 if ( $this->mInterwiki
!= '' ) {
1556 $s = $this->getLocalURL( 'action=edit' );
1562 * Is $wgUser watching this page?
1566 public function userIsWatching() {
1569 if ( is_null( $this->mWatched
) ) {
1570 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1571 $this->mWatched
= false;
1573 $this->mWatched
= $wgUser->isWatched( $this );
1576 return $this->mWatched
;
1580 * Can $wgUser read this page?
1582 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1584 * @todo fold these checks into userCan()
1586 public function userCanRead() {
1587 wfDeprecated( __METHOD__
, '1.19' );
1588 return $this->userCan( 'read' );
1592 * Can $user perform $action on this page?
1593 * This skips potentially expensive cascading permission checks
1594 * as well as avoids expensive error formatting
1596 * Suitable for use for nonessential UI controls in common cases, but
1597 * _not_ for functional access control.
1599 * May provide false positives, but should never provide a false negative.
1601 * @param $action String action that permission needs to be checked for
1602 * @param $user User to check (since 1.19); $wgUser will be used if not
1606 public function quickUserCan( $action, $user = null ) {
1607 return $this->userCan( $action, $user, false );
1611 * Can $user perform $action on this page?
1613 * @param $action String action that permission needs to be checked for
1614 * @param $user User to check (since 1.19); $wgUser will be used if not
1616 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1617 * unnecessary queries.
1620 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1621 if ( !$user instanceof User
) {
1625 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1629 * Can $user perform $action on this page?
1631 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1633 * @param $action String action that permission needs to be checked for
1634 * @param $user User to check
1635 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1636 * queries by skipping checks for cascading protections and user blocks.
1637 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1638 * whose corresponding errors may be ignored.
1639 * @return Array of arguments to wfMsg to explain permissions problems.
1641 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1642 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1644 // Remove the errors being ignored.
1645 foreach ( $errors as $index => $error ) {
1646 $error_key = is_array( $error ) ?
$error[0] : $error;
1648 if ( in_array( $error_key, $ignoreErrors ) ) {
1649 unset( $errors[$index] );
1657 * Permissions checks that fail most often, and which are easiest to test.
1659 * @param $action String the action to check
1660 * @param $user User user to check
1661 * @param $errors Array list of current errors
1662 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1663 * @param $short Boolean short circuit on first error
1665 * @return Array list of errors
1667 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1668 if ( $action == 'create' ) {
1669 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1670 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1671 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1673 } elseif ( $action == 'move' ) {
1674 if ( !$user->isAllowed( 'move-rootuserpages' )
1675 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1676 // Show user page-specific message only if the user can move other pages
1677 $errors[] = array( 'cant-move-user-page' );
1680 // Check if user is allowed to move files if it's a file
1681 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1682 $errors[] = array( 'movenotallowedfile' );
1685 if ( !$user->isAllowed( 'move' ) ) {
1686 // User can't move anything
1687 global $wgGroupPermissions;
1688 $userCanMove = false;
1689 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1690 $userCanMove = $wgGroupPermissions['user']['move'];
1692 $autoconfirmedCanMove = false;
1693 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1694 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1696 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1697 // custom message if logged-in users without any special rights can move
1698 $errors[] = array( 'movenologintext' );
1700 $errors[] = array( 'movenotallowed' );
1703 } elseif ( $action == 'move-target' ) {
1704 if ( !$user->isAllowed( 'move' ) ) {
1705 // User can't move anything
1706 $errors[] = array( 'movenotallowed' );
1707 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1708 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1709 // Show user page-specific message only if the user can move other pages
1710 $errors[] = array( 'cant-move-to-user-page' );
1712 } elseif ( !$user->isAllowed( $action ) ) {
1713 $errors[] = $this->missingPermissionError( $action, $short );
1720 * Add the resulting error code to the errors array
1722 * @param $errors Array list of current errors
1723 * @param $result Mixed result of errors
1725 * @return Array list of errors
1727 private function resultToError( $errors, $result ) {
1728 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1729 // A single array representing an error
1730 $errors[] = $result;
1731 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1732 // A nested array representing multiple errors
1733 $errors = array_merge( $errors, $result );
1734 } elseif ( $result !== '' && is_string( $result ) ) {
1735 // A string representing a message-id
1736 $errors[] = array( $result );
1737 } elseif ( $result === false ) {
1738 // a generic "We don't want them to do that"
1739 $errors[] = array( 'badaccess-group0' );
1745 * Check various permission hooks
1747 * @param $action String the action to check
1748 * @param $user User user to check
1749 * @param $errors Array list of current errors
1750 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1751 * @param $short Boolean short circuit on first error
1753 * @return Array list of errors
1755 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1756 // Use getUserPermissionsErrors instead
1758 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1759 return $result ?
array() : array( array( 'badaccess-group0' ) );
1761 // Check getUserPermissionsErrors hook
1762 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1763 $errors = $this->resultToError( $errors, $result );
1765 // Check getUserPermissionsErrorsExpensive hook
1766 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1767 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1768 $errors = $this->resultToError( $errors, $result );
1775 * Check permissions on special pages & namespaces
1777 * @param $action String the action to check
1778 * @param $user User user to check
1779 * @param $errors Array list of current errors
1780 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1781 * @param $short Boolean short circuit on first error
1783 * @return Array list of errors
1785 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1786 # Only 'createaccount' and 'execute' can be performed on
1787 # special pages, which don't actually exist in the DB.
1788 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1789 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1790 $errors[] = array( 'ns-specialprotected' );
1793 # Check $wgNamespaceProtection for restricted namespaces
1794 if ( $this->isNamespaceProtected( $user ) ) {
1795 $ns = $this->mNamespace
== NS_MAIN ?
1796 wfMsg( 'nstab-main' ) : $this->getNsText();
1797 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1798 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1805 * Check CSS/JS sub-page permissions
1807 * @param $action String the action to check
1808 * @param $user User user to check
1809 * @param $errors Array list of current errors
1810 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1811 * @param $short Boolean short circuit on first error
1813 * @return Array list of errors
1815 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1816 # Protect css/js subpages of user pages
1817 # XXX: this might be better using restrictions
1818 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1819 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1820 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1821 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1822 $errors[] = array( 'customcssprotected' );
1823 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1824 $errors[] = array( 'customjsprotected' );
1832 * Check against page_restrictions table requirements on this
1833 * page. The user must possess all required rights for this
1836 * @param $action String the action to check
1837 * @param $user User user to check
1838 * @param $errors Array list of current errors
1839 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1840 * @param $short Boolean short circuit on first error
1842 * @return Array list of errors
1844 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1845 foreach ( $this->getRestrictions( $action ) as $right ) {
1846 // Backwards compatibility, rewrite sysop -> protect
1847 if ( $right == 'sysop' ) {
1850 if ( $right != '' && !$user->isAllowed( $right ) ) {
1851 // Users with 'editprotected' permission can edit protected pages
1852 // without cascading option turned on.
1853 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1854 ||
$this->mCascadeRestriction
)
1856 $errors[] = array( 'protectedpagetext', $right );
1865 * Check restrictions on cascading pages.
1867 * @param $action String the action to check
1868 * @param $user User to check
1869 * @param $errors Array list of current errors
1870 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1871 * @param $short Boolean short circuit on first error
1873 * @return Array list of errors
1875 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1876 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1877 # We /could/ use the protection level on the source page, but it's
1878 # fairly ugly as we have to establish a precedence hierarchy for pages
1879 # included by multiple cascade-protected pages. So just restrict
1880 # it to people with 'protect' permission, as they could remove the
1881 # protection anyway.
1882 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1883 # Cascading protection depends on more than this page...
1884 # Several cascading protected pages may include this page...
1885 # Check each cascading level
1886 # This is only for protection restrictions, not for all actions
1887 if ( isset( $restrictions[$action] ) ) {
1888 foreach ( $restrictions[$action] as $right ) {
1889 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1890 if ( $right != '' && !$user->isAllowed( $right ) ) {
1892 foreach ( $cascadingSources as $page )
1893 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1894 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1904 * Check action permissions not already checked in checkQuickPermissions
1906 * @param $action String the action to check
1907 * @param $user User to check
1908 * @param $errors Array list of current errors
1909 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1910 * @param $short Boolean short circuit on first error
1912 * @return Array list of errors
1914 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1915 global $wgDeleteRevisionsLimit, $wgLang;
1917 if ( $action == 'protect' ) {
1918 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1919 // If they can't edit, they shouldn't protect.
1920 $errors[] = array( 'protect-cantedit' );
1922 } elseif ( $action == 'create' ) {
1923 $title_protection = $this->getTitleProtection();
1924 if( $title_protection ) {
1925 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1926 $title_protection['pt_create_perm'] = 'protect'; // B/C
1928 if( $title_protection['pt_create_perm'] == '' ||
1929 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1931 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1934 } elseif ( $action == 'move' ) {
1935 // Check for immobile pages
1936 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1937 // Specific message for this case
1938 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1939 } elseif ( !$this->isMovable() ) {
1940 // Less specific message for rarer cases
1941 $errors[] = array( 'immobile-source-page' );
1943 } elseif ( $action == 'move-target' ) {
1944 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1945 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1946 } elseif ( !$this->isMovable() ) {
1947 $errors[] = array( 'immobile-target-page' );
1949 } elseif ( $action == 'delete' ) {
1950 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
1951 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
1953 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
1960 * Check that the user isn't blocked from editting.
1962 * @param $action String the action to check
1963 * @param $user User to check
1964 * @param $errors Array list of current errors
1965 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1966 * @param $short Boolean short circuit on first error
1968 * @return Array list of errors
1970 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1971 // Account creation blocks handled at userlogin.
1972 // Unblocking handled in SpecialUnblock
1973 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1977 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1979 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1980 $errors[] = array( 'confirmedittext' );
1983 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1984 // Don't block the user from editing their own talk page unless they've been
1985 // explicitly blocked from that too.
1986 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1987 $block = $user->getBlock();
1989 // This is from OutputPage::blockedPage
1990 // Copied at r23888 by werdna
1992 $id = $user->blockedBy();
1993 $reason = $user->blockedFor();
1994 if ( $reason == '' ) {
1995 $reason = wfMsg( 'blockednoreason' );
1997 $ip = $user->getRequest()->getIP();
1999 if ( is_numeric( $id ) ) {
2000 $name = User
::whoIs( $id );
2005 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
2006 $blockid = $block->getId();
2007 $blockExpiry = $block->getExpiry();
2008 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
2009 if ( $blockExpiry == 'infinity' ) {
2010 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2012 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2015 $intended = strval( $block->getTarget() );
2017 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2018 $blockid, $blockExpiry, $intended, $blockTimestamp );
2025 * Check that the user is allowed to read this page.
2027 * @param $action String the action to check
2028 * @param $user User to check
2029 * @param $errors Array list of current errors
2030 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2031 * @param $short Boolean short circuit on first error
2033 * @return Array list of errors
2035 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2036 global $wgWhitelistRead, $wgGroupPermissions, $wgRevokePermissions;
2037 static $useShortcut = null;
2039 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2040 if ( is_null( $useShortcut ) ) {
2041 $useShortcut = true;
2042 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
2043 # Not a public wiki, so no shortcut
2044 $useShortcut = false;
2045 } elseif ( !empty( $wgRevokePermissions ) ) {
2047 * Iterate through each group with permissions being revoked (key not included since we don't care
2048 * what the group name is), then check if the read permission is being revoked. If it is, then
2049 * we don't use the shortcut below since the user might not be able to read, even though anon
2050 * reading is allowed.
2052 foreach ( $wgRevokePermissions as $perms ) {
2053 if ( !empty( $perms['read'] ) ) {
2054 # We might be removing the read right from the user, so no shortcut
2055 $useShortcut = false;
2062 $whitelisted = false;
2063 if ( $useShortcut ) {
2064 # Shortcut for public wikis, allows skipping quite a bit of code
2065 $whitelisted = true;
2066 } elseif ( $user->isAllowed( 'read' ) ) {
2067 # If the user is allowed to read pages, he is allowed to read all pages
2068 $whitelisted = true;
2069 } elseif ( $this->isSpecial( 'Userlogin' )
2070 ||
$this->isSpecial( 'ChangePassword' )
2071 ||
$this->isSpecial( 'PasswordReset' )
2073 # Always grant access to the login page.
2074 # Even anons need to be able to log in.
2075 $whitelisted = true;
2076 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2077 # Time to check the whitelist
2078 # Only do these checks is there's something to check against
2079 $name = $this->getPrefixedText();
2080 $dbName = $this->getPrefixedDBKey();
2082 // Check for explicit whitelisting with and without underscores
2083 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2084 $whitelisted = true;
2085 } elseif ( $this->getNamespace() == NS_MAIN
) {
2086 # Old settings might have the title prefixed with
2087 # a colon for main-namespace pages
2088 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2089 $whitelisted = true;
2091 } elseif ( $this->isSpecialPage() ) {
2092 # If it's a special page, ditch the subpage bit and check again
2093 $name = $this->getDBkey();
2094 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2095 if ( $name !== false ) {
2096 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2097 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2098 $whitelisted = true;
2104 if ( !$whitelisted ) {
2105 # If the title is not whitelisted, give extensions a chance to do so...
2106 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2107 if ( !$whitelisted ) {
2108 $errors[] = $this->missingPermissionError( $action, $short );
2116 * Get a description array when the user doesn't have the right to perform
2117 * $action (i.e. when User::isAllowed() returns false)
2119 * @param $action String the action to check
2120 * @param $short Boolean short circuit on first error
2121 * @return Array list of errors
2123 private function missingPermissionError( $action, $short ) {
2124 // We avoid expensive display logic for quickUserCan's and such
2126 return array( 'badaccess-group0' );
2129 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2130 User
::getGroupsWithPermission( $action ) );
2132 if ( count( $groups ) ) {
2136 $wgLang->commaList( $groups ),
2140 return array( 'badaccess-group0' );
2145 * Can $user perform $action on this page? This is an internal function,
2146 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2147 * checks on wfReadOnly() and blocks)
2149 * @param $action String action that permission needs to be checked for
2150 * @param $user User to check
2151 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2152 * @param $short Bool Set this to true to stop after the first permission error.
2153 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
2155 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2156 wfProfileIn( __METHOD__
);
2158 # Read has special handling
2159 if ( $action == 'read' ) {
2161 'checkPermissionHooks',
2162 'checkReadPermissions',
2166 'checkQuickPermissions',
2167 'checkPermissionHooks',
2168 'checkSpecialsAndNSPermissions',
2169 'checkCSSandJSPermissions',
2170 'checkPageRestrictions',
2171 'checkCascadingSourcesRestrictions',
2172 'checkActionPermissions',
2178 while( count( $checks ) > 0 &&
2179 !( $short && count( $errors ) > 0 ) ) {
2180 $method = array_shift( $checks );
2181 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2184 wfProfileOut( __METHOD__
);
2189 * Protect css subpages of user pages: can $wgUser edit
2192 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2195 public function userCanEditCssSubpage() {
2197 wfDeprecated( __METHOD__
, '1.19' );
2198 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2199 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2203 * Protect js subpages of user pages: can $wgUser edit
2206 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2209 public function userCanEditJsSubpage() {
2211 wfDeprecated( __METHOD__
, '1.19' );
2212 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2213 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2217 * Get a filtered list of all restriction types supported by this wiki.
2218 * @param bool $exists True to get all restriction types that apply to
2219 * titles that do exist, False for all restriction types that apply to
2220 * titles that do not exist
2223 public static function getFilteredRestrictionTypes( $exists = true ) {
2224 global $wgRestrictionTypes;
2225 $types = $wgRestrictionTypes;
2227 # Remove the create restriction for existing titles
2228 $types = array_diff( $types, array( 'create' ) );
2230 # Only the create and upload restrictions apply to non-existing titles
2231 $types = array_intersect( $types, array( 'create', 'upload' ) );
2237 * Returns restriction types for the current Title
2239 * @return array applicable restriction types
2241 public function getRestrictionTypes() {
2242 if ( $this->isSpecialPage() ) {
2246 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2248 if ( $this->getNamespace() != NS_FILE
) {
2249 # Remove the upload restriction for non-file titles
2250 $types = array_diff( $types, array( 'upload' ) );
2253 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2255 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2256 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2262 * Is this title subject to title protection?
2263 * Title protection is the one applied against creation of such title.
2265 * @return Mixed An associative array representing any existent title
2266 * protection, or false if there's none.
2268 private function getTitleProtection() {
2269 // Can't protect pages in special namespaces
2270 if ( $this->getNamespace() < 0 ) {
2274 // Can't protect pages that exist.
2275 if ( $this->exists() ) {
2279 if ( !isset( $this->mTitleProtection
) ) {
2280 $dbr = wfGetDB( DB_SLAVE
);
2281 $res = $dbr->select( 'protected_titles', '*',
2282 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2285 // fetchRow returns false if there are no rows.
2286 $this->mTitleProtection
= $dbr->fetchRow( $res );
2288 return $this->mTitleProtection
;
2292 * Update the title protection status
2294 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2295 * @param $create_perm String Permission required for creation
2296 * @param $reason String Reason for protection
2297 * @param $expiry String Expiry timestamp
2298 * @return boolean true
2300 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2301 wfDeprecated( __METHOD__
, '1.19' );
2305 $limit = array( 'create' => $create_perm );
2306 $expiry = array( 'create' => $expiry );
2308 $page = WikiPage
::factory( $this );
2309 $status = $page->doUpdateRestrictions( $limit, $expiry, false, $reason, $wgUser );
2311 return $status->isOK();
2315 * Remove any title protection due to page existing
2317 public function deleteTitleProtection() {
2318 $dbw = wfGetDB( DB_MASTER
);
2322 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2325 $this->mTitleProtection
= false;
2329 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2331 * @param $action String Action to check (default: edit)
2334 public function isSemiProtected( $action = 'edit' ) {
2335 if ( $this->exists() ) {
2336 $restrictions = $this->getRestrictions( $action );
2337 if ( count( $restrictions ) > 0 ) {
2338 foreach ( $restrictions as $restriction ) {
2339 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2349 # If it doesn't exist, it can't be protected
2355 * Does the title correspond to a protected article?
2357 * @param $action String the action the page is protected from,
2358 * by default checks all actions.
2361 public function isProtected( $action = '' ) {
2362 global $wgRestrictionLevels;
2364 $restrictionTypes = $this->getRestrictionTypes();
2366 # Special pages have inherent protection
2367 if( $this->isSpecialPage() ) {
2371 # Check regular protection levels
2372 foreach ( $restrictionTypes as $type ) {
2373 if ( $action == $type ||
$action == '' ) {
2374 $r = $this->getRestrictions( $type );
2375 foreach ( $wgRestrictionLevels as $level ) {
2376 if ( in_array( $level, $r ) && $level != '' ) {
2387 * Determines if $user is unable to edit this page because it has been protected
2388 * by $wgNamespaceProtection.
2390 * @param $user User object to check permissions
2393 public function isNamespaceProtected( User
$user ) {
2394 global $wgNamespaceProtection;
2396 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2397 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2398 if ( $right != '' && !$user->isAllowed( $right ) ) {
2407 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2409 * @return Bool If the page is subject to cascading restrictions.
2411 public function isCascadeProtected() {
2412 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2413 return ( $sources > 0 );
2417 * Cascading protection: Get the source of any cascading restrictions on this page.
2419 * @param $getPages Bool Whether or not to retrieve the actual pages
2420 * that the restrictions have come from.
2421 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2422 * have come, false for none, or true if such restrictions exist, but $getPages
2423 * was not set. The restriction array is an array of each type, each of which
2424 * contains a array of unique groups.
2426 public function getCascadeProtectionSources( $getPages = true ) {
2428 $pagerestrictions = array();
2430 if ( isset( $this->mCascadeSources
) && $getPages ) {
2431 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2432 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2433 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2436 wfProfileIn( __METHOD__
);
2438 $dbr = wfGetDB( DB_SLAVE
);
2440 if ( $this->getNamespace() == NS_FILE
) {
2441 $tables = array( 'imagelinks', 'page_restrictions' );
2442 $where_clauses = array(
2443 'il_to' => $this->getDBkey(),
2448 $tables = array( 'templatelinks', 'page_restrictions' );
2449 $where_clauses = array(
2450 'tl_namespace' => $this->getNamespace(),
2451 'tl_title' => $this->getDBkey(),
2458 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2459 'pr_expiry', 'pr_type', 'pr_level' );
2460 $where_clauses[] = 'page_id=pr_page';
2463 $cols = array( 'pr_expiry' );
2466 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2468 $sources = $getPages ?
array() : false;
2469 $now = wfTimestampNow();
2470 $purgeExpired = false;
2472 foreach ( $res as $row ) {
2473 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2474 if ( $expiry > $now ) {
2476 $page_id = $row->pr_page
;
2477 $page_ns = $row->page_namespace
;
2478 $page_title = $row->page_title
;
2479 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2480 # Add groups needed for each restriction type if its not already there
2481 # Make sure this restriction type still exists
2483 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2484 $pagerestrictions[$row->pr_type
] = array();
2487 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2488 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2489 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2495 // Trigger lazy purge of expired restrictions from the db
2496 $purgeExpired = true;
2499 if ( $purgeExpired ) {
2500 Title
::purgeExpiredRestrictions();
2504 $this->mCascadeSources
= $sources;
2505 $this->mCascadingRestrictions
= $pagerestrictions;
2507 $this->mHasCascadingRestrictions
= $sources;
2510 wfProfileOut( __METHOD__
);
2511 return array( $sources, $pagerestrictions );
2515 * Accessor/initialisation for mRestrictions
2517 * @param $action String action that permission needs to be checked for
2518 * @return Array of Strings the array of groups allowed to edit this article
2520 public function getRestrictions( $action ) {
2521 if ( !$this->mRestrictionsLoaded
) {
2522 $this->loadRestrictions();
2524 return isset( $this->mRestrictions
[$action] )
2525 ?
$this->mRestrictions
[$action]
2530 * Get the expiry time for the restriction against a given action
2533 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2534 * or not protected at all, or false if the action is not recognised.
2536 public function getRestrictionExpiry( $action ) {
2537 if ( !$this->mRestrictionsLoaded
) {
2538 $this->loadRestrictions();
2540 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2544 * Returns cascading restrictions for the current article
2548 function areRestrictionsCascading() {
2549 if ( !$this->mRestrictionsLoaded
) {
2550 $this->loadRestrictions();
2553 return $this->mCascadeRestriction
;
2557 * Loads a string into mRestrictions array
2559 * @param $res Resource restrictions as an SQL result.
2560 * @param $oldFashionedRestrictions String comma-separated list of page
2561 * restrictions from page table (pre 1.10)
2563 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2566 foreach ( $res as $row ) {
2570 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2574 * Compiles list of active page restrictions from both page table (pre 1.10)
2575 * and page_restrictions table for this existing page.
2576 * Public for usage by LiquidThreads.
2578 * @param $rows array of db result objects
2579 * @param $oldFashionedRestrictions string comma-separated list of page
2580 * restrictions from page table (pre 1.10)
2582 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2584 $dbr = wfGetDB( DB_SLAVE
);
2586 $restrictionTypes = $this->getRestrictionTypes();
2588 foreach ( $restrictionTypes as $type ) {
2589 $this->mRestrictions
[$type] = array();
2590 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2593 $this->mCascadeRestriction
= false;
2595 # Backwards-compatibility: also load the restrictions from the page record (old format).
2597 if ( $oldFashionedRestrictions === null ) {
2598 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2599 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2602 if ( $oldFashionedRestrictions != '' ) {
2604 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2605 $temp = explode( '=', trim( $restrict ) );
2606 if ( count( $temp ) == 1 ) {
2607 // old old format should be treated as edit/move restriction
2608 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2609 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2611 $restriction = trim( $temp[1] );
2612 if( $restriction != '' ) { //some old entries are empty
2613 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2618 $this->mOldRestrictions
= true;
2622 if ( count( $rows ) ) {
2623 # Current system - load second to make them override.
2624 $now = wfTimestampNow();
2625 $purgeExpired = false;
2627 # Cycle through all the restrictions.
2628 foreach ( $rows as $row ) {
2630 // Don't take care of restrictions types that aren't allowed
2631 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2634 // This code should be refactored, now that it's being used more generally,
2635 // But I don't really see any harm in leaving it in Block for now -werdna
2636 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2638 // Only apply the restrictions if they haven't expired!
2639 if ( !$expiry ||
$expiry > $now ) {
2640 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2641 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2643 $this->mCascadeRestriction |
= $row->pr_cascade
;
2645 // Trigger a lazy purge of expired restrictions
2646 $purgeExpired = true;
2650 if ( $purgeExpired ) {
2651 Title
::purgeExpiredRestrictions();
2655 $this->mRestrictionsLoaded
= true;
2659 * Load restrictions from the page_restrictions table
2661 * @param $oldFashionedRestrictions String comma-separated list of page
2662 * restrictions from page table (pre 1.10)
2664 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2666 if ( !$this->mRestrictionsLoaded
) {
2667 if ( $this->exists() ) {
2668 $dbr = wfGetDB( DB_SLAVE
);
2670 $res = $dbr->select(
2671 'page_restrictions',
2673 array( 'pr_page' => $this->getArticleID() ),
2677 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2679 $title_protection = $this->getTitleProtection();
2681 if ( $title_protection ) {
2682 $now = wfTimestampNow();
2683 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2685 if ( !$expiry ||
$expiry > $now ) {
2686 // Apply the restrictions
2687 $this->mRestrictionsExpiry
['create'] = $expiry;
2688 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2689 } else { // Get rid of the old restrictions
2690 Title
::purgeExpiredRestrictions();
2691 $this->mTitleProtection
= false;
2694 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2696 $this->mRestrictionsLoaded
= true;
2702 * Flush the protection cache in this object and force reload from the database.
2703 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2705 public function flushRestrictions() {
2706 $this->mRestrictionsLoaded
= false;
2707 $this->mTitleProtection
= null;
2711 * Purge expired restrictions from the page_restrictions table
2713 static function purgeExpiredRestrictions() {
2714 $dbw = wfGetDB( DB_MASTER
);
2716 'page_restrictions',
2717 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2723 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2729 * Does this have subpages? (Warning, usually requires an extra DB query.)
2733 public function hasSubpages() {
2734 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2739 # We dynamically add a member variable for the purpose of this method
2740 # alone to cache the result. There's no point in having it hanging
2741 # around uninitialized in every Title object; therefore we only add it
2742 # if needed and don't declare it statically.
2743 if ( isset( $this->mHasSubpages
) ) {
2744 return $this->mHasSubpages
;
2747 $subpages = $this->getSubpages( 1 );
2748 if ( $subpages instanceof TitleArray
) {
2749 return $this->mHasSubpages
= (bool)$subpages->count();
2751 return $this->mHasSubpages
= false;
2755 * Get all subpages of this page.
2757 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2758 * @return mixed TitleArray, or empty array if this page's namespace
2759 * doesn't allow subpages
2761 public function getSubpages( $limit = -1 ) {
2762 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2766 $dbr = wfGetDB( DB_SLAVE
);
2767 $conds['page_namespace'] = $this->getNamespace();
2768 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2770 if ( $limit > -1 ) {
2771 $options['LIMIT'] = $limit;
2773 return $this->mSubpages
= TitleArray
::newFromResult(
2774 $dbr->select( 'page',
2775 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2784 * Is there a version of this page in the deletion archive?
2786 * @return Int the number of archived revisions
2788 public function isDeleted() {
2789 if ( $this->getNamespace() < 0 ) {
2792 $dbr = wfGetDB( DB_SLAVE
);
2794 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2795 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2798 if ( $this->getNamespace() == NS_FILE
) {
2799 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2800 array( 'fa_name' => $this->getDBkey() ),
2809 * Is there a version of this page in the deletion archive?
2813 public function isDeletedQuick() {
2814 if ( $this->getNamespace() < 0 ) {
2817 $dbr = wfGetDB( DB_SLAVE
);
2818 $deleted = (bool)$dbr->selectField( 'archive', '1',
2819 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2822 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2823 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2824 array( 'fa_name' => $this->getDBkey() ),
2832 * Get the article ID for this Title from the link cache,
2833 * adding it if necessary
2835 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2837 * @return Int the ID
2839 public function getArticleID( $flags = 0 ) {
2840 if ( $this->getNamespace() < 0 ) {
2841 return $this->mArticleID
= 0;
2843 $linkCache = LinkCache
::singleton();
2844 if ( $flags & self
::GAID_FOR_UPDATE
) {
2845 $oldUpdate = $linkCache->forUpdate( true );
2846 $linkCache->clearLink( $this );
2847 $this->mArticleID
= $linkCache->addLinkObj( $this );
2848 $linkCache->forUpdate( $oldUpdate );
2850 if ( -1 == $this->mArticleID
) {
2851 $this->mArticleID
= $linkCache->addLinkObj( $this );
2854 return $this->mArticleID
;
2858 * Is this an article that is a redirect page?
2859 * Uses link cache, adding it if necessary
2861 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2864 public function isRedirect( $flags = 0 ) {
2865 if ( !is_null( $this->mRedirect
) ) {
2866 return $this->mRedirect
;
2868 # Calling getArticleID() loads the field from cache as needed
2869 if ( !$this->getArticleID( $flags ) ) {
2870 return $this->mRedirect
= false;
2873 $linkCache = LinkCache
::singleton();
2874 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2875 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #XXX breaks stuff #TODO: use exception
2877 $this->mRedirect
= (bool)$cached;
2879 return $this->mRedirect
;
2883 * What is the length of this page?
2884 * Uses link cache, adding it if necessary
2886 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2889 public function getLength( $flags = 0 ) {
2890 if ( $this->mLength
!= -1 ) {
2891 return $this->mLength
;
2893 # Calling getArticleID() loads the field from cache as needed
2894 if ( !$this->getArticleID( $flags ) ) {
2895 return $this->mLength
= 0;
2897 $linkCache = LinkCache
::singleton();
2898 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2899 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2901 $this->mLength
= intval( $cached );
2903 return $this->mLength
;
2907 * What is the page_latest field for this page?
2909 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2910 * @return Int or 0 if the page doesn't exist
2912 public function getLatestRevID( $flags = 0 ) {
2913 if ( $this->mLatestID
!== false ) {
2914 return intval( $this->mLatestID
);
2916 # Calling getArticleID() loads the field from cache as needed
2917 if ( !$this->getArticleID( $flags ) ) {
2918 return $this->mLatestID
= 0;
2920 $linkCache = LinkCache
::singleton();
2921 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2922 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2924 $this->mLatestID
= intval( $cached );
2926 return $this->mLatestID
;
2930 * This clears some fields in this object, and clears any associated
2931 * keys in the "bad links" section of the link cache.
2933 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2934 * loading of the new page_id. It's also called from
2935 * WikiPage::doDeleteArticle()
2937 * @param $newid Int the new Article ID
2939 public function resetArticleID( $newid ) {
2940 $linkCache = LinkCache
::singleton();
2941 $linkCache->clearLink( $this );
2943 if ( $newid === false ) {
2944 $this->mArticleID
= -1;
2946 $this->mArticleID
= intval( $newid );
2948 $this->mRestrictionsLoaded
= false;
2949 $this->mRestrictions
= array();
2950 $this->mRedirect
= null;
2951 $this->mLength
= -1;
2952 $this->mLatestID
= false;
2953 $this->mEstimateRevisions
= null;
2957 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2959 * @param $text String containing title to capitalize
2960 * @param $ns int namespace index, defaults to NS_MAIN
2961 * @return String containing capitalized title
2963 public static function capitalize( $text, $ns = NS_MAIN
) {
2966 if ( MWNamespace
::isCapitalized( $ns ) ) {
2967 return $wgContLang->ucfirst( $text );
2974 * Secure and split - main initialisation function for this object
2976 * Assumes that mDbkeyform has been set, and is urldecoded
2977 * and uses underscores, but not otherwise munged. This function
2978 * removes illegal characters, splits off the interwiki and
2979 * namespace prefixes, sets the other forms, and canonicalizes
2982 * @return Bool true on success
2984 private function secureAndSplit() {
2985 global $wgContLang, $wgLocalInterwiki;
2988 $this->mInterwiki
= $this->mFragment
= '';
2989 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2991 $dbkey = $this->mDbkeyform
;
2993 # Strip Unicode bidi override characters.
2994 # Sometimes they slip into cut-n-pasted page titles, where the
2995 # override chars get included in list displays.
2996 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2998 # Clean up whitespace
2999 # Note: use of the /u option on preg_replace here will cause
3000 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3001 # conveniently disabling them.
3002 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3003 $dbkey = trim( $dbkey, '_' );
3005 if ( $dbkey == '' ) {
3009 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3010 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3014 $this->mDbkeyform
= $dbkey;
3016 # Initial colon indicates main namespace rather than specified default
3017 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3018 if ( ':' == $dbkey[0] ) {
3019 $this->mNamespace
= NS_MAIN
;
3020 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3021 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3024 # Namespace or interwiki prefix
3026 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3029 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3031 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3032 # Ordinary namespace
3034 $this->mNamespace
= $ns;
3035 # For Talk:X pages, check if X has a "namespace" prefix
3036 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3037 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3038 # Disallow Talk:File:x type titles...
3040 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3041 # Disallow Talk:Interwiki:x type titles...
3045 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3046 if ( !$firstPass ) {
3047 # Can't make a local interwiki link to an interwiki link.
3048 # That's just crazy!
3054 $this->mInterwiki
= $wgContLang->lc( $p );
3056 # Redundant interwiki prefix to the local wiki
3057 if ( $wgLocalInterwiki !== false
3058 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3060 if ( $dbkey == '' ) {
3061 # Can't have an empty self-link
3064 $this->mInterwiki
= '';
3066 # Do another namespace split...
3070 # If there's an initial colon after the interwiki, that also
3071 # resets the default namespace
3072 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3073 $this->mNamespace
= NS_MAIN
;
3074 $dbkey = substr( $dbkey, 1 );
3077 # If there's no recognized interwiki or namespace,
3078 # then let the colon expression be part of the title.
3083 # We already know that some pages won't be in the database!
3084 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3085 $this->mArticleID
= 0;
3087 $fragment = strstr( $dbkey, '#' );
3088 if ( false !== $fragment ) {
3089 $this->setFragment( $fragment );
3090 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3091 # remove whitespace again: prevents "Foo_bar_#"
3092 # becoming "Foo_bar_"
3093 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3096 # Reject illegal characters.
3097 $rxTc = self
::getTitleInvalidRegex();
3098 if ( preg_match( $rxTc, $dbkey ) ) {
3102 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3103 # reachable due to the way web browsers deal with 'relative' URLs.
3104 # Also, they conflict with subpage syntax. Forbid them explicitly.
3105 if ( strpos( $dbkey, '.' ) !== false &&
3106 ( $dbkey === '.' ||
$dbkey === '..' ||
3107 strpos( $dbkey, './' ) === 0 ||
3108 strpos( $dbkey, '../' ) === 0 ||
3109 strpos( $dbkey, '/./' ) !== false ||
3110 strpos( $dbkey, '/../' ) !== false ||
3111 substr( $dbkey, -2 ) == '/.' ||
3112 substr( $dbkey, -3 ) == '/..' ) )
3117 # Magic tilde sequences? Nu-uh!
3118 if ( strpos( $dbkey, '~~~' ) !== false ) {
3122 # Limit the size of titles to 255 bytes. This is typically the size of the
3123 # underlying database field. We make an exception for special pages, which
3124 # don't need to be stored in the database, and may edge over 255 bytes due
3125 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3126 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
3127 strlen( $dbkey ) > 512 )
3132 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3133 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3134 # other site might be case-sensitive.
3135 $this->mUserCaseDBKey
= $dbkey;
3136 if ( $this->mInterwiki
== '' ) {
3137 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3140 # Can't make a link to a namespace alone... "empty" local links can only be
3141 # self-links with a fragment identifier.
3142 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3146 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3147 // IP names are not allowed for accounts, and can only be referring to
3148 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3149 // there are numerous ways to present the same IP. Having sp:contribs scan
3150 // them all is silly and having some show the edits and others not is
3151 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3152 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3153 ? IP
::sanitizeIP( $dbkey )
3156 // Any remaining initial :s are illegal.
3157 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3162 $this->mDbkeyform
= $dbkey;
3163 $this->mUrlform
= wfUrlencode( $dbkey );
3165 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3171 * Get an array of Title objects linking to this Title
3172 * Also stores the IDs in the link cache.
3174 * WARNING: do not use this function on arbitrary user-supplied titles!
3175 * On heavily-used templates it will max out the memory.
3177 * @param $options Array: may be FOR UPDATE
3178 * @param $table String: table name
3179 * @param $prefix String: fields prefix
3180 * @return Array of Title objects linking here
3182 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3183 if ( count( $options ) > 0 ) {
3184 $db = wfGetDB( DB_MASTER
);
3186 $db = wfGetDB( DB_SLAVE
);
3190 array( 'page', $table ),
3191 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3193 "{$prefix}_from=page_id",
3194 "{$prefix}_namespace" => $this->getNamespace(),
3195 "{$prefix}_title" => $this->getDBkey() ),
3201 if ( $res->numRows() ) {
3202 $linkCache = LinkCache
::singleton();
3203 foreach ( $res as $row ) {
3204 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3206 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3207 $retVal[] = $titleObj;
3215 * Get an array of Title objects using this Title as a template
3216 * Also stores the IDs in the link cache.
3218 * WARNING: do not use this function on arbitrary user-supplied titles!
3219 * On heavily-used templates it will max out the memory.
3221 * @param $options Array: may be FOR UPDATE
3222 * @return Array of Title the Title objects linking here
3224 public function getTemplateLinksTo( $options = array() ) {
3225 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3229 * Get an array of Title objects linked from this Title
3230 * Also stores the IDs in the link cache.
3232 * WARNING: do not use this function on arbitrary user-supplied titles!
3233 * On heavily-used templates it will max out the memory.
3235 * @param $options Array: may be FOR UPDATE
3236 * @param $table String: table name
3237 * @param $prefix String: fields prefix
3238 * @return Array of Title objects linking here
3240 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3241 $id = $this->getArticleID();
3243 # If the page doesn't exist; there can't be any link from this page
3248 if ( count( $options ) > 0 ) {
3249 $db = wfGetDB( DB_MASTER
);
3251 $db = wfGetDB( DB_SLAVE
);
3254 $namespaceFiled = "{$prefix}_namespace";
3255 $titleField = "{$prefix}_title";
3258 array( $table, 'page' ),
3259 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3260 array( "{$prefix}_from" => $id ),
3263 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3267 if ( $res->numRows() ) {
3268 $linkCache = LinkCache
::singleton();
3269 foreach ( $res as $row ) {
3270 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3272 if ( $row->page_id
) {
3273 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3275 $linkCache->addBadLinkObj( $titleObj );
3277 $retVal[] = $titleObj;
3285 * Get an array of Title objects used on this Title as a template
3286 * Also stores the IDs in the link cache.
3288 * WARNING: do not use this function on arbitrary user-supplied titles!
3289 * On heavily-used templates it will max out the memory.
3291 * @param $options Array: may be FOR UPDATE
3292 * @return Array of Title the Title objects used here
3294 public function getTemplateLinksFrom( $options = array() ) {
3295 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3299 * Get an array of Title objects referring to non-existent articles linked from this page
3301 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3302 * @return Array of Title the Title objects
3304 public function getBrokenLinksFrom() {
3305 if ( $this->getArticleID() == 0 ) {
3306 # All links from article ID 0 are false positives
3310 $dbr = wfGetDB( DB_SLAVE
);
3311 $res = $dbr->select(
3312 array( 'page', 'pagelinks' ),
3313 array( 'pl_namespace', 'pl_title' ),
3315 'pl_from' => $this->getArticleID(),
3316 'page_namespace IS NULL'
3318 __METHOD__
, array(),
3322 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3328 foreach ( $res as $row ) {
3329 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3336 * Get a list of URLs to purge from the Squid cache when this
3339 * @return Array of String the URLs
3341 public function getSquidURLs() {
3345 $this->getInternalURL(),
3346 $this->getInternalURL( 'action=history' )
3349 // purge variant urls as well
3350 if ( $wgContLang->hasVariants() ) {
3351 $variants = $wgContLang->getVariants();
3352 foreach ( $variants as $vCode ) {
3353 $urls[] = $this->getInternalURL( '', $vCode );
3361 * Purge all applicable Squid URLs
3363 public function purgeSquid() {
3365 if ( $wgUseSquid ) {
3366 $urls = $this->getSquidURLs();
3367 $u = new SquidUpdate( $urls );
3373 * Move this page without authentication
3375 * @param $nt Title the new page Title
3376 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3378 public function moveNoAuth( &$nt ) {
3379 return $this->moveTo( $nt, false );
3383 * Check whether a given move operation would be valid.
3384 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3386 * @param $nt Title the new title
3387 * @param $auth Bool indicates whether $wgUser's permissions
3389 * @param $reason String is the log summary of the move, used for spam checking
3390 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3392 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3397 // Normally we'd add this to $errors, but we'll get
3398 // lots of syntax errors if $nt is not an object
3399 return array( array( 'badtitletext' ) );
3401 if ( $this->equals( $nt ) ) {
3402 $errors[] = array( 'selfmove' );
3404 if ( !$this->isMovable() ) {
3405 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3407 if ( $nt->getInterwiki() != '' ) {
3408 $errors[] = array( 'immobile-target-namespace-iw' );
3410 if ( !$nt->isMovable() ) {
3411 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3414 $oldid = $this->getArticleID();
3415 $newid = $nt->getArticleID();
3417 if ( strlen( $nt->getDBkey() ) < 1 ) {
3418 $errors[] = array( 'articleexists' );
3420 if ( ( $this->getDBkey() == '' ) ||
3422 ( $nt->getDBkey() == '' ) ) {
3423 $errors[] = array( 'badarticleerror' );
3426 // Image-specific checks
3427 if ( $this->getNamespace() == NS_FILE
) {
3428 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3431 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3432 $errors[] = array( 'nonfile-cannot-move-to-file' );
3436 $errors = wfMergeErrorArrays( $errors,
3437 $this->getUserPermissionsErrors( 'move', $wgUser ),
3438 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3439 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3440 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3443 $match = EditPage
::matchSummarySpamRegex( $reason );
3444 if ( $match !== false ) {
3445 // This is kind of lame, won't display nice
3446 $errors[] = array( 'spamprotectiontext' );
3450 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3451 $errors[] = array( 'hookaborted', $err );
3454 # The move is allowed only if (1) the target doesn't exist, or
3455 # (2) the target is a redirect to the source, and has no history
3456 # (so we can undo bad moves right after they're done).
3458 if ( 0 != $newid ) { # Target exists; check for validity
3459 if ( !$this->isValidMoveTarget( $nt ) ) {
3460 $errors[] = array( 'articleexists' );
3463 $tp = $nt->getTitleProtection();
3464 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3465 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3466 $errors[] = array( 'cantmove-titleprotected' );
3469 if ( empty( $errors ) ) {
3476 * Check if the requested move target is a valid file move target
3477 * @param Title $nt Target title
3478 * @return array List of errors
3480 protected function validateFileMoveOperation( $nt ) {
3485 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3487 $file = wfLocalFile( $this );
3488 if ( $file->exists() ) {
3489 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3490 $errors[] = array( 'imageinvalidfilename' );
3492 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3493 $errors[] = array( 'imagetypemismatch' );
3497 if ( $nt->getNamespace() != NS_FILE
) {
3498 $errors[] = array( 'imagenocrossnamespace' );
3499 // From here we want to do checks on a file object, so if we can't
3500 // create one, we must return.
3504 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3506 $destFile = wfLocalFile( $nt );
3507 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3508 $errors[] = array( 'file-exists-sharedrepo' );
3515 * Move a title to a new location
3517 * @param $nt Title the new title
3518 * @param $auth Bool indicates whether $wgUser's permissions
3520 * @param $reason String the reason for the move
3521 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3522 * Ignored if the user doesn't have the suppressredirect right.
3523 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3525 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3527 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3528 if ( is_array( $err ) ) {
3529 // Auto-block user's IP if the account was "hard" blocked
3530 $wgUser->spreadAnyEditBlock();
3534 // If it is a file, move it first.
3535 // It is done before all other moving stuff is done because it's hard to revert.
3536 $dbw = wfGetDB( DB_MASTER
);
3537 if ( $this->getNamespace() == NS_FILE
) {
3538 $file = wfLocalFile( $this );
3539 if ( $file->exists() ) {
3540 $status = $file->move( $nt );
3541 if ( !$status->isOk() ) {
3542 return $status->getErrorsArray();
3545 // Clear RepoGroup process cache
3546 RepoGroup
::singleton()->clearCache( $this );
3547 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3550 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3551 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3552 $protected = $this->isProtected();
3554 // Do the actual move
3555 $this->moveToInternal( $nt, $reason, $createRedirect );
3557 // Refresh the sortkey for this row. Be careful to avoid resetting
3558 // cl_timestamp, which may disturb time-based lists on some sites.
3559 $prefixes = $dbw->select(
3561 array( 'cl_sortkey_prefix', 'cl_to' ),
3562 array( 'cl_from' => $pageid ),
3565 foreach ( $prefixes as $prefixRow ) {
3566 $prefix = $prefixRow->cl_sortkey_prefix
;
3567 $catTo = $prefixRow->cl_to
;
3568 $dbw->update( 'categorylinks',
3570 'cl_sortkey' => Collation
::singleton()->getSortKey(
3571 $nt->getCategorySortkey( $prefix ) ),
3572 'cl_timestamp=cl_timestamp' ),
3574 'cl_from' => $pageid,
3575 'cl_to' => $catTo ),
3580 $redirid = $this->getArticleID();
3583 # Protect the redirect title as the title used to be...
3584 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3586 'pr_page' => $redirid,
3587 'pr_type' => 'pr_type',
3588 'pr_level' => 'pr_level',
3589 'pr_cascade' => 'pr_cascade',
3590 'pr_user' => 'pr_user',
3591 'pr_expiry' => 'pr_expiry'
3593 array( 'pr_page' => $pageid ),
3597 # Update the protection log
3598 $log = new LogPage( 'protect' );
3599 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3601 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3603 // @todo FIXME: $params?
3604 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3608 $oldnamespace = $this->getNamespace() & ~
1;
3609 $newnamespace = $nt->getNamespace() & ~
1;
3610 $oldtitle = $this->getDBkey();
3611 $newtitle = $nt->getDBkey();
3613 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3614 WatchedItem
::duplicateEntries( $this, $nt );
3617 $dbw->commit( __METHOD__
);
3619 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3624 * Move page to a title which is either a redirect to the
3625 * source page or nonexistent
3627 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3628 * @param $reason String The reason for the move
3629 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3630 * if the user doesn't have the suppressredirect right
3631 * @throws MWException
3633 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3634 global $wgUser, $wgContLang;
3636 if ( $nt->exists() ) {
3637 $moveOverRedirect = true;
3638 $logType = 'move_redir';
3640 $moveOverRedirect = false;
3644 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3646 $logEntry = new ManualLogEntry( 'move', $logType );
3647 $logEntry->setPerformer( $wgUser );
3648 $logEntry->setTarget( $this );
3649 $logEntry->setComment( $reason );
3650 $logEntry->setParameters( array(
3651 '4::target' => $nt->getPrefixedText(),
3652 '5::noredir' => $redirectSuppressed ?
'1': '0',
3655 $formatter = LogFormatter
::newFromEntry( $logEntry );
3656 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3657 $comment = $formatter->getPlainActionText();
3659 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3661 # Truncate for whole multibyte characters.
3662 $comment = $wgContLang->truncate( $comment, 255 );
3664 $oldid = $this->getArticleID();
3666 $dbw = wfGetDB( DB_MASTER
);
3668 $newpage = WikiPage
::factory( $nt );
3670 if ( $moveOverRedirect ) {
3671 $newid = $nt->getArticleID();
3673 # Delete the old redirect. We don't save it to history since
3674 # by definition if we've got here it's rather uninteresting.
3675 # We have to remove it so that the next step doesn't trigger
3676 # a conflict on the unique namespace+title index...
3677 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3679 $newpage->doDeleteUpdates( $newid );
3682 # Save a null revision in the page's history notifying of the move
3683 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3684 if ( !is_object( $nullRevision ) ) {
3685 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3687 $nullRevId = $nullRevision->insertOn( $dbw );
3689 # Change the name of the target page:
3690 $dbw->update( 'page',
3692 'page_namespace' => $nt->getNamespace(),
3693 'page_title' => $nt->getDBkey(),
3695 /* WHERE */ array( 'page_id' => $oldid ),
3699 $this->resetArticleID( 0 );
3700 $nt->resetArticleID( $oldid );
3702 $newpage->updateRevisionOn( $dbw, $nullRevision );
3704 wfRunHooks( 'NewRevisionFromEditComplete',
3705 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3707 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3709 if ( !$moveOverRedirect ) {
3710 WikiPage
::onArticleCreate( $nt );
3713 # Recreate the redirect, this time in the other direction.
3714 if ( $redirectSuppressed ) {
3715 WikiPage
::onArticleDelete( $this );
3717 $mwRedir = MagicWord
::get( 'redirect' );
3718 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3719 $redirectArticle = WikiPage
::factory( $this );
3720 $newid = $redirectArticle->insertOn( $dbw );
3721 if ( $newid ) { // sanity
3722 $redirectRevision = new Revision( array(
3724 'comment' => $comment,
3725 'text' => $redirectText ) );
3726 $redirectRevision->insertOn( $dbw );
3727 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3729 wfRunHooks( 'NewRevisionFromEditComplete',
3730 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3732 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3737 $logid = $logEntry->insert();
3738 $logEntry->publish( $logid );
3742 * Move this page's subpages to be subpages of $nt
3744 * @param $nt Title Move target
3745 * @param $auth bool Whether $wgUser's permissions should be checked
3746 * @param $reason string The reason for the move
3747 * @param $createRedirect bool Whether to create redirects from the old subpages to
3748 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3749 * @return mixed array with old page titles as keys, and strings (new page titles) or
3750 * arrays (errors) as values, or an error array with numeric indices if no pages
3753 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3754 global $wgMaximumMovedPages;
3755 // Check permissions
3756 if ( !$this->userCan( 'move-subpages' ) ) {
3757 return array( 'cant-move-subpages' );
3759 // Do the source and target namespaces support subpages?
3760 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3761 return array( 'namespace-nosubpages',
3762 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3764 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3765 return array( 'namespace-nosubpages',
3766 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3769 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3772 foreach ( $subpages as $oldSubpage ) {
3774 if ( $count > $wgMaximumMovedPages ) {
3775 $retval[$oldSubpage->getPrefixedTitle()] =
3776 array( 'movepage-max-pages',
3777 $wgMaximumMovedPages );
3781 // We don't know whether this function was called before
3782 // or after moving the root page, so check both
3784 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3785 $oldSubpage->getArticleID() == $nt->getArticleID() )
3787 // When moving a page to a subpage of itself,
3788 // don't move it twice
3791 $newPageName = preg_replace(
3792 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3793 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3794 $oldSubpage->getDBkey() );
3795 if ( $oldSubpage->isTalkPage() ) {
3796 $newNs = $nt->getTalkPage()->getNamespace();
3798 $newNs = $nt->getSubjectPage()->getNamespace();
3800 # Bug 14385: we need makeTitleSafe because the new page names may
3801 # be longer than 255 characters.
3802 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3804 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3805 if ( $success === true ) {
3806 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3808 $retval[$oldSubpage->getPrefixedText()] = $success;
3815 * Checks if this page is just a one-rev redirect.
3816 * Adds lock, so don't use just for light purposes.
3820 public function isSingleRevRedirect() {
3821 $dbw = wfGetDB( DB_MASTER
);
3823 $row = $dbw->selectRow( 'page',
3824 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3827 array( 'FOR UPDATE' )
3829 # Cache some fields we may want
3830 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3831 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3832 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3833 if ( !$this->mRedirect
) {
3836 # Does the article have a history?
3837 $row = $dbw->selectField( array( 'page', 'revision' ),
3839 array( 'page_namespace' => $this->getNamespace(),
3840 'page_title' => $this->getDBkey(),
3842 'page_latest != rev_id'
3845 array( 'FOR UPDATE' )
3847 # Return true if there was no history
3848 return ( $row === false );
3852 * Checks if $this can be moved to a given Title
3853 * - Selects for update, so don't call it unless you mean business
3855 * @param $nt Title the new title to check
3858 public function isValidMoveTarget( $nt ) {
3859 # Is it an existing file?
3860 if ( $nt->getNamespace() == NS_FILE
) {
3861 $file = wfLocalFile( $nt );
3862 if ( $file->exists() ) {
3863 wfDebug( __METHOD__
. ": file exists\n" );
3867 # Is it a redirect with no history?
3868 if ( !$nt->isSingleRevRedirect() ) {
3869 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3872 # Get the article text
3873 $rev = Revision
::newFromTitle( $nt );
3874 if( !is_object( $rev ) ){
3877 $content = $rev->getContent();
3878 # Does the redirect point to the source?
3879 # Or is it a broken self-redirect, usually caused by namespace collisions?
3880 $redirTitle = $content->getRedirectTarget();
3882 if ( $redirTitle ) {
3883 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3884 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3885 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3891 # Fail safe (not a redirect after all. strange.)
3892 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() . " is a redirect, but it doesn't contain a valid redirect.\n" );
3898 * Get categories to which this Title belongs and return an array of
3899 * categories' names.
3901 * @return Array of parents in the form:
3902 * $parent => $currentarticle
3904 public function getParentCategories() {
3909 $titleKey = $this->getArticleID();
3911 if ( $titleKey === 0 ) {
3915 $dbr = wfGetDB( DB_SLAVE
);
3917 $res = $dbr->select( 'categorylinks', '*',
3919 'cl_from' => $titleKey,
3925 if ( $dbr->numRows( $res ) > 0 ) {
3926 foreach ( $res as $row ) {
3927 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3928 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3935 * Get a tree of parent categories
3937 * @param $children Array with the children in the keys, to check for circular refs
3938 * @return Array Tree of parent categories
3940 public function getParentCategoryTree( $children = array() ) {
3942 $parents = $this->getParentCategories();
3945 foreach ( $parents as $parent => $current ) {
3946 if ( array_key_exists( $parent, $children ) ) {
3947 # Circular reference
3948 $stack[$parent] = array();
3950 $nt = Title
::newFromText( $parent );
3952 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3962 * Get an associative array for selecting this title from
3965 * @return Array suitable for the $where parameter of DB::select()
3967 public function pageCond() {
3968 if ( $this->mArticleID
> 0 ) {
3969 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3970 return array( 'page_id' => $this->mArticleID
);
3972 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3977 * Get the revision ID of the previous revision
3979 * @param $revId Int Revision ID. Get the revision that was before this one.
3980 * @param $flags Int Title::GAID_FOR_UPDATE
3981 * @return Int|Bool Old revision ID, or FALSE if none exists
3983 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3984 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3985 $revId = $db->selectField( 'revision', 'rev_id',
3987 'rev_page' => $this->getArticleID( $flags ),
3988 'rev_id < ' . intval( $revId )
3991 array( 'ORDER BY' => 'rev_id DESC' )
3994 if ( $revId === false ) {
3997 return intval( $revId );
4002 * Get the revision ID of the next revision
4004 * @param $revId Int Revision ID. Get the revision that was after this one.
4005 * @param $flags Int Title::GAID_FOR_UPDATE
4006 * @return Int|Bool Next revision ID, or FALSE if none exists
4008 public function getNextRevisionID( $revId, $flags = 0 ) {
4009 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4010 $revId = $db->selectField( 'revision', 'rev_id',
4012 'rev_page' => $this->getArticleID( $flags ),
4013 'rev_id > ' . intval( $revId )
4016 array( 'ORDER BY' => 'rev_id' )
4019 if ( $revId === false ) {
4022 return intval( $revId );
4027 * Get the first revision of the page
4029 * @param $flags Int Title::GAID_FOR_UPDATE
4030 * @return Revision|Null if page doesn't exist
4032 public function getFirstRevision( $flags = 0 ) {
4033 $pageId = $this->getArticleID( $flags );
4035 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4036 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4037 array( 'rev_page' => $pageId ),
4039 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4042 return new Revision( $row );
4049 * Get the oldest revision timestamp of this page
4051 * @param $flags Int Title::GAID_FOR_UPDATE
4052 * @return String: MW timestamp
4054 public function getEarliestRevTime( $flags = 0 ) {
4055 $rev = $this->getFirstRevision( $flags );
4056 return $rev ?
$rev->getTimestamp() : null;
4060 * Check if this is a new page
4064 public function isNewPage() {
4065 $dbr = wfGetDB( DB_SLAVE
);
4066 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4070 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4074 public function isBigDeletion() {
4075 global $wgDeleteRevisionsLimit;
4077 if ( !$wgDeleteRevisionsLimit ) {
4081 $revCount = $this->estimateRevisionCount();
4082 return $revCount > $wgDeleteRevisionsLimit;
4086 * Get the approximate revision count of this page.
4090 public function estimateRevisionCount() {
4091 if ( !$this->exists() ) {
4095 if ( $this->mEstimateRevisions
=== null ) {
4096 $dbr = wfGetDB( DB_SLAVE
);
4097 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4098 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4101 return $this->mEstimateRevisions
;
4105 * Get the number of revisions between the given revision.
4106 * Used for diffs and other things that really need it.
4108 * @param $old int|Revision Old revision or rev ID (first before range)
4109 * @param $new int|Revision New revision or rev ID (first after range)
4110 * @return Int Number of revisions between these revisions.
4112 public function countRevisionsBetween( $old, $new ) {
4113 if ( !( $old instanceof Revision
) ) {
4114 $old = Revision
::newFromTitle( $this, (int)$old );
4116 if ( !( $new instanceof Revision
) ) {
4117 $new = Revision
::newFromTitle( $this, (int)$new );
4119 if ( !$old ||
!$new ) {
4120 return 0; // nothing to compare
4122 $dbr = wfGetDB( DB_SLAVE
);
4123 return (int)$dbr->selectField( 'revision', 'count(*)',
4125 'rev_page' => $this->getArticleID(),
4126 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4127 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4134 * Get the number of authors between the given revision IDs.
4135 * Used for diffs and other things that really need it.
4137 * @param $old int|Revision Old revision or rev ID (first before range)
4138 * @param $new int|Revision New revision or rev ID (first after range)
4139 * @param $limit Int Maximum number of authors
4140 * @return Int Number of revision authors between these revisions.
4142 public function countAuthorsBetween( $old, $new, $limit ) {
4143 if ( !( $old instanceof Revision
) ) {
4144 $old = Revision
::newFromTitle( $this, (int)$old );
4146 if ( !( $new instanceof Revision
) ) {
4147 $new = Revision
::newFromTitle( $this, (int)$new );
4149 if ( !$old ||
!$new ) {
4150 return 0; // nothing to compare
4152 $dbr = wfGetDB( DB_SLAVE
);
4153 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4155 'rev_page' => $this->getArticleID(),
4156 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4157 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4159 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4161 return (int)$dbr->numRows( $res );
4165 * Compare with another title.
4167 * @param $title Title
4170 public function equals( Title
$title ) {
4171 // Note: === is necessary for proper matching of number-like titles.
4172 return $this->getInterwiki() === $title->getInterwiki()
4173 && $this->getNamespace() == $title->getNamespace()
4174 && $this->getDBkey() === $title->getDBkey();
4178 * Check if this title is a subpage of another title
4180 * @param $title Title
4183 public function isSubpageOf( Title
$title ) {
4184 return $this->getInterwiki() === $title->getInterwiki()
4185 && $this->getNamespace() == $title->getNamespace()
4186 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4190 * Check if page exists. For historical reasons, this function simply
4191 * checks for the existence of the title in the page table, and will
4192 * thus return false for interwiki links, special pages and the like.
4193 * If you want to know if a title can be meaningfully viewed, you should
4194 * probably call the isKnown() method instead.
4198 public function exists() {
4199 return $this->getArticleID() != 0;
4203 * Should links to this title be shown as potentially viewable (i.e. as
4204 * "bluelinks"), even if there's no record by this title in the page
4207 * This function is semi-deprecated for public use, as well as somewhat
4208 * misleadingly named. You probably just want to call isKnown(), which
4209 * calls this function internally.
4211 * (ISSUE: Most of these checks are cheap, but the file existence check
4212 * can potentially be quite expensive. Including it here fixes a lot of
4213 * existing code, but we might want to add an optional parameter to skip
4214 * it and any other expensive checks.)
4218 public function isAlwaysKnown() {
4222 * Allows overriding default behaviour for determining if a page exists.
4223 * If $isKnown is kept as null, regular checks happen. If it's
4224 * a boolean, this value is returned by the isKnown method.
4228 * @param Title $title
4229 * @param boolean|null $isKnown
4231 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4233 if ( !is_null( $isKnown ) ) {
4237 if ( $this->mInterwiki
!= '' ) {
4238 return true; // any interwiki link might be viewable, for all we know
4241 switch( $this->mNamespace
) {
4244 // file exists, possibly in a foreign repo
4245 return (bool)wfFindFile( $this );
4247 // valid special page
4248 return SpecialPageFactory
::exists( $this->getDBkey() );
4250 // selflink, possibly with fragment
4251 return $this->mDbkeyform
== '';
4253 // known system message
4254 return $this->hasSourceText() !== false;
4261 * Does this title refer to a page that can (or might) be meaningfully
4262 * viewed? In particular, this function may be used to determine if
4263 * links to the title should be rendered as "bluelinks" (as opposed to
4264 * "redlinks" to non-existent pages).
4265 * Adding something else to this function will cause inconsistency
4266 * since LinkHolderArray calls isAlwaysKnown() and does its own
4267 * page existence check.
4271 public function isKnown() {
4272 return $this->isAlwaysKnown() ||
$this->exists();
4276 * Does this page have source text?
4280 public function hasSourceText() {
4281 if ( $this->exists() ) {
4285 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4286 // If the page doesn't exist but is a known system message, default
4287 // message content will be displayed, same for language subpages-
4288 // Use always content language to avoid loading hundreds of languages
4289 // to get the link color.
4291 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4292 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4293 return $message->exists();
4300 * Get the default message text or false if the message doesn't exist
4302 * @return String or false
4304 public function getDefaultMessageText() {
4307 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4311 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4312 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4314 if ( $message->exists() ) {
4315 return $message->plain();
4322 * Updates page_touched for this page; called from LinksUpdate.php
4324 * @return Bool true if the update succeded
4326 public function invalidateCache() {
4327 if ( wfReadOnly() ) {
4330 $dbw = wfGetDB( DB_MASTER
);
4331 $success = $dbw->update(
4333 array( 'page_touched' => $dbw->timestamp() ),
4337 HTMLFileCache
::clearFileCache( $this );
4342 * Update page_touched timestamps and send squid purge messages for
4343 * pages linking to this title. May be sent to the job queue depending
4344 * on the number of links. Typically called on create and delete.
4346 public function touchLinks() {
4347 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4350 if ( $this->getNamespace() == NS_CATEGORY
) {
4351 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4357 * Get the last touched timestamp
4359 * @param $db DatabaseBase: optional db
4360 * @return String last-touched timestamp
4362 public function getTouched( $db = null ) {
4363 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4364 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4369 * Get the timestamp when this page was updated since the user last saw it.
4372 * @return String|Null
4374 public function getNotificationTimestamp( $user = null ) {
4375 global $wgUser, $wgShowUpdatedMarker;
4376 // Assume current user if none given
4380 // Check cache first
4381 $uid = $user->getId();
4382 // avoid isset here, as it'll return false for null entries
4383 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4384 return $this->mNotificationTimestamp
[$uid];
4386 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4387 return $this->mNotificationTimestamp
[$uid] = false;
4389 // Don't cache too much!
4390 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4391 $this->mNotificationTimestamp
= array();
4393 $dbr = wfGetDB( DB_SLAVE
);
4394 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4395 'wl_notificationtimestamp',
4397 'wl_user' => $user->getId(),
4398 'wl_namespace' => $this->getNamespace(),
4399 'wl_title' => $this->getDBkey(),
4403 return $this->mNotificationTimestamp
[$uid];
4407 * Generate strings used for xml 'id' names in monobook tabs
4409 * @param $prepend string defaults to 'nstab-'
4410 * @return String XML 'id' name
4412 public function getNamespaceKey( $prepend = 'nstab-' ) {
4414 // Gets the subject namespace if this title
4415 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4416 // Checks if cononical namespace name exists for namespace
4417 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4418 // Uses canonical namespace name
4419 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4421 // Uses text of namespace
4422 $namespaceKey = $this->getSubjectNsText();
4424 // Makes namespace key lowercase
4425 $namespaceKey = $wgContLang->lc( $namespaceKey );
4427 if ( $namespaceKey == '' ) {
4428 $namespaceKey = 'main';
4430 // Changes file to image for backwards compatibility
4431 if ( $namespaceKey == 'file' ) {
4432 $namespaceKey = 'image';
4434 return $prepend . $namespaceKey;
4438 * Get all extant redirects to this Title
4440 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4441 * @return Array of Title redirects to this title
4443 public function getRedirectsHere( $ns = null ) {
4446 $dbr = wfGetDB( DB_SLAVE
);
4448 'rd_namespace' => $this->getNamespace(),
4449 'rd_title' => $this->getDBkey(),
4452 if ( !is_null( $ns ) ) {
4453 $where['page_namespace'] = $ns;
4456 $res = $dbr->select(
4457 array( 'redirect', 'page' ),
4458 array( 'page_namespace', 'page_title' ),
4463 foreach ( $res as $row ) {
4464 $redirs[] = self
::newFromRow( $row );
4470 * Check if this Title is a valid redirect target
4474 public function isValidRedirectTarget() {
4475 global $wgInvalidRedirectTargets;
4477 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4478 if ( $this->isSpecial( 'Userlogout' ) ) {
4482 foreach ( $wgInvalidRedirectTargets as $target ) {
4483 if ( $this->isSpecial( $target ) ) {
4492 * Get a backlink cache object
4494 * @return BacklinkCache
4496 function getBacklinkCache() {
4497 if ( is_null( $this->mBacklinkCache
) ) {
4498 $this->mBacklinkCache
= new BacklinkCache( $this );
4500 return $this->mBacklinkCache
;
4504 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4508 public function canUseNoindex() {
4509 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4511 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4512 ?
$wgContentNamespaces
4513 : $wgExemptFromUserRobotsControl;
4515 return !in_array( $this->mNamespace
, $bannedNamespaces );
4520 * Returns the raw sort key to be used for categories, with the specified
4521 * prefix. This will be fed to Collation::getSortKey() to get a
4522 * binary sortkey that can be used for actual sorting.
4524 * @param $prefix string The prefix to be used, specified using
4525 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4529 public function getCategorySortkey( $prefix = '' ) {
4530 $unprefixed = $this->getText();
4532 // Anything that uses this hook should only depend
4533 // on the Title object passed in, and should probably
4534 // tell the users to run updateCollations.php --force
4535 // in order to re-sort existing category relations.
4536 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4537 if ( $prefix !== '' ) {
4538 # Separate with a line feed, so the unprefixed part is only used as
4539 # a tiebreaker when two pages have the exact same prefix.
4540 # In UCA, tab is the only character that can sort above LF
4541 # so we strip both of them from the original prefix.
4542 $prefix = strtr( $prefix, "\n\t", ' ' );
4543 return "$prefix\n$unprefixed";
4549 * Get the language in which the content of this page is written.
4550 * Defaults to $wgContLang, but in certain cases it can be e.g.
4551 * $wgLang (such as special pages, which are in the user language).
4556 public function getPageLanguage() {
4558 if ( $this->isSpecialPage() ) {
4559 // special pages are in the user language
4561 } elseif ( $this->isCssOrJsPage() ||
$this->isCssJsSubpage() ) {
4562 // css/js should always be LTR and is, in fact, English
4563 return wfGetLangObj( 'en' );
4564 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4565 // Parse mediawiki messages with correct target language
4566 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4567 return wfGetLangObj( $lang );
4570 // If nothing special, it should be in the wiki content language
4571 $pageLang = $wgContLang;
4572 // Hook at the end because we don't want to override the above stuff
4573 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4574 return wfGetLangObj( $pageLang );