8 * Represents a title within MediaWiki.
9 * Optionally may contain an interwiki designation or namespace.
10 * @note This class can fetch various kinds of data from the database;
11 * however, it does so inefficiently.
13 * @internal documentation reviewed 15 Mar 2010
16 /** @name Static cache variables */
18 static private $titleCache = array();
22 * Title::newFromText maintains a cache to avoid expensive re-normalization of
23 * commonly used titles. On a batch operation this can become a memory leak
24 * if not bounded. After hitting this many titles reset the cache.
26 const CACHE_MAX
= 1000;
29 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
30 * to use the master DB
32 const GAID_FOR_UPDATE
= 1;
36 * @name Private member variables
37 * Please use the accessor functions instead.
42 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
43 var $mUrlform = ''; // /< URL-encoded form of the main part
44 var $mDbkeyform = ''; // /< Main part with underscores
45 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
46 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
47 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
48 var $mFragment; // /< Title fragment (i.e. the bit after the #)
49 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
50 var $mLatestID = false; // /< ID of most recent revision
51 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
52 var $mOldRestrictions = false;
53 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
54 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
55 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
56 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
57 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
58 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
59 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
60 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
61 # Don't change the following default, NS_MAIN is hardcoded in several
62 # places. See bug 696.
63 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
64 # Zero except in {{transclusion}} tags
65 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
66 var $mLength = -1; // /< The page length, 0 for special pages
67 var $mRedirect = null; // /< Is the article at this title a redirect?
68 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
69 var $mBacklinkCache = null; // /< Cache of links to this title
77 /*protected*/ function __construct() { }
80 * Create a new Title from a prefixed DB key
82 * @param $key String the database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return Title, or NULL on an error
87 public static function newFromDBkey( $key ) {
89 $t->mDbkeyform
= $key;
90 if ( $t->secureAndSplit() ) {
98 * Create a new Title from text, such as what one would find in a link. De-
99 * codes any HTML entities in the text.
101 * @param $text String the link text; spaces, prefixes, and an
102 * initial ':' indicating the main namespace are accepted.
103 * @param $defaultNamespace Int the namespace to use if none is speci-
104 * fied by a prefix. If you want to force a specific namespace even if
105 * $text might begin with a namespace prefix, use makeTitle() or
107 * @return Title, or null on an error.
109 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
110 if ( is_object( $text ) ) {
111 throw new MWException( 'Title::newFromText given an object' );
115 * Wiki pages often contain multiple links to the same page.
116 * Title normalization and parsing can become expensive on
117 * pages with many links, so we can save a little time by
120 * In theory these are value objects and won't get changed...
122 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
123 return Title
::$titleCache[$text];
126 # Convert things like é ā or 〗 into normalized (bug 14952) text
127 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
130 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
131 $t->mDefaultNamespace
= $defaultNamespace;
133 static $cachedcount = 0 ;
134 if ( $t->secureAndSplit() ) {
135 if ( $defaultNamespace == NS_MAIN
) {
136 if ( $cachedcount >= self
::CACHE_MAX
) {
137 # Avoid memory leaks on mass operations...
138 Title
::$titleCache = array();
142 Title
::$titleCache[$text] =& $t;
152 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
154 * Example of wrong and broken code:
155 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
157 * Example of right code:
158 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
160 * Create a new Title from URL-encoded text. Ensures that
161 * the given title's length does not exceed the maximum.
163 * @param $url String the title, as might be taken from a URL
164 * @return Title the new object, or NULL on an error
166 public static function newFromURL( $url ) {
167 global $wgLegalTitleChars;
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
177 $t->mDbkeyform
= str_replace( ' ', '_', $url );
178 if ( $t->secureAndSplit() ) {
186 * Create a new Title from an article ID
188 * @param $id Int the page_id corresponding to the Title to create
189 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
190 * @return Title the new object, or NULL on an error
192 public static function newFromID( $id, $flags = 0 ) {
193 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
194 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
195 if ( $row !== false ) {
196 $title = Title
::newFromRow( $row );
204 * Make an array of titles from an array of IDs
206 * @param $ids Array of Int Array of IDs
207 * @return Array of Titles
209 public static function newFromIDs( $ids ) {
210 if ( !count( $ids ) ) {
213 $dbr = wfGetDB( DB_SLAVE
);
218 'page_namespace', 'page_title', 'page_id',
219 'page_len', 'page_is_redirect', 'page_latest',
221 array( 'page_id' => $ids ),
226 foreach ( $res as $row ) {
227 $titles[] = Title
::newFromRow( $row );
233 * Make a Title object from a DB row
235 * @param $row Object database row (needs at least page_title,page_namespace)
236 * @return Title corresponding Title
238 public static function newFromRow( $row ) {
239 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
241 $t->mArticleID
= isset( $row->page_id
) ?
intval( $row->page_id
) : -1;
242 $t->mLength
= isset( $row->page_len
) ?
intval( $row->page_len
) : -1;
243 $t->mRedirect
= isset( $row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
244 $t->mLatestID
= isset( $row->page_latest
) ?
intval( $row->page_latest
) : false;
250 * Create a new Title from a namespace index and a DB key.
251 * It's assumed that $ns and $title are *valid*, for instance when
252 * they came directly from the database or a special page name.
253 * For convenience, spaces are converted to underscores so that
254 * eg user_text fields can be used directly.
256 * @param $ns Int the namespace of the article
257 * @param $title String the unprefixed database key form
258 * @param $fragment String the link fragment (after the "#")
259 * @param $interwiki String the interwiki prefix
260 * @return Title the new object
262 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
264 $t->mInterwiki
= $interwiki;
265 $t->mFragment
= $fragment;
266 $t->mNamespace
= $ns = intval( $ns );
267 $t->mDbkeyform
= str_replace( ' ', '_', $title );
268 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
269 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
270 $t->mTextform
= str_replace( '_', ' ', $title );
275 * Create a new Title from a namespace index and a DB key.
276 * The parameters will be checked for validity, which is a bit slower
277 * than makeTitle() but safer for user-provided data.
279 * @param $ns Int the namespace of the article
280 * @param $title String database key form
281 * @param $fragment String the link fragment (after the "#")
282 * @param $interwiki String interwiki prefix
283 * @return Title the new object, or NULL on an error
285 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
287 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
288 if ( $t->secureAndSplit() ) {
296 * Create a new Title for the Main Page
298 * @return Title the new object
300 public static function newMainPage() {
301 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
302 // Don't give fatal errors if the message is broken
304 $title = Title
::newFromText( 'Main Page' );
310 * Extract a redirect destination from a string and return the
311 * Title, or null if the text doesn't contain a valid redirect
312 * This will only return the very next target, useful for
313 * the redirect table and other checks that don't need full recursion
315 * @param $text String: Text with possible redirect
316 * @return Title: The corresponding Title
318 public static function newFromRedirect( $text ) {
319 return self
::newFromRedirectInternal( $text );
323 * Extract a redirect destination from a string and return the
324 * Title, or null if the text doesn't contain a valid redirect
325 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
326 * in order to provide (hopefully) the Title of the final destination instead of another redirect
328 * @param $text String Text with possible redirect
331 public static function newFromRedirectRecurse( $text ) {
332 $titles = self
::newFromRedirectArray( $text );
333 return $titles ?
array_pop( $titles ) : null;
337 * Extract a redirect destination from a string and return an
338 * array of Titles, or null if the text doesn't contain a valid redirect
339 * The last element in the array is the final destination after all redirects
340 * have been resolved (up to $wgMaxRedirects times)
342 * @param $text String Text with possible redirect
343 * @return Array of Titles, with the destination last
345 public static function newFromRedirectArray( $text ) {
346 global $wgMaxRedirects;
347 $title = self
::newFromRedirectInternal( $text );
348 if ( is_null( $title ) ) {
351 // recursive check to follow double redirects
352 $recurse = $wgMaxRedirects;
353 $titles = array( $title );
354 while ( --$recurse > 0 ) {
355 if ( $title->isRedirect() ) {
356 $article = new Article( $title, 0 );
357 $newtitle = $article->getRedirectTarget();
361 // Redirects to some special pages are not permitted
362 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
363 // the new title passes the checks, so make that our current title so that further recursion can be checked
365 $titles[] = $newtitle;
374 * Really extract the redirect destination
375 * Do not call this function directly, use one of the newFromRedirect* functions above
377 * @param $text String Text with possible redirect
380 protected static function newFromRedirectInternal( $text ) {
381 global $wgMaxRedirects;
382 if ( $wgMaxRedirects < 1 ) {
383 //redirects are disabled, so quit early
386 $redir = MagicWord
::get( 'redirect' );
387 $text = trim( $text );
388 if ( $redir->matchStartAndRemove( $text ) ) {
389 // Extract the first link and see if it's usable
390 // Ensure that it really does come directly after #REDIRECT
391 // Some older redirects included a colon, so don't freak about that!
393 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
394 // Strip preceding colon used to "escape" categories, etc.
395 // and URL-decode links
396 if ( strpos( $m[1], '%' ) !== false ) {
397 // Match behavior of inline link parsing here;
398 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
400 $title = Title
::newFromText( $m[1] );
401 // If the title is a redirect to bad special pages or is invalid, return null
402 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
411 # ----------------------------------------------------------------------------
413 # ----------------------------------------------------------------------------
416 * Get the prefixed DB key associated with an ID
418 * @param $id Int the page_id of the article
419 * @return Title an object representing the article, or NULL if no such article was found
421 public static function nameOf( $id ) {
422 $dbr = wfGetDB( DB_SLAVE
);
424 $s = $dbr->selectRow(
426 array( 'page_namespace', 'page_title' ),
427 array( 'page_id' => $id ),
430 if ( $s === false ) {
434 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
439 * Get a regex character class describing the legal characters in a link
441 * @return String the list of characters, not delimited
443 public static function legalChars() {
444 global $wgLegalTitleChars;
445 return $wgLegalTitleChars;
449 * Get a string representation of a title suitable for
450 * including in a search index
452 * @param $ns Int a namespace index
453 * @param $title String text-form main part
454 * @return String a stripped-down title string ready for the search index
456 public static function indexTitle( $ns, $title ) {
459 $lc = SearchEngine
::legalSearchChars() . '&#;';
460 $t = $wgContLang->normalizeForSearch( $title );
461 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
462 $t = $wgContLang->lc( $t );
465 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
466 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
468 $t = preg_replace( "/\\s+/", ' ', $t );
470 if ( $ns == NS_FILE
) {
471 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
477 * Make a prefixed DB key from a DB key and a namespace index
479 * @param $ns Int numerical representation of the namespace
480 * @param $title String the DB key form the title
481 * @param $fragment String The link fragment (after the "#")
482 * @param $interwiki String The interwiki prefix
483 * @return String the prefixed form of the title
485 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
488 $namespace = $wgContLang->getNsText( $ns );
489 $name = $namespace == '' ?
$title : "$namespace:$title";
490 if ( strval( $interwiki ) != '' ) {
491 $name = "$interwiki:$name";
493 if ( strval( $fragment ) != '' ) {
494 $name .= '#' . $fragment;
500 * Determine whether the object refers to a page within
503 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
505 public function isLocal() {
506 if ( $this->mInterwiki
!= '' ) {
507 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
514 * Determine whether the object refers to a page within
515 * this project and is transcludable.
517 * @return Bool TRUE if this is transcludable
519 public function isTrans() {
520 if ( $this->mInterwiki
== '' ) {
524 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
528 * Returns the DB name of the distant wiki which owns the object.
530 * @return String the DB name
532 public function getTransWikiID() {
533 if ( $this->mInterwiki
== '' ) {
537 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
541 * Escape a text fragment, say from a link, for a URL
543 * @param $fragment string containing a URL or link fragment (after the "#")
544 * @return String: escaped string
546 static function escapeFragmentForURL( $fragment ) {
547 # Note that we don't urlencode the fragment. urlencoded Unicode
548 # fragments appear not to work in IE (at least up to 7) or in at least
549 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
550 # to care if they aren't encoded.
551 return Sanitizer
::escapeId( $fragment, 'noninitial' );
554 # ----------------------------------------------------------------------------
556 # ----------------------------------------------------------------------------
558 /** Simple accessors */
560 * Get the text form (spaces not underscores) of the main part
562 * @return String Main part of the title
564 public function getText() { return $this->mTextform
; }
567 * Get the URL-encoded form of the main part
569 * @return String Main part of the title, URL-encoded
571 public function getPartialURL() { return $this->mUrlform
; }
574 * Get the main part with underscores
576 * @return String: Main part of the title, with underscores
578 public function getDBkey() { return $this->mDbkeyform
; }
581 * Get the namespace index, i.e. one of the NS_xxxx constants.
583 * @return Integer: Namespace index
585 public function getNamespace() { return $this->mNamespace
; }
588 * Get the namespace text
590 * @return String: Namespace text
592 public function getNsText() {
595 if ( $this->mInterwiki
!= '' ) {
596 // This probably shouldn't even happen. ohh man, oh yuck.
597 // But for interwiki transclusion it sometimes does.
598 // Shit. Shit shit shit.
600 // Use the canonical namespaces if possible to try to
601 // resolve a foreign namespace.
602 if ( MWNamespace
::exists( $this->mNamespace
) ) {
603 return MWNamespace
::getCanonicalName( $this->mNamespace
);
607 if ( $wgContLang->needsGenderDistinction() &&
608 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
609 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
610 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
613 return $wgContLang->getNsText( $this->mNamespace
);
617 * Get the DB key with the initial letter case as specified by the user
619 * @return String DB key
621 function getUserCaseDBKey() {
622 return $this->mUserCaseDBKey
;
626 * Get the namespace text of the subject (rather than talk) page
628 * @return String Namespace text
630 public function getSubjectNsText() {
632 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
636 * Get the namespace text of the talk page
638 * @return String Namespace text
640 public function getTalkNsText() {
642 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
646 * Could this title have a corresponding talk page?
648 * @return Bool TRUE or FALSE
650 public function canTalk() {
651 return( MWNamespace
::canTalk( $this->mNamespace
) );
655 * Get the interwiki prefix (or null string)
657 * @return String Interwiki prefix
659 public function getInterwiki() { return $this->mInterwiki
; }
662 * Get the Title fragment (i.e.\ the bit after the #) in text form
664 * @return String Title fragment
666 public function getFragment() { return $this->mFragment
; }
669 * Get the fragment in URL form, including the "#" character if there is one
670 * @return String Fragment in URL form
672 public function getFragmentForURL() {
673 if ( $this->mFragment
== '' ) {
676 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
681 * Get the default namespace index, for when there is no namespace
683 * @return Int Default namespace index
685 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
688 * Get title for search index
690 * @return String a stripped-down title string ready for the
693 public function getIndexTitle() {
694 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
698 * Get the prefixed database key form
700 * @return String the prefixed title, with underscores and
701 * any interwiki and namespace prefixes
703 public function getPrefixedDBkey() {
704 $s = $this->prefix( $this->mDbkeyform
);
705 $s = str_replace( ' ', '_', $s );
710 * Get the prefixed title with spaces.
711 * This is the form usually used for display
713 * @return String the prefixed title, with spaces
715 public function getPrefixedText() {
716 // @todo FIXME: Bad usage of empty() ?
717 if ( empty( $this->mPrefixedText
) ) {
718 $s = $this->prefix( $this->mTextform
);
719 $s = str_replace( '_', ' ', $s );
720 $this->mPrefixedText
= $s;
722 return $this->mPrefixedText
;
726 * Get the prefixed title with spaces, plus any fragment
727 * (part beginning with '#')
729 * @return String the prefixed title, with spaces and the fragment, including '#'
731 public function getFullText() {
732 $text = $this->getPrefixedText();
733 if ( $this->mFragment
!= '' ) {
734 $text .= '#' . $this->mFragment
;
740 * Get the base name, i.e. the leftmost parts before the /
742 * @return String Base name
744 public function getBaseText() {
745 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
746 return $this->getText();
749 $parts = explode( '/', $this->getText() );
750 # Don't discard the real title if there's no subpage involved
751 if ( count( $parts ) > 1 ) {
752 unset( $parts[count( $parts ) - 1] );
754 return implode( '/', $parts );
758 * Get the lowest-level subpage name, i.e. the rightmost part after /
760 * @return String Subpage name
762 public function getSubpageText() {
763 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
764 return( $this->mTextform
);
766 $parts = explode( '/', $this->mTextform
);
767 return( $parts[count( $parts ) - 1] );
771 * Get a URL-encoded form of the subpage text
773 * @return String URL-encoded subpage name
775 public function getSubpageUrlForm() {
776 $text = $this->getSubpageText();
777 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
782 * Get a URL-encoded title (not an actual URL) including interwiki
784 * @return String the URL-encoded form
786 public function getPrefixedURL() {
787 $s = $this->prefix( $this->mDbkeyform
);
788 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
793 * Get a real URL referring to this title, with interwiki link and
796 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
797 * links. Can be specified as an associative array as well, e.g.,
798 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
799 * @param $variant String language variant of url (for sr, zh..)
800 * @return String the URL
802 public function getFullURL( $query = '', $variant = false ) {
803 global $wgServer, $wgRequest;
805 if ( is_array( $query ) ) {
806 $query = wfArrayToCGI( $query );
809 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
811 $url = $this->getLocalURL( $query, $variant );
813 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
814 // Correct fix would be to move the prepending elsewhere.
815 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
816 $url = $wgServer . $url;
819 $baseUrl = $interwiki->getURL();
821 $namespace = wfUrlencode( $this->getNsText() );
822 if ( $namespace != '' ) {
823 # Can this actually happen? Interwikis shouldn't be parsed.
824 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
827 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
828 $url = wfAppendQuery( $url, $query );
831 # Finally, add the fragment.
832 $url .= $this->getFragmentForURL();
834 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
839 * Get a URL with no fragment or server name. If this page is generated
840 * with action=render, $wgServer is prepended.
842 * @param $query Mixed: an optional query string; if not specified,
843 * $wgArticlePath will be used. Can be specified as an associative array
844 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
846 * @param $variant String language variant of url (for sr, zh..)
847 * @return String the URL
849 public function getLocalURL( $query = '', $variant = false ) {
850 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
851 global $wgVariantArticlePath, $wgContLang;
853 if ( is_array( $query ) ) {
854 $query = wfArrayToCGI( $query );
857 if ( $this->isExternal() ) {
858 $url = $this->getFullURL();
860 // This is currently only used for edit section links in the
861 // context of interwiki transclusion. In theory we should
862 // append the query to the end of any existing query string,
863 // but interwiki transclusion is already broken in that case.
867 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
868 if ( $query == '' ) {
869 if ( $variant != false && $wgContLang->hasVariants() ) {
870 if ( !$wgVariantArticlePath ) {
871 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
873 $variantArticlePath = $wgVariantArticlePath;
875 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
876 $url = str_replace( '$1', $dbkey, $url );
878 $url = str_replace( '$1', $dbkey, $wgArticlePath );
881 global $wgActionPaths;
884 if ( !empty( $wgActionPaths ) &&
885 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
887 $action = urldecode( $matches[2] );
888 if ( isset( $wgActionPaths[$action] ) ) {
889 $query = $matches[1];
890 if ( isset( $matches[4] ) ) {
891 $query .= $matches[4];
893 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
894 if ( $query != '' ) {
895 $url = wfAppendQuery( $url, $query );
900 if ( $url === false ) {
901 if ( $query == '-' ) {
904 $url = "{$wgScript}?title={$dbkey}&{$query}";
908 // @todo FIXME: This causes breakage in various places when we
909 // actually expected a local URL and end up with dupe prefixes.
910 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
911 $url = $wgServer . $url;
914 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
919 * Get a URL that's the simplest URL that will be valid to link, locally,
920 * to the current Title. It includes the fragment, but does not include
921 * the server unless action=render is used (or the link is external). If
922 * there's a fragment but the prefixed text is empty, we just return a link
925 * The result obviously should not be URL-escaped, but does need to be
926 * HTML-escaped if it's being output in HTML.
928 * @param $query Array of Strings An associative array of key => value pairs for the
929 * query string. Keys and values will be escaped.
930 * @param $variant String language variant of URL (for sr, zh..). Ignored
931 * for external links. Default is "false" (same variant as current page,
932 * for anonymous users).
933 * @return String the URL
935 public function getLinkUrl( $query = array(), $variant = false ) {
936 wfProfileIn( __METHOD__
);
937 if ( $this->isExternal() ) {
938 $ret = $this->getFullURL( $query );
939 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
940 $ret = $this->getFragmentForURL();
942 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
944 wfProfileOut( __METHOD__
);
949 * Get an HTML-escaped version of the URL form, suitable for
950 * using in a link, without a server name or fragment
952 * @param $query String an optional query string
953 * @return String the URL
955 public function escapeLocalURL( $query = '' ) {
956 return htmlspecialchars( $this->getLocalURL( $query ) );
960 * Get an HTML-escaped version of the URL form, suitable for
961 * using in a link, including the server name and fragment
963 * @param $query String an optional query string
964 * @return String the URL
966 public function escapeFullURL( $query = '' ) {
967 return htmlspecialchars( $this->getFullURL( $query ) );
971 * Get the URL form for an internal link.
972 * - Used in various Squid-related code, in case we have a different
973 * internal hostname for the server from the exposed one.
975 * @param $query String an optional query string
976 * @param $variant String language variant of url (for sr, zh..)
977 * @return String the URL
979 public function getInternalURL( $query = '', $variant = false ) {
980 global $wgInternalServer, $wgServer;
981 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
982 $url = $server . $this->getLocalURL( $query, $variant );
983 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
988 * Get the edit URL for this Title
990 * @return String the URL, or a null string if this is an
993 public function getEditURL() {
994 if ( $this->mInterwiki
!= '' ) {
997 $s = $this->getLocalURL( 'action=edit' );
1003 * Get the HTML-escaped displayable text form.
1004 * Used for the title field in <a> tags.
1006 * @return String the text, including any prefixes
1008 public function getEscapedText() {
1009 return htmlspecialchars( $this->getPrefixedText() );
1013 * Is this Title interwiki?
1017 public function isExternal() {
1018 return ( $this->mInterwiki
!= '' );
1022 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1024 * @param $action String Action to check (default: edit)
1027 public function isSemiProtected( $action = 'edit' ) {
1028 if ( $this->exists() ) {
1029 $restrictions = $this->getRestrictions( $action );
1030 if ( count( $restrictions ) > 0 ) {
1031 foreach ( $restrictions as $restriction ) {
1032 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1042 # If it doesn't exist, it can't be protected
1048 * Does the title correspond to a protected article?
1050 * @param $action String the action the page is protected from,
1051 * by default checks all actions.
1054 public function isProtected( $action = '' ) {
1055 global $wgRestrictionLevels;
1057 $restrictionTypes = $this->getRestrictionTypes();
1059 # Special pages have inherent protection
1060 if( $this->getNamespace() == NS_SPECIAL
) {
1064 # Check regular protection levels
1065 foreach ( $restrictionTypes as $type ) {
1066 if ( $action == $type ||
$action == '' ) {
1067 $r = $this->getRestrictions( $type );
1068 foreach ( $wgRestrictionLevels as $level ) {
1069 if ( in_array( $level, $r ) && $level != '' ) {
1080 * Is this a conversion table for the LanguageConverter?
1084 public function isConversionTable() {
1086 $this->getNamespace() == NS_MEDIAWIKI
&&
1087 strpos( $this->getText(), 'Conversiontable' ) !== false
1097 * Is $wgUser watching this page?
1101 public function userIsWatching() {
1104 if ( is_null( $this->mWatched
) ) {
1105 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1106 $this->mWatched
= false;
1108 $this->mWatched
= $wgUser->isWatched( $this );
1111 return $this->mWatched
;
1115 * Can $wgUser perform $action on this page?
1116 * This skips potentially expensive cascading permission checks
1117 * as well as avoids expensive error formatting
1119 * Suitable for use for nonessential UI controls in common cases, but
1120 * _not_ for functional access control.
1122 * May provide false positives, but should never provide a false negative.
1124 * @param $action String action that permission needs to be checked for
1127 public function quickUserCan( $action ) {
1128 return $this->userCan( $action, false );
1132 * Determines if $user is unable to edit this page because it has been protected
1133 * by $wgNamespaceProtection.
1135 * @param $user User object, $wgUser will be used if not passed
1138 public function isNamespaceProtected( User
$user = null ) {
1139 global $wgNamespaceProtection;
1141 if ( $user === null ) {
1146 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1147 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1148 if ( $right != '' && !$user->isAllowed( $right ) ) {
1157 * Can $wgUser perform $action on this page?
1159 * @param $action String action that permission needs to be checked for
1160 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1163 public function userCan( $action, $doExpensiveQueries = true ) {
1165 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1169 * Can $user perform $action on this page?
1171 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1173 * @param $action String action that permission needs to be checked for
1174 * @param $user User to check
1175 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1176 * skipping checks for cascading protections and user blocks.
1177 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1178 * @return Array of arguments to wfMsg to explain permissions problems.
1180 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1181 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1183 // Remove the errors being ignored.
1184 foreach ( $errors as $index => $error ) {
1185 $error_key = is_array( $error ) ?
$error[0] : $error;
1187 if ( in_array( $error_key, $ignoreErrors ) ) {
1188 unset( $errors[$index] );
1196 * Permissions checks that fail most often, and which are easiest to test.
1198 * @param $action String the action to check
1199 * @param $user User user to check
1200 * @param $errors Array list of current errors
1201 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1202 * @param $short Boolean short circuit on first error
1204 * @return Array list of errors
1206 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1207 if ( $action == 'create' ) {
1208 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1209 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1210 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1212 } elseif ( $action == 'move' ) {
1213 if ( !$user->isAllowed( 'move-rootuserpages' )
1214 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1215 // Show user page-specific message only if the user can move other pages
1216 $errors[] = array( 'cant-move-user-page' );
1219 // Check if user is allowed to move files if it's a file
1220 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1221 $errors[] = array( 'movenotallowedfile' );
1224 if ( !$user->isAllowed( 'move' ) ) {
1225 // User can't move anything
1226 global $wgGroupPermissions;
1227 $userCanMove = false;
1228 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1229 $userCanMove = $wgGroupPermissions['user']['move'];
1231 $autoconfirmedCanMove = false;
1232 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1233 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1235 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1236 // custom message if logged-in users without any special rights can move
1237 $errors[] = array( 'movenologintext' );
1239 $errors[] = array( 'movenotallowed' );
1242 } elseif ( $action == 'move-target' ) {
1243 if ( !$user->isAllowed( 'move' ) ) {
1244 // User can't move anything
1245 $errors[] = array( 'movenotallowed' );
1246 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1247 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1248 // Show user page-specific message only if the user can move other pages
1249 $errors[] = array( 'cant-move-to-user-page' );
1251 } elseif ( !$user->isAllowed( $action ) ) {
1252 // We avoid expensive display logic for quickUserCan's and such
1255 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1256 User
::getGroupsWithPermission( $action ) );
1263 $wgLang->commaList( $groups ),
1267 $return = array( 'badaccess-group0' );
1269 $errors[] = $return;
1276 * Add the resulting error code to the errors array
1278 * @param $errors Array list of current errors
1279 * @param $result Mixed result of errors
1281 * @return Array list of errors
1283 private function resultToError( $errors, $result ) {
1284 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1285 // A single array representing an error
1286 $errors[] = $result;
1287 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1288 // A nested array representing multiple errors
1289 $errors = array_merge( $errors, $result );
1290 } elseif ( $result !== '' && is_string( $result ) ) {
1291 // A string representing a message-id
1292 $errors[] = array( $result );
1293 } elseif ( $result === false ) {
1294 // a generic "We don't want them to do that"
1295 $errors[] = array( 'badaccess-group0' );
1301 * Check various permission hooks
1303 * @param $action String the action to check
1304 * @param $user User user to check
1305 * @param $errors Array list of current errors
1306 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1307 * @param $short Boolean short circuit on first error
1309 * @return Array list of errors
1311 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1312 // Use getUserPermissionsErrors instead
1314 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1315 return $result ?
array() : array( array( 'badaccess-group0' ) );
1317 // Check getUserPermissionsErrors hook
1318 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1319 $errors = $this->resultToError( $errors, $result );
1321 // Check getUserPermissionsErrorsExpensive hook
1322 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1323 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1324 $errors = $this->resultToError( $errors, $result );
1331 * Check permissions on special pages & namespaces
1333 * @param $action String the action to check
1334 * @param $user User user to check
1335 * @param $errors Array list of current errors
1336 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1337 * @param $short Boolean short circuit on first error
1339 * @return Array list of errors
1341 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1342 # Only 'createaccount' and 'execute' can be performed on
1343 # special pages, which don't actually exist in the DB.
1344 $specialOKActions = array( 'createaccount', 'execute' );
1345 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1346 $errors[] = array( 'ns-specialprotected' );
1349 # Check $wgNamespaceProtection for restricted namespaces
1350 if ( $this->isNamespaceProtected( $user ) ) {
1351 $ns = $this->mNamespace
== NS_MAIN ?
1352 wfMsg( 'nstab-main' ) : $this->getNsText();
1353 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1354 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1361 * Check CSS/JS sub-page permissions
1363 * @param $action String the action to check
1364 * @param $user User user to check
1365 * @param $errors Array list of current errors
1366 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1367 * @param $short Boolean short circuit on first error
1369 * @return Array list of errors
1371 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1372 # Protect css/js subpages of user pages
1373 # XXX: this might be better using restrictions
1374 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1375 # and $this->userCanEditJsSubpage() from working
1376 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1377 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1378 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1379 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1380 $errors[] = array( 'customcssprotected' );
1381 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1382 $errors[] = array( 'customjsprotected' );
1390 * Check against page_restrictions table requirements on this
1391 * page. The user must possess all required rights for this
1394 * @param $action String the action to check
1395 * @param $user User user to check
1396 * @param $errors Array list of current errors
1397 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1398 * @param $short Boolean short circuit on first error
1400 * @return Array list of errors
1402 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1403 foreach ( $this->getRestrictions( $action ) as $right ) {
1404 // Backwards compatibility, rewrite sysop -> protect
1405 if ( $right == 'sysop' ) {
1408 if ( $right != '' && !$user->isAllowed( $right ) ) {
1409 // Users with 'editprotected' permission can edit protected pages
1410 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1411 // Users with 'editprotected' permission cannot edit protected pages
1412 // with cascading option turned on.
1413 if ( $this->mCascadeRestriction
) {
1414 $errors[] = array( 'protectedpagetext', $right );
1417 $errors[] = array( 'protectedpagetext', $right );
1426 * Check restrictions on cascading pages.
1428 * @param $action String the action to check
1429 * @param $user User to check
1430 * @param $errors Array list of current errors
1431 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1432 * @param $short Boolean short circuit on first error
1434 * @return Array list of errors
1436 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1437 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1438 # We /could/ use the protection level on the source page, but it's
1439 # fairly ugly as we have to establish a precedence hierarchy for pages
1440 # included by multiple cascade-protected pages. So just restrict
1441 # it to people with 'protect' permission, as they could remove the
1442 # protection anyway.
1443 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1444 # Cascading protection depends on more than this page...
1445 # Several cascading protected pages may include this page...
1446 # Check each cascading level
1447 # This is only for protection restrictions, not for all actions
1448 if ( isset( $restrictions[$action] ) ) {
1449 foreach ( $restrictions[$action] as $right ) {
1450 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1451 if ( $right != '' && !$user->isAllowed( $right ) ) {
1453 foreach ( $cascadingSources as $page )
1454 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1455 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1465 * Check action permissions not already checked in checkQuickPermissions
1467 * @param $action String the action to check
1468 * @param $user User to check
1469 * @param $errors Array list of current errors
1470 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1471 * @param $short Boolean short circuit on first error
1473 * @return Array list of errors
1475 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1476 if ( $action == 'protect' ) {
1477 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1478 // If they can't edit, they shouldn't protect.
1479 $errors[] = array( 'protect-cantedit' );
1481 } elseif ( $action == 'create' ) {
1482 $title_protection = $this->getTitleProtection();
1483 if( $title_protection ) {
1484 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1485 $title_protection['pt_create_perm'] = 'protect'; // B/C
1487 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1488 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1491 } elseif ( $action == 'move' ) {
1492 // Check for immobile pages
1493 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1494 // Specific message for this case
1495 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1496 } elseif ( !$this->isMovable() ) {
1497 // Less specific message for rarer cases
1498 $errors[] = array( 'immobile-page' );
1500 } elseif ( $action == 'move-target' ) {
1501 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1502 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1503 } elseif ( !$this->isMovable() ) {
1504 $errors[] = array( 'immobile-target-page' );
1511 * Check that the user isn't blocked from editting.
1513 * @param $action String the action to check
1514 * @param $user User to check
1515 * @param $errors Array list of current errors
1516 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1517 * @param $short Boolean short circuit on first error
1519 * @return Array list of errors
1521 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1522 if( !$doExpensiveQueries ) {
1526 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1528 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1529 $errors[] = array( 'confirmedittext' );
1532 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1533 // Edit blocks should not affect reading.
1534 // Account creation blocks handled at userlogin.
1535 // Unblocking handled in SpecialUnblock
1536 } elseif( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1537 // Don't block the user from editing their own talk page unless they've been
1538 // explicitly blocked from that too.
1539 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1540 $block = $user->mBlock
;
1542 // This is from OutputPage::blockedPage
1543 // Copied at r23888 by werdna
1545 $id = $user->blockedBy();
1546 $reason = $user->blockedFor();
1547 if ( $reason == '' ) {
1548 $reason = wfMsg( 'blockednoreason' );
1552 if ( is_numeric( $id ) ) {
1553 $name = User
::whoIs( $id );
1558 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1559 $blockid = $block->getId();
1560 $blockExpiry = $user->mBlock
->mExpiry
;
1561 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1562 if ( $blockExpiry == 'infinity' ) {
1563 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1565 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1568 $intended = strval( $user->mBlock
->getTarget() );
1570 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1571 $blockid, $blockExpiry, $intended, $blockTimestamp );
1578 * Can $user perform $action on this page? This is an internal function,
1579 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1580 * checks on wfReadOnly() and blocks)
1582 * @param $action String action that permission needs to be checked for
1583 * @param $user User to check
1584 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1585 * @param $short Bool Set this to true to stop after the first permission error.
1586 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1588 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1589 wfProfileIn( __METHOD__
);
1593 'checkQuickPermissions',
1594 'checkPermissionHooks',
1595 'checkSpecialsAndNSPermissions',
1596 'checkCSSandJSPermissions',
1597 'checkPageRestrictions',
1598 'checkCascadingSourcesRestrictions',
1599 'checkActionPermissions',
1603 while( count( $checks ) > 0 &&
1604 !( $short && count( $errors ) > 0 ) ) {
1605 $method = array_shift( $checks );
1606 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1609 wfProfileOut( __METHOD__
);
1614 * Is this title subject to title protection?
1615 * Title protection is the one applied against creation of such title.
1617 * @return Mixed An associative array representing any existent title
1618 * protection, or false if there's none.
1620 private function getTitleProtection() {
1621 // Can't protect pages in special namespaces
1622 if ( $this->getNamespace() < 0 ) {
1626 // Can't protect pages that exist.
1627 if ( $this->exists() ) {
1631 if ( !isset( $this->mTitleProtection
) ) {
1632 $dbr = wfGetDB( DB_SLAVE
);
1633 $res = $dbr->select( 'protected_titles', '*',
1634 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1637 // fetchRow returns false if there are no rows.
1638 $this->mTitleProtection
= $dbr->fetchRow( $res );
1640 return $this->mTitleProtection
;
1644 * Update the title protection status
1646 * @param $create_perm String Permission required for creation
1647 * @param $reason String Reason for protection
1648 * @param $expiry String Expiry timestamp
1649 * @return boolean true
1651 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1652 global $wgUser, $wgContLang;
1654 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1655 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1660 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1662 $dbw = wfGetDB( DB_MASTER
);
1664 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1666 $expiry_description = '';
1667 if ( $encodedExpiry != $dbw->getInfinity() ) {
1668 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1669 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1671 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1674 # Update protection table
1675 if ( $create_perm != '' ) {
1676 $this->mTitleProtection
= array(
1677 'pt_namespace' => $namespace,
1678 'pt_title' => $title,
1679 'pt_create_perm' => $create_perm,
1680 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1681 'pt_expiry' => $encodedExpiry,
1682 'pt_user' => $wgUser->getId(),
1683 'pt_reason' => $reason,
1685 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1686 $this->mTitleProtection
, __METHOD__
);
1688 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1689 'pt_title' => $title ), __METHOD__
);
1690 $this->mTitleProtection
= false;
1693 # Update the protection log
1694 if ( $dbw->affectedRows() ) {
1695 $log = new LogPage( 'protect' );
1697 if ( $create_perm ) {
1698 $params = array( "[create=$create_perm] $expiry_description", '' );
1699 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1701 $log->addEntry( 'unprotect', $this, $reason );
1709 * Remove any title protection due to page existing
1711 public function deleteTitleProtection() {
1712 $dbw = wfGetDB( DB_MASTER
);
1716 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1719 $this->mTitleProtection
= false;
1723 * Would anybody with sufficient privileges be able to move this page?
1724 * Some pages just aren't movable.
1726 * @return Bool TRUE or FALSE
1728 public function isMovable() {
1729 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1733 * Can $wgUser read this page?
1736 * @todo fold these checks into userCan()
1738 public function userCanRead() {
1739 global $wgUser, $wgGroupPermissions;
1741 static $useShortcut = null;
1743 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1744 if ( is_null( $useShortcut ) ) {
1745 global $wgRevokePermissions;
1746 $useShortcut = true;
1747 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1748 # Not a public wiki, so no shortcut
1749 $useShortcut = false;
1750 } elseif ( !empty( $wgRevokePermissions ) ) {
1752 * Iterate through each group with permissions being revoked (key not included since we don't care
1753 * what the group name is), then check if the read permission is being revoked. If it is, then
1754 * we don't use the shortcut below since the user might not be able to read, even though anon
1755 * reading is allowed.
1757 foreach ( $wgRevokePermissions as $perms ) {
1758 if ( !empty( $perms['read'] ) ) {
1759 # We might be removing the read right from the user, so no shortcut
1760 $useShortcut = false;
1768 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1769 if ( $result !== null ) {
1773 # Shortcut for public wikis, allows skipping quite a bit of code
1774 if ( $useShortcut ) {
1778 if ( $wgUser->isAllowed( 'read' ) ) {
1781 global $wgWhitelistRead;
1783 # Always grant access to the login page.
1784 # Even anons need to be able to log in.
1785 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'ChangePassword' ) ) {
1789 # Bail out if there isn't whitelist
1790 if ( !is_array( $wgWhitelistRead ) ) {
1794 # Check for explicit whitelisting
1795 $name = $this->getPrefixedText();
1796 $dbName = $this->getPrefixedDBKey();
1797 // Check with and without underscores
1798 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1801 # Old settings might have the title prefixed with
1802 # a colon for main-namespace pages
1803 if ( $this->getNamespace() == NS_MAIN
) {
1804 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1809 # If it's a special page, ditch the subpage bit and check again
1810 if ( $this->getNamespace() == NS_SPECIAL
) {
1811 $name = $this->getDBkey();
1812 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1813 if ( $name === false ) {
1814 # Invalid special page, but we show standard login required message
1818 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1819 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1829 * Is this the mainpage?
1830 * @note Title::newFromText seams to be sufficiently optimized by the title
1831 * cache that we don't need to over-optimize by doing direct comparisons and
1832 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1833 * ends up reporting something differently than $title->isMainPage();
1837 public function isMainPage() {
1838 return $this->equals( Title
::newMainPage() );
1842 * Is this a talk page of some sort?
1846 public function isTalkPage() {
1847 return MWNamespace
::isTalk( $this->getNamespace() );
1851 * Is this a subpage?
1855 public function isSubpage() {
1856 return MWNamespace
::hasSubpages( $this->mNamespace
)
1857 ?
strpos( $this->getText(), '/' ) !== false
1862 * Does this have subpages? (Warning, usually requires an extra DB query.)
1866 public function hasSubpages() {
1867 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1872 # We dynamically add a member variable for the purpose of this method
1873 # alone to cache the result. There's no point in having it hanging
1874 # around uninitialized in every Title object; therefore we only add it
1875 # if needed and don't declare it statically.
1876 if ( isset( $this->mHasSubpages
) ) {
1877 return $this->mHasSubpages
;
1880 $subpages = $this->getSubpages( 1 );
1881 if ( $subpages instanceof TitleArray
) {
1882 return $this->mHasSubpages
= (bool)$subpages->count();
1884 return $this->mHasSubpages
= false;
1888 * Get all subpages of this page.
1890 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1891 * @return mixed TitleArray, or empty array if this page's namespace
1892 * doesn't allow subpages
1894 public function getSubpages( $limit = -1 ) {
1895 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1899 $dbr = wfGetDB( DB_SLAVE
);
1900 $conds['page_namespace'] = $this->getNamespace();
1901 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1903 if ( $limit > -1 ) {
1904 $options['LIMIT'] = $limit;
1906 return $this->mSubpages
= TitleArray
::newFromResult(
1907 $dbr->select( 'page',
1908 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1917 * Could this page contain custom CSS or JavaScript, based
1922 public function isCssOrJsPage() {
1923 return $this->mNamespace
== NS_MEDIAWIKI
1924 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1928 * Is this a .css or .js subpage of a user page?
1931 public function isCssJsSubpage() {
1932 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1936 * Is this a *valid* .css or .js subpage of a user page?
1939 * @deprecated since 1.17
1941 public function isValidCssJsSubpage() {
1942 return $this->isCssJsSubpage();
1946 * Trim down a .css or .js subpage title to get the corresponding skin name
1948 * @return string containing skin name from .css or .js subpage title
1950 public function getSkinFromCssJsSubpage() {
1951 $subpage = explode( '/', $this->mTextform
);
1952 $subpage = $subpage[ count( $subpage ) - 1 ];
1953 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1957 * Is this a .css subpage of a user page?
1961 public function isCssSubpage() {
1962 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1966 * Is this a .js subpage of a user page?
1970 public function isJsSubpage() {
1971 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1975 * Protect css subpages of user pages: can $wgUser edit
1979 * @todo XXX: this might be better using restrictions
1981 public function userCanEditCssSubpage() {
1983 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1984 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1988 * Protect js subpages of user pages: can $wgUser edit
1992 * @todo XXX: this might be better using restrictions
1994 public function userCanEditJsSubpage() {
1996 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
1997 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2001 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2003 * @return Bool If the page is subject to cascading restrictions.
2005 public function isCascadeProtected() {
2006 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2007 return ( $sources > 0 );
2011 * Cascading protection: Get the source of any cascading restrictions on this page.
2013 * @param $getPages Bool Whether or not to retrieve the actual pages
2014 * that the restrictions have come from.
2015 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2016 * have come, false for none, or true if such restrictions exist, but $getPages
2017 * was not set. The restriction array is an array of each type, each of which
2018 * contains a array of unique groups.
2020 public function getCascadeProtectionSources( $getPages = true ) {
2022 $pagerestrictions = array();
2024 if ( isset( $this->mCascadeSources
) && $getPages ) {
2025 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2026 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2027 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2030 wfProfileIn( __METHOD__
);
2032 $dbr = wfGetDB( DB_SLAVE
);
2034 if ( $this->getNamespace() == NS_FILE
) {
2035 $tables = array( 'imagelinks', 'page_restrictions' );
2036 $where_clauses = array(
2037 'il_to' => $this->getDBkey(),
2042 $tables = array( 'templatelinks', 'page_restrictions' );
2043 $where_clauses = array(
2044 'tl_namespace' => $this->getNamespace(),
2045 'tl_title' => $this->getDBkey(),
2052 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2053 'pr_expiry', 'pr_type', 'pr_level' );
2054 $where_clauses[] = 'page_id=pr_page';
2057 $cols = array( 'pr_expiry' );
2060 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2062 $sources = $getPages ?
array() : false;
2063 $now = wfTimestampNow();
2064 $purgeExpired = false;
2066 foreach ( $res as $row ) {
2067 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2068 if ( $expiry > $now ) {
2070 $page_id = $row->pr_page
;
2071 $page_ns = $row->page_namespace
;
2072 $page_title = $row->page_title
;
2073 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2074 # Add groups needed for each restriction type if its not already there
2075 # Make sure this restriction type still exists
2077 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2078 $pagerestrictions[$row->pr_type
] = array();
2081 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2082 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2083 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2089 // Trigger lazy purge of expired restrictions from the db
2090 $purgeExpired = true;
2093 if ( $purgeExpired ) {
2094 Title
::purgeExpiredRestrictions();
2098 $this->mCascadeSources
= $sources;
2099 $this->mCascadingRestrictions
= $pagerestrictions;
2101 $this->mHasCascadingRestrictions
= $sources;
2104 wfProfileOut( __METHOD__
);
2105 return array( $sources, $pagerestrictions );
2109 * Returns cascading restrictions for the current article
2113 function areRestrictionsCascading() {
2114 if ( !$this->mRestrictionsLoaded
) {
2115 $this->loadRestrictions();
2118 return $this->mCascadeRestriction
;
2122 * Loads a string into mRestrictions array
2124 * @param $res Resource restrictions as an SQL result.
2125 * @param $oldFashionedRestrictions String comma-separated list of page
2126 * restrictions from page table (pre 1.10)
2128 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2131 foreach ( $res as $row ) {
2135 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2139 * Compiles list of active page restrictions from both page table (pre 1.10)
2140 * and page_restrictions table for this existing page.
2141 * Public for usage by LiquidThreads.
2143 * @param $rows array of db result objects
2144 * @param $oldFashionedRestrictions string comma-separated list of page
2145 * restrictions from page table (pre 1.10)
2147 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2149 $dbr = wfGetDB( DB_SLAVE
);
2151 $restrictionTypes = $this->getRestrictionTypes();
2153 foreach ( $restrictionTypes as $type ) {
2154 $this->mRestrictions
[$type] = array();
2155 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2158 $this->mCascadeRestriction
= false;
2160 # Backwards-compatibility: also load the restrictions from the page record (old format).
2162 if ( $oldFashionedRestrictions === null ) {
2163 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2164 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2167 if ( $oldFashionedRestrictions != '' ) {
2169 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2170 $temp = explode( '=', trim( $restrict ) );
2171 if ( count( $temp ) == 1 ) {
2172 // old old format should be treated as edit/move restriction
2173 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2174 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2176 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2180 $this->mOldRestrictions
= true;
2184 if ( count( $rows ) ) {
2185 # Current system - load second to make them override.
2186 $now = wfTimestampNow();
2187 $purgeExpired = false;
2189 # Cycle through all the restrictions.
2190 foreach ( $rows as $row ) {
2192 // Don't take care of restrictions types that aren't allowed
2193 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2196 // This code should be refactored, now that it's being used more generally,
2197 // But I don't really see any harm in leaving it in Block for now -werdna
2198 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2200 // Only apply the restrictions if they haven't expired!
2201 if ( !$expiry ||
$expiry > $now ) {
2202 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2203 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2205 $this->mCascadeRestriction |
= $row->pr_cascade
;
2207 // Trigger a lazy purge of expired restrictions
2208 $purgeExpired = true;
2212 if ( $purgeExpired ) {
2213 Title
::purgeExpiredRestrictions();
2217 $this->mRestrictionsLoaded
= true;
2221 * Load restrictions from the page_restrictions table
2223 * @param $oldFashionedRestrictions String comma-separated list of page
2224 * restrictions from page table (pre 1.10)
2226 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2228 if ( !$this->mRestrictionsLoaded
) {
2229 if ( $this->exists() ) {
2230 $dbr = wfGetDB( DB_SLAVE
);
2232 $res = $dbr->select(
2233 'page_restrictions',
2235 array( 'pr_page' => $this->getArticleId() ),
2239 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2241 $title_protection = $this->getTitleProtection();
2243 if ( $title_protection ) {
2244 $now = wfTimestampNow();
2245 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2247 if ( !$expiry ||
$expiry > $now ) {
2248 // Apply the restrictions
2249 $this->mRestrictionsExpiry
['create'] = $expiry;
2250 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2251 } else { // Get rid of the old restrictions
2252 Title
::purgeExpiredRestrictions();
2253 $this->mTitleProtection
= false;
2256 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2258 $this->mRestrictionsLoaded
= true;
2264 * Purge expired restrictions from the page_restrictions table
2266 static function purgeExpiredRestrictions() {
2267 $dbw = wfGetDB( DB_MASTER
);
2269 'page_restrictions',
2270 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2276 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2282 * Accessor/initialisation for mRestrictions
2284 * @param $action String action that permission needs to be checked for
2285 * @return Array of Strings the array of groups allowed to edit this article
2287 public function getRestrictions( $action ) {
2288 if ( !$this->mRestrictionsLoaded
) {
2289 $this->loadRestrictions();
2291 return isset( $this->mRestrictions
[$action] )
2292 ?
$this->mRestrictions
[$action]
2297 * Get the expiry time for the restriction against a given action
2299 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2300 * or not protected at all, or false if the action is not recognised.
2302 public function getRestrictionExpiry( $action ) {
2303 if ( !$this->mRestrictionsLoaded
) {
2304 $this->loadRestrictions();
2306 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2310 * Is there a version of this page in the deletion archive?
2312 * @return Int the number of archived revisions
2314 public function isDeleted() {
2315 if ( $this->getNamespace() < 0 ) {
2318 $dbr = wfGetDB( DB_SLAVE
);
2319 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2320 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2323 if ( $this->getNamespace() == NS_FILE
) {
2324 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2325 array( 'fa_name' => $this->getDBkey() ),
2334 * Is there a version of this page in the deletion archive?
2338 public function isDeletedQuick() {
2339 if ( $this->getNamespace() < 0 ) {
2342 $dbr = wfGetDB( DB_SLAVE
);
2343 $deleted = (bool)$dbr->selectField( 'archive', '1',
2344 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2347 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2348 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2349 array( 'fa_name' => $this->getDBkey() ),
2357 * Get the article ID for this Title from the link cache,
2358 * adding it if necessary
2360 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2362 * @return Int the ID
2364 public function getArticleID( $flags = 0 ) {
2365 if ( $this->getNamespace() < 0 ) {
2366 return $this->mArticleID
= 0;
2368 $linkCache = LinkCache
::singleton();
2369 if ( $flags & self
::GAID_FOR_UPDATE
) {
2370 $oldUpdate = $linkCache->forUpdate( true );
2371 $linkCache->clearLink( $this );
2372 $this->mArticleID
= $linkCache->addLinkObj( $this );
2373 $linkCache->forUpdate( $oldUpdate );
2375 if ( -1 == $this->mArticleID
) {
2376 $this->mArticleID
= $linkCache->addLinkObj( $this );
2379 return $this->mArticleID
;
2383 * Is this an article that is a redirect page?
2384 * Uses link cache, adding it if necessary
2386 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2389 public function isRedirect( $flags = 0 ) {
2390 if ( !is_null( $this->mRedirect
) ) {
2391 return $this->mRedirect
;
2393 # Calling getArticleID() loads the field from cache as needed
2394 if ( !$this->getArticleID( $flags ) ) {
2395 return $this->mRedirect
= false;
2397 $linkCache = LinkCache
::singleton();
2398 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2400 return $this->mRedirect
;
2404 * What is the length of this page?
2405 * Uses link cache, adding it if necessary
2407 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2410 public function getLength( $flags = 0 ) {
2411 if ( $this->mLength
!= -1 ) {
2412 return $this->mLength
;
2414 # Calling getArticleID() loads the field from cache as needed
2415 if ( !$this->getArticleID( $flags ) ) {
2416 return $this->mLength
= 0;
2418 $linkCache = LinkCache
::singleton();
2419 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2421 return $this->mLength
;
2425 * What is the page_latest field for this page?
2427 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2428 * @return Int or 0 if the page doesn't exist
2430 public function getLatestRevID( $flags = 0 ) {
2431 if ( $this->mLatestID
!== false ) {
2432 return intval( $this->mLatestID
);
2434 # Calling getArticleID() loads the field from cache as needed
2435 if ( !$this->getArticleID( $flags ) ) {
2436 return $this->mLatestID
= 0;
2438 $linkCache = LinkCache
::singleton();
2439 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2441 return $this->mLatestID
;
2445 * This clears some fields in this object, and clears any associated
2446 * keys in the "bad links" section of the link cache.
2448 * - This is called from Article::doEdit() and Article::insertOn() to allow
2449 * loading of the new page_id. It's also called from
2450 * Article::doDeleteArticle()
2452 * @param $newid Int the new Article ID
2454 public function resetArticleID( $newid ) {
2455 $linkCache = LinkCache
::singleton();
2456 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2458 if ( $newid === false ) {
2459 $this->mArticleID
= -1;
2461 $this->mArticleID
= intval( $newid );
2463 $this->mRestrictionsLoaded
= false;
2464 $this->mRestrictions
= array();
2465 $this->mRedirect
= null;
2466 $this->mLength
= -1;
2467 $this->mLatestID
= false;
2471 * Updates page_touched for this page; called from LinksUpdate.php
2473 * @return Bool true if the update succeded
2475 public function invalidateCache() {
2476 if ( wfReadOnly() ) {
2479 $dbw = wfGetDB( DB_MASTER
);
2480 $success = $dbw->update(
2482 array( 'page_touched' => $dbw->timestamp() ),
2486 HTMLFileCache
::clearFileCache( $this );
2491 * Prefix some arbitrary text with the namespace or interwiki prefix
2494 * @param $name String the text
2495 * @return String the prefixed text
2498 private function prefix( $name ) {
2500 if ( $this->mInterwiki
!= '' ) {
2501 $p = $this->mInterwiki
. ':';
2504 if ( 0 != $this->mNamespace
) {
2505 $p .= $this->getNsText() . ':';
2511 * Returns a simple regex that will match on characters and sequences invalid in titles.
2512 * Note that this doesn't pick up many things that could be wrong with titles, but that
2513 * replacing this regex with something valid will make many titles valid.
2515 * @return String regex string
2517 static function getTitleInvalidRegex() {
2518 static $rxTc = false;
2520 # Matching titles will be held as illegal.
2522 # Any character not allowed is forbidden...
2523 '[^' . Title
::legalChars() . ']' .
2524 # URL percent encoding sequences interfere with the ability
2525 # to round-trip titles -- you can't link to them consistently.
2526 '|%[0-9A-Fa-f]{2}' .
2527 # XML/HTML character references produce similar issues.
2528 '|&[A-Za-z0-9\x80-\xff]+;' .
2530 '|&#x[0-9A-Fa-f]+;' .
2538 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2540 * @param $text String containing title to capitalize
2541 * @param $ns int namespace index, defaults to NS_MAIN
2542 * @return String containing capitalized title
2544 public static function capitalize( $text, $ns = NS_MAIN
) {
2547 if ( MWNamespace
::isCapitalized( $ns ) ) {
2548 return $wgContLang->ucfirst( $text );
2555 * Secure and split - main initialisation function for this object
2557 * Assumes that mDbkeyform has been set, and is urldecoded
2558 * and uses underscores, but not otherwise munged. This function
2559 * removes illegal characters, splits off the interwiki and
2560 * namespace prefixes, sets the other forms, and canonicalizes
2563 * @return Bool true on success
2565 private function secureAndSplit() {
2566 global $wgContLang, $wgLocalInterwiki;
2569 $this->mInterwiki
= $this->mFragment
= '';
2570 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2572 $dbkey = $this->mDbkeyform
;
2574 # Strip Unicode bidi override characters.
2575 # Sometimes they slip into cut-n-pasted page titles, where the
2576 # override chars get included in list displays.
2577 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2579 # Clean up whitespace
2580 # Note: use of the /u option on preg_replace here will cause
2581 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2582 # conveniently disabling them.
2583 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2584 $dbkey = trim( $dbkey, '_' );
2586 if ( $dbkey == '' ) {
2590 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2591 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2595 $this->mDbkeyform
= $dbkey;
2597 # Initial colon indicates main namespace rather than specified default
2598 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2599 if ( ':' == $dbkey { 0 } ) {
2600 $this->mNamespace
= NS_MAIN
;
2601 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2602 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2605 # Namespace or interwiki prefix
2607 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2610 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2612 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2613 # Ordinary namespace
2615 $this->mNamespace
= $ns;
2616 # For Talk:X pages, check if X has a "namespace" prefix
2617 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2618 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2619 # Disallow Talk:File:x type titles...
2621 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2622 # Disallow Talk:Interwiki:x type titles...
2626 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2627 if ( !$firstPass ) {
2628 # Can't make a local interwiki link to an interwiki link.
2629 # That's just crazy!
2635 $this->mInterwiki
= $wgContLang->lc( $p );
2637 # Redundant interwiki prefix to the local wiki
2638 if ( $wgLocalInterwiki !== false
2639 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2641 if ( $dbkey == '' ) {
2642 # Can't have an empty self-link
2645 $this->mInterwiki
= '';
2647 # Do another namespace split...
2651 # If there's an initial colon after the interwiki, that also
2652 # resets the default namespace
2653 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2654 $this->mNamespace
= NS_MAIN
;
2655 $dbkey = substr( $dbkey, 1 );
2658 # If there's no recognized interwiki or namespace,
2659 # then let the colon expression be part of the title.
2664 # We already know that some pages won't be in the database!
2665 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2666 $this->mArticleID
= 0;
2668 $fragment = strstr( $dbkey, '#' );
2669 if ( false !== $fragment ) {
2670 $this->setFragment( $fragment );
2671 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2672 # remove whitespace again: prevents "Foo_bar_#"
2673 # becoming "Foo_bar_"
2674 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2677 # Reject illegal characters.
2678 $rxTc = self
::getTitleInvalidRegex();
2679 if ( preg_match( $rxTc, $dbkey ) ) {
2683 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2684 # reachable due to the way web browsers deal with 'relative' URLs.
2685 # Also, they conflict with subpage syntax. Forbid them explicitly.
2686 if ( strpos( $dbkey, '.' ) !== false &&
2687 ( $dbkey === '.' ||
$dbkey === '..' ||
2688 strpos( $dbkey, './' ) === 0 ||
2689 strpos( $dbkey, '../' ) === 0 ||
2690 strpos( $dbkey, '/./' ) !== false ||
2691 strpos( $dbkey, '/../' ) !== false ||
2692 substr( $dbkey, -2 ) == '/.' ||
2693 substr( $dbkey, -3 ) == '/..' ) )
2698 # Magic tilde sequences? Nu-uh!
2699 if ( strpos( $dbkey, '~~~' ) !== false ) {
2703 # Limit the size of titles to 255 bytes. This is typically the size of the
2704 # underlying database field. We make an exception for special pages, which
2705 # don't need to be stored in the database, and may edge over 255 bytes due
2706 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2707 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2708 strlen( $dbkey ) > 512 )
2713 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2714 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2715 # other site might be case-sensitive.
2716 $this->mUserCaseDBKey
= $dbkey;
2717 if ( $this->mInterwiki
== '' ) {
2718 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2721 # Can't make a link to a namespace alone... "empty" local links can only be
2722 # self-links with a fragment identifier.
2723 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2727 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2728 // IP names are not allowed for accounts, and can only be referring to
2729 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2730 // there are numerous ways to present the same IP. Having sp:contribs scan
2731 // them all is silly and having some show the edits and others not is
2732 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2733 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2734 ? IP
::sanitizeIP( $dbkey )
2737 // Any remaining initial :s are illegal.
2738 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2743 $this->mDbkeyform
= $dbkey;
2744 $this->mUrlform
= wfUrlencode( $dbkey );
2746 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2752 * Set the fragment for this title. Removes the first character from the
2753 * specified fragment before setting, so it assumes you're passing it with
2756 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2757 * Still in active use privately.
2759 * @param $fragment String text
2761 public function setFragment( $fragment ) {
2762 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2766 * Get a Title object associated with the talk page of this article
2768 * @return Title the object for the talk page
2770 public function getTalkPage() {
2771 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2775 * Get a title object associated with the subject page of this
2778 * @return Title the object for the subject page
2780 public function getSubjectPage() {
2781 // Is this the same title?
2782 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2783 if ( $this->getNamespace() == $subjectNS ) {
2786 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2790 * Get an array of Title objects linking to this Title
2791 * Also stores the IDs in the link cache.
2793 * WARNING: do not use this function on arbitrary user-supplied titles!
2794 * On heavily-used templates it will max out the memory.
2796 * @param $options Array: may be FOR UPDATE
2797 * @param $table String: table name
2798 * @param $prefix String: fields prefix
2799 * @return Array of Title objects linking here
2801 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2802 $linkCache = LinkCache
::singleton();
2804 if ( count( $options ) > 0 ) {
2805 $db = wfGetDB( DB_MASTER
);
2807 $db = wfGetDB( DB_SLAVE
);
2811 array( 'page', $table ),
2812 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2814 "{$prefix}_from=page_id",
2815 "{$prefix}_namespace" => $this->getNamespace(),
2816 "{$prefix}_title" => $this->getDBkey() ),
2822 if ( $db->numRows( $res ) ) {
2823 foreach ( $res as $row ) {
2824 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2826 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
2827 $retVal[] = $titleObj;
2835 * Get an array of Title objects using this Title as a template
2836 * Also stores the IDs in the link cache.
2838 * WARNING: do not use this function on arbitrary user-supplied titles!
2839 * On heavily-used templates it will max out the memory.
2841 * @param $options Array: may be FOR UPDATE
2842 * @return Array of Title the Title objects linking here
2844 public function getTemplateLinksTo( $options = array() ) {
2845 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2849 * Get an array of Title objects referring to non-existent articles linked from this page
2851 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2852 * @return Array of Title the Title objects
2854 public function getBrokenLinksFrom() {
2855 if ( $this->getArticleId() == 0 ) {
2856 # All links from article ID 0 are false positives
2860 $dbr = wfGetDB( DB_SLAVE
);
2861 $res = $dbr->select(
2862 array( 'page', 'pagelinks' ),
2863 array( 'pl_namespace', 'pl_title' ),
2865 'pl_from' => $this->getArticleId(),
2866 'page_namespace IS NULL'
2868 __METHOD__
, array(),
2872 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2878 foreach ( $res as $row ) {
2879 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2886 * Get a list of URLs to purge from the Squid cache when this
2889 * @return Array of String the URLs
2891 public function getSquidURLs() {
2895 $this->getInternalURL(),
2896 $this->getInternalURL( 'action=history' )
2899 // purge variant urls as well
2900 if ( $wgContLang->hasVariants() ) {
2901 $variants = $wgContLang->getVariants();
2902 foreach ( $variants as $vCode ) {
2903 $urls[] = $this->getInternalURL( '', $vCode );
2911 * Purge all applicable Squid URLs
2913 public function purgeSquid() {
2915 if ( $wgUseSquid ) {
2916 $urls = $this->getSquidURLs();
2917 $u = new SquidUpdate( $urls );
2923 * Move this page without authentication
2925 * @param $nt Title the new page Title
2926 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2928 public function moveNoAuth( &$nt ) {
2929 return $this->moveTo( $nt, false );
2933 * Check whether a given move operation would be valid.
2934 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2936 * @param $nt Title the new title
2937 * @param $auth Bool indicates whether $wgUser's permissions
2939 * @param $reason String is the log summary of the move, used for spam checking
2940 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2942 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2947 // Normally we'd add this to $errors, but we'll get
2948 // lots of syntax errors if $nt is not an object
2949 return array( array( 'badtitletext' ) );
2951 if ( $this->equals( $nt ) ) {
2952 $errors[] = array( 'selfmove' );
2954 if ( !$this->isMovable() ) {
2955 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2957 if ( $nt->getInterwiki() != '' ) {
2958 $errors[] = array( 'immobile-target-namespace-iw' );
2960 if ( !$nt->isMovable() ) {
2961 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2964 $oldid = $this->getArticleID();
2965 $newid = $nt->getArticleID();
2967 if ( strlen( $nt->getDBkey() ) < 1 ) {
2968 $errors[] = array( 'articleexists' );
2970 if ( ( $this->getDBkey() == '' ) ||
2972 ( $nt->getDBkey() == '' ) ) {
2973 $errors[] = array( 'badarticleerror' );
2976 // Image-specific checks
2977 if ( $this->getNamespace() == NS_FILE
) {
2978 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2981 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
2982 $errors[] = array( 'nonfile-cannot-move-to-file' );
2986 $errors = wfMergeErrorArrays( $errors,
2987 $this->getUserPermissionsErrors( 'move', $wgUser ),
2988 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2989 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2990 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2993 $match = EditPage
::matchSummarySpamRegex( $reason );
2994 if ( $match !== false ) {
2995 // This is kind of lame, won't display nice
2996 $errors[] = array( 'spamprotectiontext' );
3000 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3001 $errors[] = array( 'hookaborted', $err );
3004 # The move is allowed only if (1) the target doesn't exist, or
3005 # (2) the target is a redirect to the source, and has no history
3006 # (so we can undo bad moves right after they're done).
3008 if ( 0 != $newid ) { # Target exists; check for validity
3009 if ( !$this->isValidMoveTarget( $nt ) ) {
3010 $errors[] = array( 'articleexists' );
3013 $tp = $nt->getTitleProtection();
3014 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3015 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3016 $errors[] = array( 'cantmove-titleprotected' );
3019 if ( empty( $errors ) ) {
3026 * Check if the requested move target is a valid file move target
3027 * @param Title $nt Target title
3028 * @return array List of errors
3030 protected function validateFileMoveOperation( $nt ) {
3035 if ( $nt->getNamespace() != NS_FILE
) {
3036 $errors[] = array( 'imagenocrossnamespace' );
3039 $file = wfLocalFile( $this );
3040 if ( $file->exists() ) {
3041 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3042 $errors[] = array( 'imageinvalidfilename' );
3044 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3045 $errors[] = array( 'imagetypemismatch' );
3049 $destFile = wfLocalFile( $nt );
3050 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3051 $errors[] = array( 'file-exists-sharedrepo' );
3058 * Move a title to a new location
3060 * @param $nt Title the new title
3061 * @param $auth Bool indicates whether $wgUser's permissions
3063 * @param $reason String the reason for the move
3064 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3065 * Ignored if the user doesn't have the suppressredirect right.
3066 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3068 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3069 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3070 if ( is_array( $err ) ) {
3074 // If it is a file, move it first. It is done before all other moving stuff is
3075 // done because it's hard to revert
3076 $dbw = wfGetDB( DB_MASTER
);
3077 if ( $this->getNamespace() == NS_FILE
) {
3078 $file = wfLocalFile( $this );
3079 if ( $file->exists() ) {
3080 $status = $file->move( $nt );
3081 if ( !$status->isOk() ) {
3082 return $status->getErrorsArray();
3087 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3088 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3089 $protected = $this->isProtected();
3090 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3092 // Do the actual move
3093 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3094 if ( is_array( $err ) ) {
3095 # @todo FIXME: What about the File we have already moved?
3100 $redirid = $this->getArticleID();
3102 // Refresh the sortkey for this row. Be careful to avoid resetting
3103 // cl_timestamp, which may disturb time-based lists on some sites.
3104 $prefixes = $dbw->select(
3106 array( 'cl_sortkey_prefix', 'cl_to' ),
3107 array( 'cl_from' => $pageid ),
3110 foreach ( $prefixes as $prefixRow ) {
3111 $prefix = $prefixRow->cl_sortkey_prefix
;
3112 $catTo = $prefixRow->cl_to
;
3113 $dbw->update( 'categorylinks',
3115 'cl_sortkey' => Collation
::singleton()->getSortKey(
3116 $nt->getCategorySortkey( $prefix ) ),
3117 'cl_timestamp=cl_timestamp' ),
3119 'cl_from' => $pageid,
3120 'cl_to' => $catTo ),
3126 # Protect the redirect title as the title used to be...
3127 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3129 'pr_page' => $redirid,
3130 'pr_type' => 'pr_type',
3131 'pr_level' => 'pr_level',
3132 'pr_cascade' => 'pr_cascade',
3133 'pr_user' => 'pr_user',
3134 'pr_expiry' => 'pr_expiry'
3136 array( 'pr_page' => $pageid ),
3140 # Update the protection log
3141 $log = new LogPage( 'protect' );
3142 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3144 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3146 // @todo FIXME: $params?
3147 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3151 $oldnamespace = $this->getNamespace() & ~
1;
3152 $newnamespace = $nt->getNamespace() & ~
1;
3153 $oldtitle = $this->getDBkey();
3154 $newtitle = $nt->getDBkey();
3156 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3157 WatchedItem
::duplicateEntries( $this, $nt );
3160 # Update search engine
3161 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3163 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3169 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3170 # No longer a content page
3171 # Not viewed, edited, removing
3172 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3173 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3174 # Now a content page
3175 # Not viewed, edited, adding
3176 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3177 } elseif ( $pageCountChange ) {
3179 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3187 # Update message cache for interface messages
3188 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3189 # @bug 17860: old article can be deleted, if this the case,
3190 # delete it from message cache
3191 if ( $this->getArticleID() === 0 ) {
3192 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3194 $oldarticle = new Article( $this );
3195 MessageCache
::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3198 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3199 $newarticle = new Article( $nt );
3200 MessageCache
::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3204 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3209 * Move page to a title which is either a redirect to the
3210 * source page or nonexistent
3212 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3213 * @param $reason String The reason for the move
3214 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3215 * if the user doesn't have the suppressredirect right
3217 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3218 global $wgUser, $wgContLang;
3220 $moveOverRedirect = $nt->exists();
3222 $commentMsg = ( $moveOverRedirect ?
'1movedto2_redir' : '1movedto2' );
3223 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3226 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3228 # Truncate for whole multibyte characters.
3229 $comment = $wgContLang->truncate( $comment, 255 );
3231 $oldid = $this->getArticleID();
3232 $latest = $this->getLatestRevID();
3234 $oldns = $this->getNamespace();
3235 $olddbk = $this->getDBkey();
3237 $dbw = wfGetDB( DB_MASTER
);
3239 if ( $moveOverRedirect ) {
3240 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3242 $newid = $nt->getArticleID();
3243 $newns = $nt->getNamespace();
3244 $newdbk = $nt->getDBkey();
3246 # Delete the old redirect. We don't save it to history since
3247 # by definition if we've got here it's rather uninteresting.
3248 # We have to remove it so that the next step doesn't trigger
3249 # a conflict on the unique namespace+title index...
3250 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3251 if ( !$dbw->cascadingDeletes() ) {
3252 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3253 global $wgUseTrackbacks;
3254 if ( $wgUseTrackbacks ) {
3255 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3257 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3258 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3259 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3260 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3261 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3262 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3263 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3265 // If the target page was recently created, it may have an entry in recentchanges still
3266 $dbw->delete( 'recentchanges',
3267 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3272 # Save a null revision in the page's history notifying of the move
3273 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3274 if ( !is_object( $nullRevision ) ) {
3275 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3277 $nullRevId = $nullRevision->insertOn( $dbw );
3279 # Change the name of the target page:
3280 $dbw->update( 'page',
3282 'page_touched' => $dbw->timestamp(),
3283 'page_namespace' => $nt->getNamespace(),
3284 'page_title' => $nt->getDBkey(),
3285 'page_latest' => $nullRevId,
3287 /* WHERE */ array( 'page_id' => $oldid ),
3290 $nt->resetArticleID( $oldid );
3292 $article = new Article( $nt );
3293 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3295 # Recreate the redirect, this time in the other direction.
3296 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3297 $mwRedir = MagicWord
::get( 'redirect' );
3298 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3299 $redirectArticle = new Article( $this );
3300 $newid = $redirectArticle->insertOn( $dbw );
3301 $redirectRevision = new Revision( array(
3303 'comment' => $comment,
3304 'text' => $redirectText ) );
3305 $redirectRevision->insertOn( $dbw );
3306 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3308 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3310 # Now, we record the link from the redirect to the new title.
3311 # It should have no other outgoing links...
3312 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3313 $dbw->insert( 'pagelinks',
3315 'pl_from' => $newid,
3316 'pl_namespace' => $nt->getNamespace(),
3317 'pl_title' => $nt->getDBkey() ),
3319 $redirectSuppressed = false;
3321 // Get rid of old new page entries in Special:NewPages and RC.
3322 // Needs to be before $this->resetArticleID( 0 ).
3323 $dbw->delete( 'recentchanges', array(
3324 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3325 'rc_namespace' => $oldns,
3326 'rc_title' => $olddbk,
3332 $this->resetArticleID( 0 );
3333 $redirectSuppressed = true;
3337 $log = new LogPage( 'move' );
3338 $logType = ( $moveOverRedirect ?
'move_redir' : 'move' );
3339 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3341 # Purge caches for old and new titles
3342 if ( $moveOverRedirect ) {
3343 # A simple purge is enough when moving over a redirect
3346 # Purge caches as per article creation, including any pages that link to this title
3347 Article
::onArticleCreate( $nt );
3349 $this->purgeSquid();
3353 * Move this page's subpages to be subpages of $nt
3355 * @param $nt Title Move target
3356 * @param $auth bool Whether $wgUser's permissions should be checked
3357 * @param $reason string The reason for the move
3358 * @param $createRedirect bool Whether to create redirects from the old subpages to
3359 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3360 * @return mixed array with old page titles as keys, and strings (new page titles) or
3361 * arrays (errors) as values, or an error array with numeric indices if no pages
3364 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3365 global $wgMaximumMovedPages;
3366 // Check permissions
3367 if ( !$this->userCan( 'move-subpages' ) ) {
3368 return array( 'cant-move-subpages' );
3370 // Do the source and target namespaces support subpages?
3371 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3372 return array( 'namespace-nosubpages',
3373 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3375 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3376 return array( 'namespace-nosubpages',
3377 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3380 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3383 foreach ( $subpages as $oldSubpage ) {
3385 if ( $count > $wgMaximumMovedPages ) {
3386 $retval[$oldSubpage->getPrefixedTitle()] =
3387 array( 'movepage-max-pages',
3388 $wgMaximumMovedPages );
3392 // We don't know whether this function was called before
3393 // or after moving the root page, so check both
3395 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3396 $oldSubpage->getArticleID() == $nt->getArticleId() )
3398 // When moving a page to a subpage of itself,
3399 // don't move it twice
3402 $newPageName = preg_replace(
3403 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3404 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3405 $oldSubpage->getDBkey() );
3406 if ( $oldSubpage->isTalkPage() ) {
3407 $newNs = $nt->getTalkPage()->getNamespace();
3409 $newNs = $nt->getSubjectPage()->getNamespace();
3411 # Bug 14385: we need makeTitleSafe because the new page names may
3412 # be longer than 255 characters.
3413 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3415 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3416 if ( $success === true ) {
3417 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3419 $retval[$oldSubpage->getPrefixedText()] = $success;
3426 * Checks if this page is just a one-rev redirect.
3427 * Adds lock, so don't use just for light purposes.
3431 public function isSingleRevRedirect() {
3432 $dbw = wfGetDB( DB_MASTER
);
3434 $row = $dbw->selectRow( 'page',
3435 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3438 array( 'FOR UPDATE' )
3440 # Cache some fields we may want
3441 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3442 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3443 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3444 if ( !$this->mRedirect
) {
3447 # Does the article have a history?
3448 $row = $dbw->selectField( array( 'page', 'revision' ),
3450 array( 'page_namespace' => $this->getNamespace(),
3451 'page_title' => $this->getDBkey(),
3453 'page_latest != rev_id'
3456 array( 'FOR UPDATE' )
3458 # Return true if there was no history
3459 return ( $row === false );
3463 * Checks if $this can be moved to a given Title
3464 * - Selects for update, so don't call it unless you mean business
3466 * @param $nt Title the new title to check
3469 public function isValidMoveTarget( $nt ) {
3470 # Is it an existing file?
3471 if ( $nt->getNamespace() == NS_FILE
) {
3472 $file = wfLocalFile( $nt );
3473 if ( $file->exists() ) {
3474 wfDebug( __METHOD__
. ": file exists\n" );
3478 # Is it a redirect with no history?
3479 if ( !$nt->isSingleRevRedirect() ) {
3480 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3483 # Get the article text
3484 $rev = Revision
::newFromTitle( $nt );
3485 $text = $rev->getText();
3486 # Does the redirect point to the source?
3487 # Or is it a broken self-redirect, usually caused by namespace collisions?
3489 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3490 $redirTitle = Title
::newFromText( $m[1] );
3491 if ( !is_object( $redirTitle ) ||
3492 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3493 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3494 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3499 wfDebug( __METHOD__
. ": failsafe\n" );
3506 * Can this title be added to a user's watchlist?
3508 * @return Bool TRUE or FALSE
3510 public function isWatchable() {
3511 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3515 * Get categories to which this Title belongs and return an array of
3516 * categories' names.
3518 * @return Array of parents in the form:
3519 * $parent => $currentarticle
3521 public function getParentCategories() {
3526 $titleKey = $this->getArticleId();
3528 if ( $titleKey === 0 ) {
3532 $dbr = wfGetDB( DB_SLAVE
);
3534 $res = $dbr->select( 'categorylinks', '*',
3536 'cl_from' => $titleKey,
3542 if ( $dbr->numRows( $res ) > 0 ) {
3543 foreach ( $res as $row ) {
3544 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3545 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3552 * Get a tree of parent categories
3554 * @param $children Array with the children in the keys, to check for circular refs
3555 * @return Array Tree of parent categories
3557 public function getParentCategoryTree( $children = array() ) {
3559 $parents = $this->getParentCategories();
3562 foreach ( $parents as $parent => $current ) {
3563 if ( array_key_exists( $parent, $children ) ) {
3564 # Circular reference
3565 $stack[$parent] = array();
3567 $nt = Title
::newFromText( $parent );
3569 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3579 * Get an associative array for selecting this title from
3582 * @return Array suitable for the $where parameter of DB::select()
3584 public function pageCond() {
3585 if ( $this->mArticleID
> 0 ) {
3586 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3587 return array( 'page_id' => $this->mArticleID
);
3589 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3594 * Get the revision ID of the previous revision
3596 * @param $revId Int Revision ID. Get the revision that was before this one.
3597 * @param $flags Int Title::GAID_FOR_UPDATE
3598 * @return Int|Bool Old revision ID, or FALSE if none exists
3600 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3601 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3602 return $db->selectField( 'revision', 'rev_id',
3604 'rev_page' => $this->getArticleId( $flags ),
3605 'rev_id < ' . intval( $revId )
3608 array( 'ORDER BY' => 'rev_id DESC' )
3613 * Get the revision ID of the next revision
3615 * @param $revId Int Revision ID. Get the revision that was after this one.
3616 * @param $flags Int Title::GAID_FOR_UPDATE
3617 * @return Int|Bool Next revision ID, or FALSE if none exists
3619 public function getNextRevisionID( $revId, $flags = 0 ) {
3620 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3621 return $db->selectField( 'revision', 'rev_id',
3623 'rev_page' => $this->getArticleId( $flags ),
3624 'rev_id > ' . intval( $revId )
3627 array( 'ORDER BY' => 'rev_id' )
3632 * Get the first revision of the page
3634 * @param $flags Int Title::GAID_FOR_UPDATE
3635 * @return Revision|Null if page doesn't exist
3637 public function getFirstRevision( $flags = 0 ) {
3638 $pageId = $this->getArticleId( $flags );
3640 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3641 $row = $db->selectRow( 'revision', '*',
3642 array( 'rev_page' => $pageId ),
3644 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3647 return new Revision( $row );
3654 * Get the oldest revision timestamp of this page
3656 * @param $flags Int Title::GAID_FOR_UPDATE
3657 * @return String: MW timestamp
3659 public function getEarliestRevTime( $flags = 0 ) {
3660 $rev = $this->getFirstRevision( $flags );
3661 return $rev ?
$rev->getTimestamp() : null;
3665 * Check if this is a new page
3669 public function isNewPage() {
3670 $dbr = wfGetDB( DB_SLAVE
);
3671 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3675 * Get the number of revisions between the given revision.
3676 * Used for diffs and other things that really need it.
3678 * @param $old int|Revision Old revision or rev ID (first before range)
3679 * @param $new int|Revision New revision or rev ID (first after range)
3680 * @return Int Number of revisions between these revisions.
3682 public function countRevisionsBetween( $old, $new ) {
3683 if ( !( $old instanceof Revision
) ) {
3684 $old = Revision
::newFromTitle( $this, (int)$old );
3686 if ( !( $new instanceof Revision
) ) {
3687 $new = Revision
::newFromTitle( $this, (int)$new );
3689 if ( !$old ||
!$new ) {
3690 return 0; // nothing to compare
3692 $dbr = wfGetDB( DB_SLAVE
);
3693 return (int)$dbr->selectField( 'revision', 'count(*)',
3695 'rev_page' => $this->getArticleId(),
3696 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3697 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3704 * Get the number of authors between the given revision IDs.
3705 * Used for diffs and other things that really need it.
3707 * @param $old int|Revision Old revision or rev ID (first before range)
3708 * @param $new int|Revision New revision or rev ID (first after range)
3709 * @param $limit Int Maximum number of authors
3710 * @return Int Number of revision authors between these revisions.
3712 public function countAuthorsBetween( $old, $new, $limit ) {
3713 if ( !( $old instanceof Revision
) ) {
3714 $old = Revision
::newFromTitle( $this, (int)$old );
3716 if ( !( $new instanceof Revision
) ) {
3717 $new = Revision
::newFromTitle( $this, (int)$new );
3719 if ( !$old ||
!$new ) {
3720 return 0; // nothing to compare
3722 $dbr = wfGetDB( DB_SLAVE
);
3723 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3725 'rev_page' => $this->getArticleID(),
3726 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3727 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3729 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3731 return (int)$dbr->numRows( $res );
3735 * Compare with another title.
3737 * @param $title Title
3740 public function equals( Title
$title ) {
3741 // Note: === is necessary for proper matching of number-like titles.
3742 return $this->getInterwiki() === $title->getInterwiki()
3743 && $this->getNamespace() == $title->getNamespace()
3744 && $this->getDBkey() === $title->getDBkey();
3748 * Callback for usort() to do title sorts by (namespace, title)
3753 * @return Integer: result of string comparison, or namespace comparison
3755 public static function compare( $a, $b ) {
3756 if ( $a->getNamespace() == $b->getNamespace() ) {
3757 return strcmp( $a->getText(), $b->getText() );
3759 return $a->getNamespace() - $b->getNamespace();
3764 * Return a string representation of this title
3766 * @return String representation of this title
3768 public function __toString() {
3769 return $this->getPrefixedText();
3773 * Check if page exists. For historical reasons, this function simply
3774 * checks for the existence of the title in the page table, and will
3775 * thus return false for interwiki links, special pages and the like.
3776 * If you want to know if a title can be meaningfully viewed, you should
3777 * probably call the isKnown() method instead.
3781 public function exists() {
3782 return $this->getArticleId() != 0;
3786 * Should links to this title be shown as potentially viewable (i.e. as
3787 * "bluelinks"), even if there's no record by this title in the page
3790 * This function is semi-deprecated for public use, as well as somewhat
3791 * misleadingly named. You probably just want to call isKnown(), which
3792 * calls this function internally.
3794 * (ISSUE: Most of these checks are cheap, but the file existence check
3795 * can potentially be quite expensive. Including it here fixes a lot of
3796 * existing code, but we might want to add an optional parameter to skip
3797 * it and any other expensive checks.)
3801 public function isAlwaysKnown() {
3802 if ( $this->mInterwiki
!= '' ) {
3803 return true; // any interwiki link might be viewable, for all we know
3805 switch( $this->mNamespace
) {
3808 // file exists, possibly in a foreign repo
3809 return (bool)wfFindFile( $this );
3811 // valid special page
3812 return SpecialPageFactory
::exists( $this->getDBkey() );
3814 // selflink, possibly with fragment
3815 return $this->mDbkeyform
== '';
3817 // known system message
3818 return $this->getDefaultMessageText() !== false;
3825 * Does this title refer to a page that can (or might) be meaningfully
3826 * viewed? In particular, this function may be used to determine if
3827 * links to the title should be rendered as "bluelinks" (as opposed to
3828 * "redlinks" to non-existent pages).
3832 public function isKnown() {
3833 return $this->isAlwaysKnown() ||
$this->exists();
3837 * Does this page have source text?
3841 public function hasSourceText() {
3842 if ( $this->exists() ) {
3846 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3847 // If the page doesn't exist but is a known system message, default
3848 // message content will be displayed, same for language subpages
3849 return $this->getDefaultMessageText() !== false;
3856 * Get the default message text or false if the message doesn't exist
3858 * @return String or false
3860 public function getDefaultMessageText() {
3863 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
3867 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3868 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3870 if ( $message->exists() ) {
3871 return $message->plain();
3878 * Is this in a namespace that allows actual pages?
3881 * @internal note -- uses hardcoded namespace index instead of constants
3883 public function canExist() {
3884 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3888 * Update page_touched timestamps and send squid purge messages for
3889 * pages linking to this title. May be sent to the job queue depending
3890 * on the number of links. Typically called on create and delete.
3892 public function touchLinks() {
3893 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3896 if ( $this->getNamespace() == NS_CATEGORY
) {
3897 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3903 * Get the last touched timestamp
3905 * @param $db DatabaseBase: optional db
3906 * @return String last-touched timestamp
3908 public function getTouched( $db = null ) {
3909 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
3910 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3915 * Get the timestamp when this page was updated since the user last saw it.
3918 * @return String|Null
3920 public function getNotificationTimestamp( $user = null ) {
3921 global $wgUser, $wgShowUpdatedMarker;
3922 // Assume current user if none given
3926 // Check cache first
3927 $uid = $user->getId();
3928 // avoid isset here, as it'll return false for null entries
3929 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
3930 return $this->mNotificationTimestamp
[$uid];
3932 if ( !$uid ||
!$wgShowUpdatedMarker ) {
3933 return $this->mNotificationTimestamp
[$uid] = false;
3935 // Don't cache too much!
3936 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3937 $this->mNotificationTimestamp
= array();
3939 $dbr = wfGetDB( DB_SLAVE
);
3940 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3941 'wl_notificationtimestamp',
3942 array( 'wl_namespace' => $this->getNamespace(),
3943 'wl_title' => $this->getDBkey(),
3944 'wl_user' => $user->getId()
3948 return $this->mNotificationTimestamp
[$uid];
3952 * Get the trackback URL for this page
3954 * @return String Trackback URL
3956 public function trackbackURL() {
3957 global $wgScriptPath, $wgServer, $wgScriptExtension;
3959 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3960 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3964 * Get the trackback RDF for this page
3966 * @return String Trackback RDF
3968 public function trackbackRDF() {
3969 $url = htmlspecialchars( $this->getFullURL() );
3970 $title = htmlspecialchars( $this->getText() );
3971 $tburl = $this->trackbackURL();
3973 // Autodiscovery RDF is placed in comments so HTML validator
3974 // won't barf. This is a rather icky workaround, but seems
3975 // frequently used by this kind of RDF thingy.
3977 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3979 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3980 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3981 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3984 dc:identifier=\"$url\"
3986 trackback:ping=\"$tburl\" />
3992 * Generate strings used for xml 'id' names in monobook tabs
3994 * @param $prepend string defaults to 'nstab-'
3995 * @return String XML 'id' name
3997 public function getNamespaceKey( $prepend = 'nstab-' ) {
3999 // Gets the subject namespace if this title
4000 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4001 // Checks if cononical namespace name exists for namespace
4002 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4003 // Uses canonical namespace name
4004 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4006 // Uses text of namespace
4007 $namespaceKey = $this->getSubjectNsText();
4009 // Makes namespace key lowercase
4010 $namespaceKey = $wgContLang->lc( $namespaceKey );
4012 if ( $namespaceKey == '' ) {
4013 $namespaceKey = 'main';
4015 // Changes file to image for backwards compatibility
4016 if ( $namespaceKey == 'file' ) {
4017 $namespaceKey = 'image';
4019 return $prepend . $namespaceKey;
4023 * Returns true if this is a special page.
4027 public function isSpecialPage() {
4028 return $this->getNamespace() == NS_SPECIAL
;
4032 * Returns true if this title resolves to the named special page
4034 * @param $name String The special page name
4037 public function isSpecial( $name ) {
4038 if ( $this->getNamespace() == NS_SPECIAL
) {
4039 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4040 if ( $name == $thisName ) {
4048 * If the Title refers to a special page alias which is not the local default, resolve
4049 * the alias, and localise the name as necessary. Otherwise, return $this
4053 public function fixSpecialName() {
4054 if ( $this->getNamespace() == NS_SPECIAL
) {
4055 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4056 if ( $canonicalName ) {
4057 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName );
4058 if ( $localName != $this->mDbkeyform
) {
4059 return Title
::makeTitle( NS_SPECIAL
, $localName );
4067 * Is this Title in a namespace which contains content?
4068 * In other words, is this a content page, for the purposes of calculating
4073 public function isContentPage() {
4074 return MWNamespace
::isContent( $this->getNamespace() );
4078 * Get all extant redirects to this Title
4080 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4081 * @return Array of Title redirects to this title
4083 public function getRedirectsHere( $ns = null ) {
4086 $dbr = wfGetDB( DB_SLAVE
);
4088 'rd_namespace' => $this->getNamespace(),
4089 'rd_title' => $this->getDBkey(),
4092 if ( !is_null( $ns ) ) {
4093 $where['page_namespace'] = $ns;
4096 $res = $dbr->select(
4097 array( 'redirect', 'page' ),
4098 array( 'page_namespace', 'page_title' ),
4103 foreach ( $res as $row ) {
4104 $redirs[] = self
::newFromRow( $row );
4110 * Check if this Title is a valid redirect target
4114 public function isValidRedirectTarget() {
4115 global $wgInvalidRedirectTargets;
4117 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4118 if ( $this->isSpecial( 'Userlogout' ) ) {
4122 foreach ( $wgInvalidRedirectTargets as $target ) {
4123 if ( $this->isSpecial( $target ) ) {
4132 * Get a backlink cache object
4134 * @return object BacklinkCache
4136 function getBacklinkCache() {
4137 if ( is_null( $this->mBacklinkCache
) ) {
4138 $this->mBacklinkCache
= new BacklinkCache( $this );
4140 return $this->mBacklinkCache
;
4144 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4148 public function canUseNoindex() {
4149 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4151 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4152 ?
$wgContentNamespaces
4153 : $wgExemptFromUserRobotsControl;
4155 return !in_array( $this->mNamespace
, $bannedNamespaces );
4160 * Returns restriction types for the current Title
4162 * @return array applicable restriction types
4164 public function getRestrictionTypes() {
4165 if ( $this->getNamespace() == NS_SPECIAL
) {
4169 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4171 if ( $this->getNamespace() != NS_FILE
) {
4172 # Remove the upload restriction for non-file titles
4173 $types = array_diff( $types, array( 'upload' ) );
4176 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4178 wfDebug( __METHOD__
. ': applicable restriction types for ' .
4179 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4184 * Get a filtered list of all restriction types supported by this wiki.
4185 * @param bool $exists True to get all restriction types that apply to
4186 * titles that do exist, False for all restriction types that apply to
4187 * titles that do not exist
4190 public static function getFilteredRestrictionTypes( $exists = true ) {
4191 global $wgRestrictionTypes;
4192 $types = $wgRestrictionTypes;
4194 # Remove the create restriction for existing titles
4195 $types = array_diff( $types, array( 'create' ) );
4197 # Only the create and upload restrictions apply to non-existing titles
4198 $types = array_intersect( $types, array( 'create', 'upload' ) );
4204 * Returns the raw sort key to be used for categories, with the specified
4205 * prefix. This will be fed to Collation::getSortKey() to get a
4206 * binary sortkey that can be used for actual sorting.
4208 * @param $prefix string The prefix to be used, specified using
4209 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4213 public function getCategorySortkey( $prefix = '' ) {
4214 $unprefixed = $this->getText();
4215 if ( $prefix !== '' ) {
4216 # Separate with a line feed, so the unprefixed part is only used as
4217 # a tiebreaker when two pages have the exact same prefix.
4218 # In UCA, tab is the only character that can sort above LF
4219 # so we strip both of them from the original prefix.
4220 $prefix = strtr( $prefix, "\n\t", ' ' );
4221 return "$prefix\n$unprefixed";
4227 * Get the language this page is written in
4228 * Defaults to $wgContLang
4230 * @return object Language
4232 public function getPageLanguage() {
4234 $this->mPageLanguage
= $wgContLang;
4235 if ( $this->isCssOrJsPage() ) {
4236 // css/js should always be LTR and is, in fact, English
4237 $this->mPageLanguage
= Language
::factory( 'en' );
4238 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4239 // Parse mediawiki messages with correct target language
4240 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4241 $this->mPageLanguage
= wfGetLangObj( $lang );
4243 return $this->mPageLanguage
;
4248 * A BadTitle is generated in MediaWiki::parseTitle() if the title is invalid; the
4249 * software uses this to display an error page. Internally it's basically a Title
4250 * for an empty special page
4252 class BadTitle
extends Title
{
4253 public function __construct(){
4254 $this->mTextform
= '';
4255 $this->mUrlform
= '';
4256 $this->mDbkeyform
= '';
4257 $this->mNamespace
= NS_SPECIAL
; // Stops talk page link, etc, being shown
4260 public function exists(){
4264 public function getPrefixedText(){
4268 public function getText(){
4272 public function getPrefixedURL(){
4276 public function getPrefixedDBKey(){