8 * @deprecated This used to be a define, but was moved to
9 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
11 define( 'GAID_FOR_UPDATE', Title
::GAID_FOR_UPDATE
);
14 * Represents a title within MediaWiki.
15 * Optionally may contain an interwiki designation or namespace.
16 * @note This class can fetch various kinds of data from the database;
17 * however, it does so inefficiently.
19 * @internal documentation reviewed 15 Mar 2010
22 /** @name Static cache variables */
24 static private $titleCache = array();
28 * Title::newFromText maintains a cache to avoid expensive re-normalization of
29 * commonly used titles. On a batch operation this can become a memory leak
30 * if not bounded. After hitting this many titles reset the cache.
32 const CACHE_MAX
= 1000;
35 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
36 * to use the master DB
38 const GAID_FOR_UPDATE
= 1;
42 * @name Private member variables
43 * Please use the accessor functions instead.
48 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; // /< URL-encoded form of the main part
50 var $mDbkeyform = ''; // /< Main part with underscores
51 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
54 var $mFragment; // /< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; // /< ID of most recent revision
57 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
61 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
62 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
63 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
64 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
65 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
66 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
67 # Don't change the following default, NS_MAIN is hardcoded in several
68 # places. See bug 696.
69 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
70 # Zero except in {{transclusion}} tags
71 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
72 var $mLength = -1; // /< The page length, 0 for special pages
73 var $mRedirect = null; // /< Is the article at this title a redirect?
74 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
75 var $mBacklinkCache = null; // /< Cache of links to this title
82 /*protected*/ function __construct() { }
85 * Create a new Title from a prefixed DB key
87 * @param $key String the database key, which has underscores
88 * instead of spaces, possibly including namespace and
90 * @return Title, or NULL on an error
92 public static function newFromDBkey( $key ) {
94 $t->mDbkeyform
= $key;
95 if ( $t->secureAndSplit() ) {
103 * Create a new Title from text, such as what one would find in a link. De-
104 * codes any HTML entities in the text.
106 * @param $text String the link text; spaces, prefixes, and an
107 * initial ':' indicating the main namespace are accepted.
108 * @param $defaultNamespace Int the namespace to use if none is speci-
109 * fied by a prefix. If you want to force a specific namespace even if
110 * $text might begin with a namespace prefix, use makeTitle() or
112 * @return Title, or null on an error.
114 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
115 if ( is_object( $text ) ) {
116 throw new MWException( 'Title::newFromText given an object' );
120 * Wiki pages often contain multiple links to the same page.
121 * Title normalization and parsing can become expensive on
122 * pages with many links, so we can save a little time by
125 * In theory these are value objects and won't get changed...
127 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
128 return Title
::$titleCache[$text];
131 # Convert things like é ā or 〗 into normalized (bug 14952) text
132 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
135 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace
= $defaultNamespace;
138 static $cachedcount = 0 ;
139 if ( $t->secureAndSplit() ) {
140 if ( $defaultNamespace == NS_MAIN
) {
141 if ( $cachedcount >= self
::CACHE_MAX
) {
142 # Avoid memory leaks on mass operations...
143 Title
::$titleCache = array();
147 Title
::$titleCache[$text] =& $t;
157 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
159 * Example of wrong and broken code:
160 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
162 * Example of right code:
163 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
165 * Create a new Title from URL-encoded text. Ensures that
166 * the given title's length does not exceed the maximum.
168 * @param $url String the title, as might be taken from a URL
169 * @return Title the new object, or NULL on an error
171 public static function newFromURL( $url ) {
172 global $wgLegalTitleChars;
175 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
176 # but some URLs used it as a space replacement and they still come
177 # from some external search tools.
178 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
179 $url = str_replace( '+', ' ', $url );
182 $t->mDbkeyform
= str_replace( ' ', '_', $url );
183 if ( $t->secureAndSplit() ) {
191 * Create a new Title from an article ID
193 * @param $id Int the page_id corresponding to the Title to create
194 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
195 * @return Title the new object, or NULL on an error
197 public static function newFromID( $id, $flags = 0 ) {
198 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
199 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
200 if ( $row !== false ) {
201 $title = Title
::newFromRow( $row );
209 * Make an array of titles from an array of IDs
211 * @param $ids Array of Int Array of IDs
212 * @return Array of Titles
214 public static function newFromIDs( $ids ) {
215 if ( !count( $ids ) ) {
218 $dbr = wfGetDB( DB_SLAVE
);
223 'page_namespace', 'page_title', 'page_id',
224 'page_len', 'page_is_redirect', 'page_latest',
226 array( 'page_id' => $ids ),
231 foreach ( $res as $row ) {
232 $titles[] = Title
::newFromRow( $row );
238 * Make a Title object from a DB row
240 * @param $row Object database row (needs at least page_title,page_namespace)
241 * @return Title corresponding Title
243 public static function newFromRow( $row ) {
244 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
246 $t->mArticleID
= isset( $row->page_id
) ?
intval( $row->page_id
) : -1;
247 $t->mLength
= isset( $row->page_len
) ?
intval( $row->page_len
) : -1;
248 $t->mRedirect
= isset( $row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
249 $t->mLatestID
= isset( $row->page_latest
) ?
intval( $row->page_latest
) : false;
255 * Create a new Title from a namespace index and a DB key.
256 * It's assumed that $ns and $title are *valid*, for instance when
257 * they came directly from the database or a special page name.
258 * For convenience, spaces are converted to underscores so that
259 * eg user_text fields can be used directly.
261 * @param $ns Int the namespace of the article
262 * @param $title String the unprefixed database key form
263 * @param $fragment String the link fragment (after the "#")
264 * @param $interwiki String the interwiki prefix
265 * @return Title the new object
267 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
269 $t->mInterwiki
= $interwiki;
270 $t->mFragment
= $fragment;
271 $t->mNamespace
= $ns = intval( $ns );
272 $t->mDbkeyform
= str_replace( ' ', '_', $title );
273 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
274 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
275 $t->mTextform
= str_replace( '_', ' ', $title );
280 * Create a new Title from a namespace index and a DB key.
281 * The parameters will be checked for validity, which is a bit slower
282 * than makeTitle() but safer for user-provided data.
284 * @param $ns Int the namespace of the article
285 * @param $title String database key form
286 * @param $fragment String the link fragment (after the "#")
287 * @param $interwiki String interwiki prefix
288 * @return Title the new object, or NULL on an error
290 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
292 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
293 if ( $t->secureAndSplit() ) {
301 * Create a new Title for the Main Page
303 * @return Title the new object
305 public static function newMainPage() {
306 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
307 // Don't give fatal errors if the message is broken
309 $title = Title
::newFromText( 'Main Page' );
315 * Extract a redirect destination from a string and return the
316 * Title, or null if the text doesn't contain a valid redirect
317 * This will only return the very next target, useful for
318 * the redirect table and other checks that don't need full recursion
320 * @param $text String: Text with possible redirect
321 * @return Title: The corresponding Title
323 public static function newFromRedirect( $text ) {
324 return self
::newFromRedirectInternal( $text );
328 * Extract a redirect destination from a string and return the
329 * Title, or null if the text doesn't contain a valid redirect
330 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
331 * in order to provide (hopefully) the Title of the final destination instead of another redirect
333 * @param $text String Text with possible redirect
336 public static function newFromRedirectRecurse( $text ) {
337 $titles = self
::newFromRedirectArray( $text );
338 return $titles ?
array_pop( $titles ) : null;
342 * Extract a redirect destination from a string and return an
343 * array of Titles, or null if the text doesn't contain a valid redirect
344 * The last element in the array is the final destination after all redirects
345 * have been resolved (up to $wgMaxRedirects times)
347 * @param $text String Text with possible redirect
348 * @return Array of Titles, with the destination last
350 public static function newFromRedirectArray( $text ) {
351 global $wgMaxRedirects;
352 $title = self
::newFromRedirectInternal( $text );
353 if ( is_null( $title ) ) {
356 // recursive check to follow double redirects
357 $recurse = $wgMaxRedirects;
358 $titles = array( $title );
359 while ( --$recurse > 0 ) {
360 if ( $title->isRedirect() ) {
361 $article = new Article( $title, 0 );
362 $newtitle = $article->getRedirectTarget();
366 // Redirects to some special pages are not permitted
367 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
368 // the new title passes the checks, so make that our current title so that further recursion can be checked
370 $titles[] = $newtitle;
379 * Really extract the redirect destination
380 * Do not call this function directly, use one of the newFromRedirect* functions above
382 * @param $text String Text with possible redirect
385 protected static function newFromRedirectInternal( $text ) {
386 global $wgMaxRedirects;
387 if ( $wgMaxRedirects < 1 ) {
388 //redirects are disabled, so quit early
391 $redir = MagicWord
::get( 'redirect' );
392 $text = trim( $text );
393 if ( $redir->matchStartAndRemove( $text ) ) {
394 // Extract the first link and see if it's usable
395 // Ensure that it really does come directly after #REDIRECT
396 // Some older redirects included a colon, so don't freak about that!
398 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
399 // Strip preceding colon used to "escape" categories, etc.
400 // and URL-decode links
401 if ( strpos( $m[1], '%' ) !== false ) {
402 // Match behavior of inline link parsing here;
403 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
405 $title = Title
::newFromText( $m[1] );
406 // If the title is a redirect to bad special pages or is invalid, return null
407 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
416 # ----------------------------------------------------------------------------
418 # ----------------------------------------------------------------------------
421 * Get the prefixed DB key associated with an ID
423 * @param $id Int the page_id of the article
424 * @return Title an object representing the article, or NULL if no such article was found
426 public static function nameOf( $id ) {
427 $dbr = wfGetDB( DB_SLAVE
);
429 $s = $dbr->selectRow(
431 array( 'page_namespace', 'page_title' ),
432 array( 'page_id' => $id ),
435 if ( $s === false ) {
439 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
444 * Get a regex character class describing the legal characters in a link
446 * @return String the list of characters, not delimited
448 public static function legalChars() {
449 global $wgLegalTitleChars;
450 return $wgLegalTitleChars;
454 * Get a string representation of a title suitable for
455 * including in a search index
457 * @param $ns Int a namespace index
458 * @param $title String text-form main part
459 * @return String a stripped-down title string ready for the search index
461 public static function indexTitle( $ns, $title ) {
464 $lc = SearchEngine
::legalSearchChars() . '&#;';
465 $t = $wgContLang->normalizeForSearch( $title );
466 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
467 $t = $wgContLang->lc( $t );
470 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
471 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
473 $t = preg_replace( "/\\s+/", ' ', $t );
475 if ( $ns == NS_FILE
) {
476 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
482 * Make a prefixed DB key from a DB key and a namespace index
484 * @param $ns Int numerical representation of the namespace
485 * @param $title String the DB key form the title
486 * @param $fragment String The link fragment (after the "#")
487 * @param $interwiki String The interwiki prefix
488 * @return String the prefixed form of the title
490 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
493 $namespace = $wgContLang->getNsText( $ns );
494 $name = $namespace == '' ?
$title : "$namespace:$title";
495 if ( strval( $interwiki ) != '' ) {
496 $name = "$interwiki:$name";
498 if ( strval( $fragment ) != '' ) {
499 $name .= '#' . $fragment;
505 * Determine whether the object refers to a page within
508 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
510 public function isLocal() {
511 if ( $this->mInterwiki
!= '' ) {
512 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
519 * Determine whether the object refers to a page within
520 * this project and is transcludable.
522 * @return Bool TRUE if this is transcludable
524 public function isTrans() {
525 if ( $this->mInterwiki
== '' ) {
529 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
533 * Returns the DB name of the distant wiki which owns the object.
535 * @return String the DB name
537 public function getTransWikiID() {
538 if ( $this->mInterwiki
== '' ) {
542 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
546 * Escape a text fragment, say from a link, for a URL
548 * @param $fragment string containing a URL or link fragment (after the "#")
549 * @return String: escaped string
551 static function escapeFragmentForURL( $fragment ) {
552 # Note that we don't urlencode the fragment. urlencoded Unicode
553 # fragments appear not to work in IE (at least up to 7) or in at least
554 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
555 # to care if they aren't encoded.
556 return Sanitizer
::escapeId( $fragment, 'noninitial' );
559 # ----------------------------------------------------------------------------
561 # ----------------------------------------------------------------------------
563 /** Simple accessors */
565 * Get the text form (spaces not underscores) of the main part
567 * @return String Main part of the title
569 public function getText() { return $this->mTextform
; }
572 * Get the URL-encoded form of the main part
574 * @return String Main part of the title, URL-encoded
576 public function getPartialURL() { return $this->mUrlform
; }
579 * Get the main part with underscores
581 * @return String: Main part of the title, with underscores
583 public function getDBkey() { return $this->mDbkeyform
; }
586 * Get the namespace index, i.e. one of the NS_xxxx constants.
588 * @return Integer: Namespace index
590 public function getNamespace() { return $this->mNamespace
; }
593 * Get the namespace text
595 * @return String: Namespace text
597 public function getNsText() {
600 if ( $this->mInterwiki
!= '' ) {
601 // This probably shouldn't even happen. ohh man, oh yuck.
602 // But for interwiki transclusion it sometimes does.
603 // Shit. Shit shit shit.
605 // Use the canonical namespaces if possible to try to
606 // resolve a foreign namespace.
607 if ( MWNamespace
::exists( $this->mNamespace
) ) {
608 return MWNamespace
::getCanonicalName( $this->mNamespace
);
612 if ( $wgContLang->needsGenderDistinction() &&
613 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
614 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
615 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
618 return $wgContLang->getNsText( $this->mNamespace
);
622 * Get the DB key with the initial letter case as specified by the user
624 * @return String DB key
626 function getUserCaseDBKey() {
627 return $this->mUserCaseDBKey
;
631 * Get the namespace text of the subject (rather than talk) page
633 * @return String Namespace text
635 public function getSubjectNsText() {
637 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
641 * Get the namespace text of the talk page
643 * @return String Namespace text
645 public function getTalkNsText() {
647 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
651 * Could this title have a corresponding talk page?
653 * @return Bool TRUE or FALSE
655 public function canTalk() {
656 return( MWNamespace
::canTalk( $this->mNamespace
) );
660 * Get the interwiki prefix (or null string)
662 * @return String Interwiki prefix
664 public function getInterwiki() { return $this->mInterwiki
; }
667 * Get the Title fragment (i.e.\ the bit after the #) in text form
669 * @return String Title fragment
671 public function getFragment() { return $this->mFragment
; }
674 * Get the fragment in URL form, including the "#" character if there is one
675 * @return String Fragment in URL form
677 public function getFragmentForURL() {
678 if ( $this->mFragment
== '' ) {
681 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
686 * Get the default namespace index, for when there is no namespace
688 * @return Int Default namespace index
690 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
693 * Get title for search index
695 * @return String a stripped-down title string ready for the
698 public function getIndexTitle() {
699 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
703 * Get the prefixed database key form
705 * @return String the prefixed title, with underscores and
706 * any interwiki and namespace prefixes
708 public function getPrefixedDBkey() {
709 $s = $this->prefix( $this->mDbkeyform
);
710 $s = str_replace( ' ', '_', $s );
715 * Get the prefixed title with spaces.
716 * This is the form usually used for display
718 * @return String the prefixed title, with spaces
720 public function getPrefixedText() {
721 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
722 $s = $this->prefix( $this->mTextform
);
723 $s = str_replace( '_', ' ', $s );
724 $this->mPrefixedText
= $s;
726 return $this->mPrefixedText
;
730 * Get the prefixed title with spaces, plus any fragment
731 * (part beginning with '#')
733 * @return String the prefixed title, with spaces and the fragment, including '#'
735 public function getFullText() {
736 $text = $this->getPrefixedText();
737 if ( $this->mFragment
!= '' ) {
738 $text .= '#' . $this->mFragment
;
744 * Get the base name, i.e. the leftmost parts before the /
746 * @return String Base name
748 public function getBaseText() {
749 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
750 return $this->getText();
753 $parts = explode( '/', $this->getText() );
754 # Don't discard the real title if there's no subpage involved
755 if ( count( $parts ) > 1 ) {
756 unset( $parts[count( $parts ) - 1] );
758 return implode( '/', $parts );
762 * Get the lowest-level subpage name, i.e. the rightmost part after /
764 * @return String Subpage name
766 public function getSubpageText() {
767 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
768 return( $this->mTextform
);
770 $parts = explode( '/', $this->mTextform
);
771 return( $parts[count( $parts ) - 1] );
775 * Get a URL-encoded form of the subpage text
777 * @return String URL-encoded subpage name
779 public function getSubpageUrlForm() {
780 $text = $this->getSubpageText();
781 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
786 * Get a URL-encoded title (not an actual URL) including interwiki
788 * @return String the URL-encoded form
790 public function getPrefixedURL() {
791 $s = $this->prefix( $this->mDbkeyform
);
792 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
797 * Get a real URL referring to this title, with interwiki link and
800 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
801 * links. Can be specified as an associative array as well, e.g.,
802 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
803 * @param $variant String language variant of url (for sr, zh..)
804 * @return String the URL
806 public function getFullURL( $query = '', $variant = false ) {
807 global $wgServer, $wgRequest;
809 if ( is_array( $query ) ) {
810 $query = wfArrayToCGI( $query );
813 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
815 $url = $this->getLocalURL( $query, $variant );
817 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
818 // Correct fix would be to move the prepending elsewhere.
819 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
820 $url = $wgServer . $url;
823 $baseUrl = $interwiki->getURL();
825 $namespace = wfUrlencode( $this->getNsText() );
826 if ( $namespace != '' ) {
827 # Can this actually happen? Interwikis shouldn't be parsed.
828 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
831 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
832 $url = wfAppendQuery( $url, $query );
835 # Finally, add the fragment.
836 $url .= $this->getFragmentForURL();
838 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
843 * Get a URL with no fragment or server name. If this page is generated
844 * with action=render, $wgServer is prepended.
846 * @param $query Mixed: an optional query string; if not specified,
847 * $wgArticlePath will be used. Can be specified as an associative array
848 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
850 * @param $variant String language variant of url (for sr, zh..)
851 * @return String the URL
853 public function getLocalURL( $query = '', $variant = false ) {
854 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
855 global $wgVariantArticlePath, $wgContLang;
857 if ( is_array( $query ) ) {
858 $query = wfArrayToCGI( $query );
861 if ( $this->isExternal() ) {
862 $url = $this->getFullURL();
864 // This is currently only used for edit section links in the
865 // context of interwiki transclusion. In theory we should
866 // append the query to the end of any existing query string,
867 // but interwiki transclusion is already broken in that case.
871 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
872 if ( $query == '' ) {
873 if ( $variant != false && $wgContLang->hasVariants() ) {
874 if ( !$wgVariantArticlePath ) {
875 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
877 $variantArticlePath = $wgVariantArticlePath;
879 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
880 $url = str_replace( '$1', $dbkey, $url );
882 $url = str_replace( '$1', $dbkey, $wgArticlePath );
885 global $wgActionPaths;
888 if ( !empty( $wgActionPaths ) &&
889 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
891 $action = urldecode( $matches[2] );
892 if ( isset( $wgActionPaths[$action] ) ) {
893 $query = $matches[1];
894 if ( isset( $matches[4] ) ) {
895 $query .= $matches[4];
897 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
898 if ( $query != '' ) {
899 $url = wfAppendQuery( $url, $query );
903 if ( $url === false ) {
904 if ( $query == '-' ) {
907 $url = "{$wgScript}?title={$dbkey}&{$query}";
911 // FIXME: this causes breakage in various places when we
912 // actually expected a local URL and end up with dupe prefixes.
913 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
914 $url = $wgServer . $url;
917 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
922 * Get a URL that's the simplest URL that will be valid to link, locally,
923 * to the current Title. It includes the fragment, but does not include
924 * the server unless action=render is used (or the link is external). If
925 * there's a fragment but the prefixed text is empty, we just return a link
928 * The result obviously should not be URL-escaped, but does need to be
929 * HTML-escaped if it's being output in HTML.
931 * @param $query Array of Strings An associative array of key => value pairs for the
932 * query string. Keys and values will be escaped.
933 * @param $variant String language variant of URL (for sr, zh..). Ignored
934 * for external links. Default is "false" (same variant as current page,
935 * for anonymous users).
936 * @return String the URL
938 public function getLinkUrl( $query = array(), $variant = false ) {
939 wfProfileIn( __METHOD__
);
940 if ( $this->isExternal() ) {
941 $ret = $this->getFullURL( $query );
942 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
943 $ret = $this->getFragmentForURL();
945 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
947 wfProfileOut( __METHOD__
);
952 * Get an HTML-escaped version of the URL form, suitable for
953 * using in a link, without a server name or fragment
955 * @param $query String an optional query string
956 * @return String the URL
958 public function escapeLocalURL( $query = '' ) {
959 return htmlspecialchars( $this->getLocalURL( $query ) );
963 * Get an HTML-escaped version of the URL form, suitable for
964 * using in a link, including the server name and fragment
966 * @param $query String an optional query string
967 * @return String the URL
969 public function escapeFullURL( $query = '' ) {
970 return htmlspecialchars( $this->getFullURL( $query ) );
974 * Get the URL form for an internal link.
975 * - Used in various Squid-related code, in case we have a different
976 * internal hostname for the server from the exposed one.
978 * @param $query String an optional query string
979 * @param $variant String language variant of url (for sr, zh..)
980 * @return String the URL
982 public function getInternalURL( $query = '', $variant = false ) {
983 global $wgInternalServer, $wgServer;
984 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
985 $url = $server . $this->getLocalURL( $query, $variant );
986 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
991 * Get the edit URL for this Title
993 * @return String the URL, or a null string if this is an
996 public function getEditURL() {
997 if ( $this->mInterwiki
!= '' ) {
1000 $s = $this->getLocalURL( 'action=edit' );
1006 * Get the HTML-escaped displayable text form.
1007 * Used for the title field in <a> tags.
1009 * @return String the text, including any prefixes
1011 public function getEscapedText() {
1012 return htmlspecialchars( $this->getPrefixedText() );
1016 * Is this Title interwiki?
1020 public function isExternal() {
1021 return ( $this->mInterwiki
!= '' );
1025 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1027 * @param $action String Action to check (default: edit)
1030 public function isSemiProtected( $action = 'edit' ) {
1031 if ( $this->exists() ) {
1032 $restrictions = $this->getRestrictions( $action );
1033 if ( count( $restrictions ) > 0 ) {
1034 foreach ( $restrictions as $restriction ) {
1035 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1045 # If it doesn't exist, it can't be protected
1051 * Does the title correspond to a protected article?
1053 * @param $action String the action the page is protected from,
1054 * by default checks all actions.
1057 public function isProtected( $action = '' ) {
1058 global $wgRestrictionLevels;
1060 $restrictionTypes = $this->getRestrictionTypes();
1062 # Special pages have inherent protection
1063 if( $this->getNamespace() == NS_SPECIAL
) {
1067 # Check regular protection levels
1068 foreach ( $restrictionTypes as $type ) {
1069 if ( $action == $type ||
$action == '' ) {
1070 $r = $this->getRestrictions( $type );
1071 foreach ( $wgRestrictionLevels as $level ) {
1072 if ( in_array( $level, $r ) && $level != '' ) {
1083 * Is this a conversion table for the LanguageConverter?
1087 public function isConversionTable() {
1089 $this->getNamespace() == NS_MEDIAWIKI
&&
1090 strpos( $this->getText(), 'Conversiontable' ) !== false
1100 * Is $wgUser watching this page?
1104 public function userIsWatching() {
1107 if ( is_null( $this->mWatched
) ) {
1108 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1109 $this->mWatched
= false;
1111 $this->mWatched
= $wgUser->isWatched( $this );
1114 return $this->mWatched
;
1118 * Can $wgUser perform $action on this page?
1119 * This skips potentially expensive cascading permission checks
1120 * as well as avoids expensive error formatting
1122 * Suitable for use for nonessential UI controls in common cases, but
1123 * _not_ for functional access control.
1125 * May provide false positives, but should never provide a false negative.
1127 * @param $action String action that permission needs to be checked for
1130 public function quickUserCan( $action ) {
1131 return $this->userCan( $action, false );
1135 * Determines if $user is unable to edit this page because it has been protected
1136 * by $wgNamespaceProtection.
1138 * @param $user User object, $wgUser will be used if not passed
1141 public function isNamespaceProtected( User
$user = null ) {
1142 global $wgNamespaceProtection;
1144 if ( $user === null ) {
1149 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1150 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1151 if ( $right != '' && !$user->isAllowed( $right ) ) {
1160 * Can $wgUser perform $action on this page?
1162 * @param $action String action that permission needs to be checked for
1163 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1166 public function userCan( $action, $doExpensiveQueries = true ) {
1168 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1172 * Can $user perform $action on this page?
1174 * FIXME: This *does not* check throttles (User::pingLimiter()).
1176 * @param $action String action that permission needs to be checked for
1177 * @param $user User to check
1178 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1179 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1180 * @return Array of arguments to wfMsg to explain permissions problems.
1182 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1183 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1185 // Remove the errors being ignored.
1186 foreach ( $errors as $index => $error ) {
1187 $error_key = is_array( $error ) ?
$error[0] : $error;
1189 if ( in_array( $error_key, $ignoreErrors ) ) {
1190 unset( $errors[$index] );
1198 * Permissions checks that fail most often, and which are easiest to test.
1200 * @param $action String the action to check
1201 * @param $user User user to check
1202 * @param $errors Array list of current errors
1203 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1204 * @param $short Boolean short circuit on first error
1206 * @return Array list of errors
1208 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1209 if ( $action == 'create' ) {
1210 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1211 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1212 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1214 } elseif ( $action == 'move' ) {
1215 if ( !$user->isAllowed( 'move-rootuserpages' )
1216 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1217 // Show user page-specific message only if the user can move other pages
1218 $errors[] = array( 'cant-move-user-page' );
1221 // Check if user is allowed to move files if it's a file
1222 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1223 $errors[] = array( 'movenotallowedfile' );
1226 if ( !$user->isAllowed( 'move' ) ) {
1227 // User can't move anything
1228 global $wgGroupPermissions;
1229 $userCanMove = false;
1230 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1231 $userCanMove = $wgGroupPermissions['user']['move'];
1233 $autoconfirmedCanMove = false;
1234 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1235 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1237 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1238 // custom message if logged-in users without any special rights can move
1239 $errors[] = array( 'movenologintext' );
1241 $errors[] = array( 'movenotallowed' );
1244 } elseif ( $action == 'move-target' ) {
1245 if ( !$user->isAllowed( 'move' ) ) {
1246 // User can't move anything
1247 $errors[] = array( 'movenotallowed' );
1248 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1249 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1250 // Show user page-specific message only if the user can move other pages
1251 $errors[] = array( 'cant-move-to-user-page' );
1253 } elseif ( !$user->isAllowed( $action ) ) {
1254 // We avoid expensive display logic for quickUserCan's and such
1257 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1258 User
::getGroupsWithPermission( $action ) );
1265 $wgLang->commaList( $groups ),
1269 $return = array( 'badaccess-group0' );
1271 $errors[] = $return;
1278 * Add the resulting error code to the errors array
1280 * @param $errors Array list of current errors
1281 * @param $result Mixed result of errors
1283 * @return Array list of errors
1285 private function resultToError( $errors, $result ) {
1286 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1287 // A single array representing an error
1288 $errors[] = $result;
1289 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1290 // A nested array representing multiple errors
1291 $errors = array_merge( $errors, $result );
1292 } else if ( $result !== '' && is_string( $result ) ) {
1293 // A string representing a message-id
1294 $errors[] = array( $result );
1295 } else if ( $result === false ) {
1296 // a generic "We don't want them to do that"
1297 $errors[] = array( 'badaccess-group0' );
1303 * Check various permission hooks
1305 * @param $action String the action to check
1306 * @param $user User user to check
1307 * @param $errors Array list of current errors
1308 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1309 * @param $short Boolean short circuit on first error
1311 * @return Array list of errors
1313 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1314 // Use getUserPermissionsErrors instead
1316 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1317 return $result ?
array() : array( array( 'badaccess-group0' ) );
1319 // Check getUserPermissionsErrors hook
1320 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1321 $errors = $this->resultToError( $errors, $result );
1323 // Check getUserPermissionsErrorsExpensive hook
1324 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1325 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1326 $errors = $this->resultToError( $errors, $result );
1333 * Check permissions on special pages & namespaces
1335 * @param $action String the action to check
1336 * @param $user User user to check
1337 * @param $errors Array list of current errors
1338 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1339 * @param $short Boolean short circuit on first error
1341 * @return Array list of errors
1343 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1344 # Only 'createaccount' and 'execute' can be performed on
1345 # special pages, which don't actually exist in the DB.
1346 $specialOKActions = array( 'createaccount', 'execute' );
1347 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1348 $errors[] = array( 'ns-specialprotected' );
1351 # Check $wgNamespaceProtection for restricted namespaces
1352 if ( $this->isNamespaceProtected( $user ) ) {
1353 $ns = $this->mNamespace
== NS_MAIN ?
1354 wfMsg( 'nstab-main' ) : $this->getNsText();
1355 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1356 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1363 * Check CSS/JS sub-page permissions
1365 * @param $action String the action to check
1366 * @param $user User user to check
1367 * @param $errors Array list of current errors
1368 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1369 * @param $short Boolean short circuit on first error
1371 * @return Array list of errors
1373 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1374 # Protect css/js subpages of user pages
1375 # XXX: this might be better using restrictions
1376 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1377 # and $this->userCanEditJsSubpage() from working
1378 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1379 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1380 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1381 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1382 $errors[] = array( 'customcssjsprotected' );
1383 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1384 $errors[] = array( 'customcssjsprotected' );
1392 * Check against page_restrictions table requirements on this
1393 * page. The user must possess all required rights for this
1396 * @param $action String the action to check
1397 * @param $user User user to check
1398 * @param $errors Array list of current errors
1399 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1400 * @param $short Boolean short circuit on first error
1402 * @return Array list of errors
1404 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1405 foreach ( $this->getRestrictions( $action ) as $right ) {
1406 // Backwards compatibility, rewrite sysop -> protect
1407 if ( $right == 'sysop' ) {
1410 if ( $right != '' && !$user->isAllowed( $right ) ) {
1411 // Users with 'editprotected' permission can edit protected pages
1412 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1413 // Users with 'editprotected' permission cannot edit protected pages
1414 // with cascading option turned on.
1415 if ( $this->mCascadeRestriction
) {
1416 $errors[] = array( 'protectedpagetext', $right );
1419 $errors[] = array( 'protectedpagetext', $right );
1428 * Check restrictions on cascading pages.
1430 * @param $action String the action to check
1431 * @param $user User to check
1432 * @param $errors Array list of current errors
1433 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1434 * @param $short Boolean short circuit on first error
1436 * @return Array list of errors
1438 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1439 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1440 # We /could/ use the protection level on the source page, but it's
1441 # fairly ugly as we have to establish a precedence hierarchy for pages
1442 # included by multiple cascade-protected pages. So just restrict
1443 # it to people with 'protect' permission, as they could remove the
1444 # protection anyway.
1445 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1446 # Cascading protection depends on more than this page...
1447 # Several cascading protected pages may include this page...
1448 # Check each cascading level
1449 # This is only for protection restrictions, not for all actions
1450 if ( isset( $restrictions[$action] ) ) {
1451 foreach ( $restrictions[$action] as $right ) {
1452 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1453 if ( $right != '' && !$user->isAllowed( $right ) ) {
1455 foreach ( $cascadingSources as $page )
1456 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1457 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1467 * Check action permissions not already checked in checkQuickPermissions
1469 * @param $action String the action to check
1470 * @param $user User to check
1471 * @param $errors Array list of current errors
1472 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1473 * @param $short Boolean short circuit on first error
1475 * @return Array list of errors
1477 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1478 if ( $action == 'protect' ) {
1479 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1480 // If they can't edit, they shouldn't protect.
1481 $errors[] = array( 'protect-cantedit' );
1483 } elseif ( $action == 'create' ) {
1484 $title_protection = $this->getTitleProtection();
1485 if( $title_protection ) {
1486 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1487 $title_protection['pt_create_perm'] = 'protect'; // B/C
1489 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1490 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1493 } elseif ( $action == 'move' ) {
1494 // Check for immobile pages
1495 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1496 // Specific message for this case
1497 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1498 } elseif ( !$this->isMovable() ) {
1499 // Less specific message for rarer cases
1500 $errors[] = array( 'immobile-page' );
1502 } elseif ( $action == 'move-target' ) {
1503 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1504 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1505 } elseif ( !$this->isMovable() ) {
1506 $errors[] = array( 'immobile-target-page' );
1513 * Check that the user isn't blocked from editting.
1515 * @param $action String the action to check
1516 * @param $user User to check
1517 * @param $errors Array list of current errors
1518 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1519 * @param $short Boolean short circuit on first error
1521 * @return Array list of errors
1523 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1524 if( $short && count( $errors ) > 0 ) {
1528 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1530 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1531 $errors[] = array( 'confirmedittext' );
1534 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1535 // Edit blocks should not affect reading.
1536 // Account creation blocks handled at userlogin.
1537 // Unblocking handled in SpecialUnblock
1538 } elseif( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1539 // Don't block the user from editing their own talk page unless they've been
1540 // explicitly blocked from that too.
1541 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1542 $block = $user->mBlock
;
1544 // This is from OutputPage::blockedPage
1545 // Copied at r23888 by werdna
1547 $id = $user->blockedBy();
1548 $reason = $user->blockedFor();
1549 if ( $reason == '' ) {
1550 $reason = wfMsg( 'blockednoreason' );
1554 if ( is_numeric( $id ) ) {
1555 $name = User
::whoIs( $id );
1560 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1561 $blockid = $block->getId();
1562 $blockExpiry = $user->mBlock
->mExpiry
;
1563 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1564 if ( $blockExpiry == 'infinity' ) {
1565 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1567 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1570 $intended = strval( $user->mBlock
->getTarget() );
1572 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1573 $blockid, $blockExpiry, $intended, $blockTimestamp );
1580 * Can $user perform $action on this page? This is an internal function,
1581 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1582 * checks on wfReadOnly() and blocks)
1584 * @param $action String action that permission needs to be checked for
1585 * @param $user User to check
1586 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1587 * @param $short Bool Set this to true to stop after the first permission error.
1588 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1590 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1591 wfProfileIn( __METHOD__
);
1595 'checkQuickPermissions',
1596 'checkPermissionHooks',
1597 'checkSpecialsAndNSPermissions',
1598 'checkCSSandJSPermissions',
1599 'checkPageRestrictions',
1600 'checkCascadingSourcesRestrictions',
1601 'checkActionPermissions',
1605 while( count( $checks ) > 0 &&
1606 !( $short && count( $errors ) > 0 ) ) {
1607 $method = array_shift( $checks );
1608 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1611 wfProfileOut( __METHOD__
);
1616 * Is this title subject to title protection?
1617 * Title protection is the one applied against creation of such title.
1619 * @return Mixed An associative array representing any existent title
1620 * protection, or false if there's none.
1622 private function getTitleProtection() {
1623 // Can't protect pages in special namespaces
1624 if ( $this->getNamespace() < 0 ) {
1628 // Can't protect pages that exist.
1629 if ( $this->exists() ) {
1633 if ( !isset( $this->mTitleProtection
) ) {
1634 $dbr = wfGetDB( DB_SLAVE
);
1635 $res = $dbr->select( 'protected_titles', '*',
1636 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1639 // fetchRow returns false if there are no rows.
1640 $this->mTitleProtection
= $dbr->fetchRow( $res );
1642 return $this->mTitleProtection
;
1646 * Update the title protection status
1648 * @param $create_perm String Permission required for creation
1649 * @param $reason String Reason for protection
1650 * @param $expiry String Expiry timestamp
1651 * @return boolean true
1653 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1654 global $wgUser, $wgContLang;
1656 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1657 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1662 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1664 $dbw = wfGetDB( DB_MASTER
);
1666 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1668 $expiry_description = '';
1669 if ( $encodedExpiry != $dbw->getInfinity() ) {
1670 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1671 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1673 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1676 # Update protection table
1677 if ( $create_perm != '' ) {
1678 $this->mTitleProtection
= array(
1679 'pt_namespace' => $namespace,
1680 'pt_title' => $title,
1681 'pt_create_perm' => $create_perm,
1682 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1683 'pt_expiry' => $encodedExpiry,
1684 'pt_user' => $wgUser->getId(),
1685 'pt_reason' => $reason,
1687 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1688 $this->mTitleProtection
, __METHOD__
);
1690 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1691 'pt_title' => $title ), __METHOD__
);
1692 $this->mTitleProtection
= false;
1695 # Update the protection log
1696 if ( $dbw->affectedRows() ) {
1697 $log = new LogPage( 'protect' );
1699 if ( $create_perm ) {
1700 $params = array( "[create=$create_perm] $expiry_description", '' );
1701 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1703 $log->addEntry( 'unprotect', $this, $reason );
1711 * Remove any title protection due to page existing
1713 public function deleteTitleProtection() {
1714 $dbw = wfGetDB( DB_MASTER
);
1718 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1721 $this->mTitleProtection
= false;
1725 * Would anybody with sufficient privileges be able to move this page?
1726 * Some pages just aren't movable.
1728 * @return Bool TRUE or FALSE
1730 public function isMovable() {
1731 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1735 * Can $wgUser read this page?
1738 * @todo fold these checks into userCan()
1740 public function userCanRead() {
1741 global $wgUser, $wgGroupPermissions;
1743 static $useShortcut = null;
1745 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1746 if ( is_null( $useShortcut ) ) {
1747 global $wgRevokePermissions;
1748 $useShortcut = true;
1749 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1750 # Not a public wiki, so no shortcut
1751 $useShortcut = false;
1752 } elseif ( !empty( $wgRevokePermissions ) ) {
1754 * Iterate through each group with permissions being revoked (key not included since we don't care
1755 * what the group name is), then check if the read permission is being revoked. If it is, then
1756 * we don't use the shortcut below since the user might not be able to read, even though anon
1757 * reading is allowed.
1759 foreach ( $wgRevokePermissions as $perms ) {
1760 if ( !empty( $perms['read'] ) ) {
1761 # We might be removing the read right from the user, so no shortcut
1762 $useShortcut = false;
1770 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1771 if ( $result !== null ) {
1775 # Shortcut for public wikis, allows skipping quite a bit of code
1776 if ( $useShortcut ) {
1780 if ( $wgUser->isAllowed( 'read' ) ) {
1783 global $wgWhitelistRead;
1785 # Always grant access to the login page.
1786 # Even anons need to be able to log in.
1787 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'ChangePassword' ) ) {
1791 # Bail out if there isn't whitelist
1792 if ( !is_array( $wgWhitelistRead ) ) {
1796 # Check for explicit whitelisting
1797 $name = $this->getPrefixedText();
1798 $dbName = $this->getPrefixedDBKey();
1799 // Check with and without underscores
1800 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1803 # Old settings might have the title prefixed with
1804 # a colon for main-namespace pages
1805 if ( $this->getNamespace() == NS_MAIN
) {
1806 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1811 # If it's a special page, ditch the subpage bit and check again
1812 if ( $this->getNamespace() == NS_SPECIAL
) {
1813 $name = $this->getDBkey();
1814 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1815 if ( $name === false ) {
1816 # Invalid special page, but we show standard login required message
1820 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1821 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1831 * Is this the mainpage?
1832 * @note Title::newFromText seams to be sufficiently optimized by the title
1833 * cache that we don't need to over-optimize by doing direct comparisons and
1834 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1835 * ends up reporting something differently than $title->isMainPage();
1839 public function isMainPage() {
1840 return $this->equals( Title
::newMainPage() );
1844 * Is this a talk page of some sort?
1848 public function isTalkPage() {
1849 return MWNamespace
::isTalk( $this->getNamespace() );
1853 * Is this a subpage?
1857 public function isSubpage() {
1858 return MWNamespace
::hasSubpages( $this->mNamespace
)
1859 ?
strpos( $this->getText(), '/' ) !== false
1864 * Does this have subpages? (Warning, usually requires an extra DB query.)
1868 public function hasSubpages() {
1869 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1874 # We dynamically add a member variable for the purpose of this method
1875 # alone to cache the result. There's no point in having it hanging
1876 # around uninitialized in every Title object; therefore we only add it
1877 # if needed and don't declare it statically.
1878 if ( isset( $this->mHasSubpages
) ) {
1879 return $this->mHasSubpages
;
1882 $subpages = $this->getSubpages( 1 );
1883 if ( $subpages instanceof TitleArray
) {
1884 return $this->mHasSubpages
= (bool)$subpages->count();
1886 return $this->mHasSubpages
= false;
1890 * Get all subpages of this page.
1892 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1893 * @return mixed TitleArray, or empty array if this page's namespace
1894 * doesn't allow subpages
1896 public function getSubpages( $limit = -1 ) {
1897 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1901 $dbr = wfGetDB( DB_SLAVE
);
1902 $conds['page_namespace'] = $this->getNamespace();
1903 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1905 if ( $limit > -1 ) {
1906 $options['LIMIT'] = $limit;
1908 return $this->mSubpages
= TitleArray
::newFromResult(
1909 $dbr->select( 'page',
1910 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1919 * Could this page contain custom CSS or JavaScript, based
1924 public function isCssOrJsPage() {
1925 return $this->mNamespace
== NS_MEDIAWIKI
1926 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1930 * Is this a .css or .js subpage of a user page?
1933 public function isCssJsSubpage() {
1934 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1938 * Is this a *valid* .css or .js subpage of a user page?
1941 * @deprecated since 1.17
1943 public function isValidCssJsSubpage() {
1944 return $this->isCssJsSubpage();
1948 * Trim down a .css or .js subpage title to get the corresponding skin name
1950 * @return string containing skin name from .css or .js subpage title
1952 public function getSkinFromCssJsSubpage() {
1953 $subpage = explode( '/', $this->mTextform
);
1954 $subpage = $subpage[ count( $subpage ) - 1 ];
1955 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1959 * Is this a .css subpage of a user page?
1963 public function isCssSubpage() {
1964 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1968 * Is this a .js subpage of a user page?
1972 public function isJsSubpage() {
1973 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1977 * Protect css subpages of user pages: can $wgUser edit
1981 * @todo XXX: this might be better using restrictions
1983 public function userCanEditCssSubpage() {
1985 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1986 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1990 * Protect js subpages of user pages: can $wgUser edit
1994 * @todo XXX: this might be better using restrictions
1996 public function userCanEditJsSubpage() {
1998 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
1999 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2003 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2005 * @return Bool If the page is subject to cascading restrictions.
2007 public function isCascadeProtected() {
2008 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2009 return ( $sources > 0 );
2013 * Cascading protection: Get the source of any cascading restrictions on this page.
2015 * @param $getPages Bool Whether or not to retrieve the actual pages
2016 * that the restrictions have come from.
2017 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2018 * have come, false for none, or true if such restrictions exist, but $getPages
2019 * was not set. The restriction array is an array of each type, each of which
2020 * contains a array of unique groups.
2022 public function getCascadeProtectionSources( $getPages = true ) {
2024 $pagerestrictions = array();
2026 if ( isset( $this->mCascadeSources
) && $getPages ) {
2027 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2028 } else if ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2029 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2032 wfProfileIn( __METHOD__
);
2034 $dbr = wfGetDB( DB_SLAVE
);
2036 if ( $this->getNamespace() == NS_FILE
) {
2037 $tables = array( 'imagelinks', 'page_restrictions' );
2038 $where_clauses = array(
2039 'il_to' => $this->getDBkey(),
2044 $tables = array( 'templatelinks', 'page_restrictions' );
2045 $where_clauses = array(
2046 'tl_namespace' => $this->getNamespace(),
2047 'tl_title' => $this->getDBkey(),
2054 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2055 'pr_expiry', 'pr_type', 'pr_level' );
2056 $where_clauses[] = 'page_id=pr_page';
2059 $cols = array( 'pr_expiry' );
2062 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2064 $sources = $getPages ?
array() : false;
2065 $now = wfTimestampNow();
2066 $purgeExpired = false;
2068 foreach ( $res as $row ) {
2069 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2070 if ( $expiry > $now ) {
2072 $page_id = $row->pr_page
;
2073 $page_ns = $row->page_namespace
;
2074 $page_title = $row->page_title
;
2075 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2076 # Add groups needed for each restriction type if its not already there
2077 # Make sure this restriction type still exists
2079 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2080 $pagerestrictions[$row->pr_type
] = array();
2083 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2084 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2085 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2091 // Trigger lazy purge of expired restrictions from the db
2092 $purgeExpired = true;
2095 if ( $purgeExpired ) {
2096 Title
::purgeExpiredRestrictions();
2100 $this->mCascadeSources
= $sources;
2101 $this->mCascadingRestrictions
= $pagerestrictions;
2103 $this->mHasCascadingRestrictions
= $sources;
2106 wfProfileOut( __METHOD__
);
2107 return array( $sources, $pagerestrictions );
2111 * Returns cascading restrictions for the current article
2115 function areRestrictionsCascading() {
2116 if ( !$this->mRestrictionsLoaded
) {
2117 $this->loadRestrictions();
2120 return $this->mCascadeRestriction
;
2124 * Loads a string into mRestrictions array
2126 * @param $res Resource restrictions as an SQL result.
2127 * @param $oldFashionedRestrictions String comma-separated list of page
2128 * restrictions from page table (pre 1.10)
2130 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2133 foreach ( $res as $row ) {
2137 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2141 * Compiles list of active page restrictions from both page table (pre 1.10)
2142 * and page_restrictions table for this existing page.
2143 * Public for usage by LiquidThreads.
2145 * @param $rows array of db result objects
2146 * @param $oldFashionedRestrictions string comma-separated list of page
2147 * restrictions from page table (pre 1.10)
2149 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2151 $dbr = wfGetDB( DB_SLAVE
);
2153 $restrictionTypes = $this->getRestrictionTypes();
2155 foreach ( $restrictionTypes as $type ) {
2156 $this->mRestrictions
[$type] = array();
2157 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2160 $this->mCascadeRestriction
= false;
2162 # Backwards-compatibility: also load the restrictions from the page record (old format).
2164 if ( $oldFashionedRestrictions === null ) {
2165 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2166 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2169 if ( $oldFashionedRestrictions != '' ) {
2171 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2172 $temp = explode( '=', trim( $restrict ) );
2173 if ( count( $temp ) == 1 ) {
2174 // old old format should be treated as edit/move restriction
2175 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2176 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2178 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2182 $this->mOldRestrictions
= true;
2186 if ( count( $rows ) ) {
2187 # Current system - load second to make them override.
2188 $now = wfTimestampNow();
2189 $purgeExpired = false;
2191 # Cycle through all the restrictions.
2192 foreach ( $rows as $row ) {
2194 // Don't take care of restrictions types that aren't allowed
2195 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2198 // This code should be refactored, now that it's being used more generally,
2199 // But I don't really see any harm in leaving it in Block for now -werdna
2200 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2202 // Only apply the restrictions if they haven't expired!
2203 if ( !$expiry ||
$expiry > $now ) {
2204 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2205 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2207 $this->mCascadeRestriction |
= $row->pr_cascade
;
2209 // Trigger a lazy purge of expired restrictions
2210 $purgeExpired = true;
2214 if ( $purgeExpired ) {
2215 Title
::purgeExpiredRestrictions();
2219 $this->mRestrictionsLoaded
= true;
2223 * Load restrictions from the page_restrictions table
2225 * @param $oldFashionedRestrictions String comma-separated list of page
2226 * restrictions from page table (pre 1.10)
2228 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2230 if ( !$this->mRestrictionsLoaded
) {
2231 if ( $this->exists() ) {
2232 $dbr = wfGetDB( DB_SLAVE
);
2234 $res = $dbr->select(
2235 'page_restrictions',
2237 array( 'pr_page' => $this->getArticleId() ),
2241 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2243 $title_protection = $this->getTitleProtection();
2245 if ( $title_protection ) {
2246 $now = wfTimestampNow();
2247 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2249 if ( !$expiry ||
$expiry > $now ) {
2250 // Apply the restrictions
2251 $this->mRestrictionsExpiry
['create'] = $expiry;
2252 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2253 } else { // Get rid of the old restrictions
2254 Title
::purgeExpiredRestrictions();
2255 $this->mTitleProtection
= false;
2258 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2260 $this->mRestrictionsLoaded
= true;
2266 * Purge expired restrictions from the page_restrictions table
2268 static function purgeExpiredRestrictions() {
2269 $dbw = wfGetDB( DB_MASTER
);
2271 'page_restrictions',
2272 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2278 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2284 * Accessor/initialisation for mRestrictions
2286 * @param $action String action that permission needs to be checked for
2287 * @return Array of Strings the array of groups allowed to edit this article
2289 public function getRestrictions( $action ) {
2290 if ( !$this->mRestrictionsLoaded
) {
2291 $this->loadRestrictions();
2293 return isset( $this->mRestrictions
[$action] )
2294 ?
$this->mRestrictions
[$action]
2299 * Get the expiry time for the restriction against a given action
2301 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2302 * or not protected at all, or false if the action is not recognised.
2304 public function getRestrictionExpiry( $action ) {
2305 if ( !$this->mRestrictionsLoaded
) {
2306 $this->loadRestrictions();
2308 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2312 * Is there a version of this page in the deletion archive?
2314 * @return Int the number of archived revisions
2316 public function isDeleted() {
2317 if ( $this->getNamespace() < 0 ) {
2320 $dbr = wfGetDB( DB_SLAVE
);
2321 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2322 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2325 if ( $this->getNamespace() == NS_FILE
) {
2326 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2327 array( 'fa_name' => $this->getDBkey() ),
2336 * Is there a version of this page in the deletion archive?
2340 public function isDeletedQuick() {
2341 if ( $this->getNamespace() < 0 ) {
2344 $dbr = wfGetDB( DB_SLAVE
);
2345 $deleted = (bool)$dbr->selectField( 'archive', '1',
2346 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2349 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2350 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2351 array( 'fa_name' => $this->getDBkey() ),
2359 * Get the article ID for this Title from the link cache,
2360 * adding it if necessary
2362 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2364 * @return Int the ID
2366 public function getArticleID( $flags = 0 ) {
2367 if ( $this->getNamespace() < 0 ) {
2368 return $this->mArticleID
= 0;
2370 $linkCache = LinkCache
::singleton();
2371 if ( $flags & self
::GAID_FOR_UPDATE
) {
2372 $oldUpdate = $linkCache->forUpdate( true );
2373 $linkCache->clearLink( $this );
2374 $this->mArticleID
= $linkCache->addLinkObj( $this );
2375 $linkCache->forUpdate( $oldUpdate );
2377 if ( -1 == $this->mArticleID
) {
2378 $this->mArticleID
= $linkCache->addLinkObj( $this );
2381 return $this->mArticleID
;
2385 * Is this an article that is a redirect page?
2386 * Uses link cache, adding it if necessary
2388 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2391 public function isRedirect( $flags = 0 ) {
2392 if ( !is_null( $this->mRedirect
) ) {
2393 return $this->mRedirect
;
2395 # Calling getArticleID() loads the field from cache as needed
2396 if ( !$this->getArticleID( $flags ) ) {
2397 return $this->mRedirect
= false;
2399 $linkCache = LinkCache
::singleton();
2400 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2402 return $this->mRedirect
;
2406 * What is the length of this page?
2407 * Uses link cache, adding it if necessary
2409 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2412 public function getLength( $flags = 0 ) {
2413 if ( $this->mLength
!= -1 ) {
2414 return $this->mLength
;
2416 # Calling getArticleID() loads the field from cache as needed
2417 if ( !$this->getArticleID( $flags ) ) {
2418 return $this->mLength
= 0;
2420 $linkCache = LinkCache
::singleton();
2421 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2423 return $this->mLength
;
2427 * What is the page_latest field for this page?
2429 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2430 * @return Int or 0 if the page doesn't exist
2432 public function getLatestRevID( $flags = 0 ) {
2433 if ( $this->mLatestID
!== false ) {
2434 return intval( $this->mLatestID
);
2436 # Calling getArticleID() loads the field from cache as needed
2437 if ( !$this->getArticleID( $flags ) ) {
2438 return $this->mLatestID
= 0;
2440 $linkCache = LinkCache
::singleton();
2441 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2443 return $this->mLatestID
;
2447 * This clears some fields in this object, and clears any associated
2448 * keys in the "bad links" section of the link cache.
2450 * - This is called from Article::doEdit() and Article::insertOn() to allow
2451 * loading of the new page_id. It's also called from
2452 * Article::doDeleteArticle()
2454 * @param $newid Int the new Article ID
2456 public function resetArticleID( $newid ) {
2457 $linkCache = LinkCache
::singleton();
2458 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2460 if ( $newid === false ) {
2461 $this->mArticleID
= -1;
2463 $this->mArticleID
= intval( $newid );
2465 $this->mRestrictionsLoaded
= false;
2466 $this->mRestrictions
= array();
2467 $this->mRedirect
= null;
2468 $this->mLength
= -1;
2469 $this->mLatestID
= false;
2473 * Updates page_touched for this page; called from LinksUpdate.php
2475 * @return Bool true if the update succeded
2477 public function invalidateCache() {
2478 if ( wfReadOnly() ) {
2481 $dbw = wfGetDB( DB_MASTER
);
2482 $success = $dbw->update(
2484 array( 'page_touched' => $dbw->timestamp() ),
2488 HTMLFileCache
::clearFileCache( $this );
2493 * Prefix some arbitrary text with the namespace or interwiki prefix
2496 * @param $name String the text
2497 * @return String the prefixed text
2500 private function prefix( $name ) {
2502 if ( $this->mInterwiki
!= '' ) {
2503 $p = $this->mInterwiki
. ':';
2506 if ( 0 != $this->mNamespace
) {
2507 $p .= $this->getNsText() . ':';
2513 * Returns a simple regex that will match on characters and sequences invalid in titles.
2514 * Note that this doesn't pick up many things that could be wrong with titles, but that
2515 * replacing this regex with something valid will make many titles valid.
2517 * @return String regex string
2519 static function getTitleInvalidRegex() {
2520 static $rxTc = false;
2522 # Matching titles will be held as illegal.
2524 # Any character not allowed is forbidden...
2525 '[^' . Title
::legalChars() . ']' .
2526 # URL percent encoding sequences interfere with the ability
2527 # to round-trip titles -- you can't link to them consistently.
2528 '|%[0-9A-Fa-f]{2}' .
2529 # XML/HTML character references produce similar issues.
2530 '|&[A-Za-z0-9\x80-\xff]+;' .
2532 '|&#x[0-9A-Fa-f]+;' .
2540 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2542 * @param $text String containing title to capitalize
2543 * @param $ns int namespace index, defaults to NS_MAIN
2544 * @return String containing capitalized title
2546 public static function capitalize( $text, $ns = NS_MAIN
) {
2549 if ( MWNamespace
::isCapitalized( $ns ) ) {
2550 return $wgContLang->ucfirst( $text );
2557 * Secure and split - main initialisation function for this object
2559 * Assumes that mDbkeyform has been set, and is urldecoded
2560 * and uses underscores, but not otherwise munged. This function
2561 * removes illegal characters, splits off the interwiki and
2562 * namespace prefixes, sets the other forms, and canonicalizes
2565 * @return Bool true on success
2567 private function secureAndSplit() {
2568 global $wgContLang, $wgLocalInterwiki;
2571 $this->mInterwiki
= $this->mFragment
= '';
2572 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2574 $dbkey = $this->mDbkeyform
;
2576 # Strip Unicode bidi override characters.
2577 # Sometimes they slip into cut-n-pasted page titles, where the
2578 # override chars get included in list displays.
2579 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2581 # Clean up whitespace
2582 # Note: use of the /u option on preg_replace here will cause
2583 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2584 # conveniently disabling them.
2585 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2586 $dbkey = trim( $dbkey, '_' );
2588 if ( $dbkey == '' ) {
2592 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2593 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2597 $this->mDbkeyform
= $dbkey;
2599 # Initial colon indicates main namespace rather than specified default
2600 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2601 if ( ':' == $dbkey { 0 } ) {
2602 $this->mNamespace
= NS_MAIN
;
2603 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2604 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2607 # Namespace or interwiki prefix
2609 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2612 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2614 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2615 # Ordinary namespace
2617 $this->mNamespace
= $ns;
2618 # For Talk:X pages, check if X has a "namespace" prefix
2619 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2620 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2621 # Disallow Talk:File:x type titles...
2623 } else if ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2624 # Disallow Talk:Interwiki:x type titles...
2628 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2629 if ( !$firstPass ) {
2630 # Can't make a local interwiki link to an interwiki link.
2631 # That's just crazy!
2637 $this->mInterwiki
= $wgContLang->lc( $p );
2639 # Redundant interwiki prefix to the local wiki
2640 if ( $wgLocalInterwiki !== false
2641 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2643 if ( $dbkey == '' ) {
2644 # Can't have an empty self-link
2647 $this->mInterwiki
= '';
2649 # Do another namespace split...
2653 # If there's an initial colon after the interwiki, that also
2654 # resets the default namespace
2655 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2656 $this->mNamespace
= NS_MAIN
;
2657 $dbkey = substr( $dbkey, 1 );
2660 # If there's no recognized interwiki or namespace,
2661 # then let the colon expression be part of the title.
2666 # We already know that some pages won't be in the database!
2667 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2668 $this->mArticleID
= 0;
2670 $fragment = strstr( $dbkey, '#' );
2671 if ( false !== $fragment ) {
2672 $this->setFragment( $fragment );
2673 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2674 # remove whitespace again: prevents "Foo_bar_#"
2675 # becoming "Foo_bar_"
2676 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2679 # Reject illegal characters.
2680 $rxTc = self
::getTitleInvalidRegex();
2681 if ( preg_match( $rxTc, $dbkey ) ) {
2685 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2686 # reachable due to the way web browsers deal with 'relative' URLs.
2687 # Also, they conflict with subpage syntax. Forbid them explicitly.
2688 if ( strpos( $dbkey, '.' ) !== false &&
2689 ( $dbkey === '.' ||
$dbkey === '..' ||
2690 strpos( $dbkey, './' ) === 0 ||
2691 strpos( $dbkey, '../' ) === 0 ||
2692 strpos( $dbkey, '/./' ) !== false ||
2693 strpos( $dbkey, '/../' ) !== false ||
2694 substr( $dbkey, -2 ) == '/.' ||
2695 substr( $dbkey, -3 ) == '/..' ) )
2700 # Magic tilde sequences? Nu-uh!
2701 if ( strpos( $dbkey, '~~~' ) !== false ) {
2705 # Limit the size of titles to 255 bytes. This is typically the size of the
2706 # underlying database field. We make an exception for special pages, which
2707 # don't need to be stored in the database, and may edge over 255 bytes due
2708 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2709 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2710 strlen( $dbkey ) > 512 )
2715 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2716 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2717 # other site might be case-sensitive.
2718 $this->mUserCaseDBKey
= $dbkey;
2719 if ( $this->mInterwiki
== '' ) {
2720 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2723 # Can't make a link to a namespace alone... "empty" local links can only be
2724 # self-links with a fragment identifier.
2725 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2729 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2730 // IP names are not allowed for accounts, and can only be referring to
2731 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2732 // there are numerous ways to present the same IP. Having sp:contribs scan
2733 // them all is silly and having some show the edits and others not is
2734 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2735 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2736 ? IP
::sanitizeIP( $dbkey )
2739 // Any remaining initial :s are illegal.
2740 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2745 $this->mDbkeyform
= $dbkey;
2746 $this->mUrlform
= wfUrlencode( $dbkey );
2748 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2754 * Set the fragment for this title. Removes the first character from the
2755 * specified fragment before setting, so it assumes you're passing it with
2758 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2759 * Still in active use privately.
2761 * @param $fragment String text
2763 public function setFragment( $fragment ) {
2764 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2768 * Get a Title object associated with the talk page of this article
2770 * @return Title the object for the talk page
2772 public function getTalkPage() {
2773 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2777 * Get a title object associated with the subject page of this
2780 * @return Title the object for the subject page
2782 public function getSubjectPage() {
2783 // Is this the same title?
2784 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2785 if ( $this->getNamespace() == $subjectNS ) {
2788 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2792 * Get an array of Title objects linking to this Title
2793 * Also stores the IDs in the link cache.
2795 * WARNING: do not use this function on arbitrary user-supplied titles!
2796 * On heavily-used templates it will max out the memory.
2798 * @param $options Array: may be FOR UPDATE
2799 * @param $table String: table name
2800 * @param $prefix String: fields prefix
2801 * @return Array of Title objects linking here
2803 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2804 $linkCache = LinkCache
::singleton();
2806 if ( count( $options ) > 0 ) {
2807 $db = wfGetDB( DB_MASTER
);
2809 $db = wfGetDB( DB_SLAVE
);
2813 array( 'page', $table ),
2814 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2816 "{$prefix}_from=page_id",
2817 "{$prefix}_namespace" => $this->getNamespace(),
2818 "{$prefix}_title" => $this->getDBkey() ),
2824 if ( $db->numRows( $res ) ) {
2825 foreach ( $res as $row ) {
2826 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2828 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
2829 $retVal[] = $titleObj;
2837 * Get an array of Title objects using this Title as a template
2838 * Also stores the IDs in the link cache.
2840 * WARNING: do not use this function on arbitrary user-supplied titles!
2841 * On heavily-used templates it will max out the memory.
2843 * @param $options Array: may be FOR UPDATE
2844 * @return Array of Title the Title objects linking here
2846 public function getTemplateLinksTo( $options = array() ) {
2847 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2851 * Get an array of Title objects referring to non-existent articles linked from this page
2853 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2854 * @return Array of Title the Title objects
2856 public function getBrokenLinksFrom() {
2857 if ( $this->getArticleId() == 0 ) {
2858 # All links from article ID 0 are false positives
2862 $dbr = wfGetDB( DB_SLAVE
);
2863 $res = $dbr->select(
2864 array( 'page', 'pagelinks' ),
2865 array( 'pl_namespace', 'pl_title' ),
2867 'pl_from' => $this->getArticleId(),
2868 'page_namespace IS NULL'
2870 __METHOD__
, array(),
2874 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2880 foreach ( $res as $row ) {
2881 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2888 * Get a list of URLs to purge from the Squid cache when this
2891 * @return Array of String the URLs
2893 public function getSquidURLs() {
2897 $this->getInternalURL(),
2898 $this->getInternalURL( 'action=history' )
2901 // purge variant urls as well
2902 if ( $wgContLang->hasVariants() ) {
2903 $variants = $wgContLang->getVariants();
2904 foreach ( $variants as $vCode ) {
2905 $urls[] = $this->getInternalURL( '', $vCode );
2913 * Purge all applicable Squid URLs
2915 public function purgeSquid() {
2917 if ( $wgUseSquid ) {
2918 $urls = $this->getSquidURLs();
2919 $u = new SquidUpdate( $urls );
2925 * Move this page without authentication
2927 * @param $nt Title the new page Title
2928 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2930 public function moveNoAuth( &$nt ) {
2931 return $this->moveTo( $nt, false );
2935 * Check whether a given move operation would be valid.
2936 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2938 * @param $nt Title the new title
2939 * @param $auth Bool indicates whether $wgUser's permissions
2941 * @param $reason String is the log summary of the move, used for spam checking
2942 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2944 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2949 // Normally we'd add this to $errors, but we'll get
2950 // lots of syntax errors if $nt is not an object
2951 return array( array( 'badtitletext' ) );
2953 if ( $this->equals( $nt ) ) {
2954 $errors[] = array( 'selfmove' );
2956 if ( !$this->isMovable() ) {
2957 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2959 if ( $nt->getInterwiki() != '' ) {
2960 $errors[] = array( 'immobile-target-namespace-iw' );
2962 if ( !$nt->isMovable() ) {
2963 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2966 $oldid = $this->getArticleID();
2967 $newid = $nt->getArticleID();
2969 if ( strlen( $nt->getDBkey() ) < 1 ) {
2970 $errors[] = array( 'articleexists' );
2972 if ( ( $this->getDBkey() == '' ) ||
2974 ( $nt->getDBkey() == '' ) ) {
2975 $errors[] = array( 'badarticleerror' );
2978 // Image-specific checks
2979 if ( $this->getNamespace() == NS_FILE
) {
2980 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2983 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
2984 $errors[] = array( 'nonfile-cannot-move-to-file' );
2988 $errors = wfMergeErrorArrays( $errors,
2989 $this->getUserPermissionsErrors( 'move', $wgUser ),
2990 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2991 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2992 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2995 $match = EditPage
::matchSummarySpamRegex( $reason );
2996 if ( $match !== false ) {
2997 // This is kind of lame, won't display nice
2998 $errors[] = array( 'spamprotectiontext' );
3002 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3003 $errors[] = array( 'hookaborted', $err );
3006 # The move is allowed only if (1) the target doesn't exist, or
3007 # (2) the target is a redirect to the source, and has no history
3008 # (so we can undo bad moves right after they're done).
3010 if ( 0 != $newid ) { # Target exists; check for validity
3011 if ( !$this->isValidMoveTarget( $nt ) ) {
3012 $errors[] = array( 'articleexists' );
3015 $tp = $nt->getTitleProtection();
3016 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3017 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3018 $errors[] = array( 'cantmove-titleprotected' );
3021 if ( empty( $errors ) ) {
3028 * Check if the requested move target is a valid file move target
3029 * @param Title $nt Target title
3030 * @return array List of errors
3032 protected function validateFileMoveOperation( $nt ) {
3037 if ( $nt->getNamespace() != NS_FILE
) {
3038 $errors[] = array( 'imagenocrossnamespace' );
3041 $file = wfLocalFile( $this );
3042 if ( $file->exists() ) {
3043 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3044 $errors[] = array( 'imageinvalidfilename' );
3046 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3047 $errors[] = array( 'imagetypemismatch' );
3051 $destFile = wfLocalFile( $nt );
3052 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3053 $errors[] = array( 'file-exists-sharedrepo' );
3060 * Move a title to a new location
3062 * @param $nt Title the new title
3063 * @param $auth Bool indicates whether $wgUser's permissions
3065 * @param $reason String the reason for the move
3066 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3067 * Ignored if the user doesn't have the suppressredirect right.
3068 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3070 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3071 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3072 if ( is_array( $err ) ) {
3076 // If it is a file, move it first. It is done before all other moving stuff is
3077 // done because it's hard to revert
3078 $dbw = wfGetDB( DB_MASTER
);
3079 if ( $this->getNamespace() == NS_FILE
) {
3080 $file = wfLocalFile( $this );
3081 if ( $file->exists() ) {
3082 $status = $file->move( $nt );
3083 if ( !$status->isOk() ) {
3084 return $status->getErrorsArray();
3089 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3090 $pageid = $this->getArticleID( GAID_FOR_UPDATE
);
3091 $protected = $this->isProtected();
3092 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3094 // Do the actual move
3095 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3096 if ( is_array( $err ) ) {
3097 # FIXME: What about the File we have already moved?
3102 $redirid = $this->getArticleID();
3104 // Refresh the sortkey for this row. Be careful to avoid resetting
3105 // cl_timestamp, which may disturb time-based lists on some sites.
3106 $prefixes = $dbw->select(
3108 array( 'cl_sortkey_prefix', 'cl_to' ),
3109 array( 'cl_from' => $pageid ),
3112 foreach ( $prefixes as $prefixRow ) {
3113 $prefix = $prefixRow->cl_sortkey_prefix
;
3114 $catTo = $prefixRow->cl_to
;
3115 $dbw->update( 'categorylinks',
3117 'cl_sortkey' => Collation
::singleton()->getSortKey(
3118 $nt->getCategorySortkey( $prefix ) ),
3119 'cl_timestamp=cl_timestamp' ),
3121 'cl_from' => $pageid,
3122 'cl_to' => $catTo ),
3128 # Protect the redirect title as the title used to be...
3129 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3131 'pr_page' => $redirid,
3132 'pr_type' => 'pr_type',
3133 'pr_level' => 'pr_level',
3134 'pr_cascade' => 'pr_cascade',
3135 'pr_user' => 'pr_user',
3136 'pr_expiry' => 'pr_expiry'
3138 array( 'pr_page' => $pageid ),
3142 # Update the protection log
3143 $log = new LogPage( 'protect' );
3144 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3146 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3148 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3152 $oldnamespace = $this->getNamespace() & ~
1;
3153 $newnamespace = $nt->getNamespace() & ~
1;
3154 $oldtitle = $this->getDBkey();
3155 $newtitle = $nt->getDBkey();
3157 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3158 WatchedItem
::duplicateEntries( $this, $nt );
3161 # Update search engine
3162 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3164 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3170 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3171 # No longer a content page
3172 # Not viewed, edited, removing
3173 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3174 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3175 # Now a content page
3176 # Not viewed, edited, adding
3177 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3178 } elseif ( $pageCountChange ) {
3180 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3188 # Update message cache for interface messages
3189 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3190 # @bug 17860: old article can be deleted, if this the case,
3191 # delete it from message cache
3192 if ( $this->getArticleID() === 0 ) {
3193 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3195 $oldarticle = new Article( $this );
3196 MessageCache
::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3199 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3200 $newarticle = new Article( $nt );
3201 MessageCache
::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3205 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3210 * Move page to a title which is either a redirect to the
3211 * source page or nonexistent
3213 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3214 * @param $reason String The reason for the move
3215 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3216 * if the user doesn't have the suppressredirect right
3218 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3219 global $wgUser, $wgContLang;
3221 $moveOverRedirect = $nt->exists();
3223 $commentMsg = ( $moveOverRedirect ?
'1movedto2_redir' : '1movedto2' );
3224 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3227 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3229 # Truncate for whole multibyte characters.
3230 $comment = $wgContLang->truncate( $comment, 255 );
3232 $oldid = $this->getArticleID();
3233 $latest = $this->getLatestRevID();
3235 $oldns = $this->getNamespace();
3236 $olddbk = $this->getDBkey();
3238 $dbw = wfGetDB( DB_MASTER
);
3240 if ( $moveOverRedirect ) {
3241 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3243 $newid = $nt->getArticleID();
3244 $newns = $nt->getNamespace();
3245 $newdbk = $nt->getDBkey();
3247 # Delete the old redirect. We don't save it to history since
3248 # by definition if we've got here it's rather uninteresting.
3249 # We have to remove it so that the next step doesn't trigger
3250 # a conflict on the unique namespace+title index...
3251 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3252 if ( !$dbw->cascadingDeletes() ) {
3253 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3254 global $wgUseTrackbacks;
3255 if ( $wgUseTrackbacks ) {
3256 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3258 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3259 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3260 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3261 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3262 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3263 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3264 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3266 // If the target page was recently created, it may have an entry in recentchanges still
3267 $dbw->delete( 'recentchanges',
3268 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3273 # Save a null revision in the page's history notifying of the move
3274 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3275 if ( !is_object( $nullRevision ) ) {
3276 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3278 $nullRevId = $nullRevision->insertOn( $dbw );
3280 $article = new Article( $this );
3281 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3283 # Change the name of the target page:
3284 $dbw->update( 'page',
3286 'page_touched' => $dbw->timestamp(),
3287 'page_namespace' => $nt->getNamespace(),
3288 'page_title' => $nt->getDBkey(),
3289 'page_latest' => $nullRevId,
3291 /* WHERE */ array( 'page_id' => $oldid ),
3294 $nt->resetArticleID( $oldid );
3296 # Recreate the redirect, this time in the other direction.
3297 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3298 $mwRedir = MagicWord
::get( 'redirect' );
3299 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3300 $redirectArticle = new Article( $this );
3301 $newid = $redirectArticle->insertOn( $dbw );
3302 $redirectRevision = new Revision( array(
3304 'comment' => $comment,
3305 'text' => $redirectText ) );
3306 $redirectRevision->insertOn( $dbw );
3307 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3309 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3311 # Now, we record the link from the redirect to the new title.
3312 # It should have no other outgoing links...
3313 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3314 $dbw->insert( 'pagelinks',
3316 'pl_from' => $newid,
3317 'pl_namespace' => $nt->getNamespace(),
3318 'pl_title' => $nt->getDBkey() ),
3320 $redirectSuppressed = false;
3322 // Get rid of old new page entries in Special:NewPages and RC.
3323 // Needs to be before $this->resetArticleID( 0 ).
3324 $dbw->delete( 'recentchanges', array(
3325 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3326 'rc_namespace' => $oldns,
3327 'rc_title' => $olddbk,
3333 $this->resetArticleID( 0 );
3334 $redirectSuppressed = true;
3338 $log = new LogPage( 'move' );
3339 $logType = ( $moveOverRedirect ?
'move_redir' : 'move' );
3340 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3342 # Purge caches for old and new titles
3343 if ( $moveOverRedirect ) {
3344 # A simple purge is enough when moving over a redirect
3347 # Purge caches as per article creation, including any pages that link to this title
3348 Article
::onArticleCreate( $nt );
3350 $this->purgeSquid();
3354 * Move this page's subpages to be subpages of $nt
3356 * @param $nt Title Move target
3357 * @param $auth bool Whether $wgUser's permissions should be checked
3358 * @param $reason string The reason for the move
3359 * @param $createRedirect bool Whether to create redirects from the old subpages to
3360 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3361 * @return mixed array with old page titles as keys, and strings (new page titles) or
3362 * arrays (errors) as values, or an error array with numeric indices if no pages
3365 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3366 global $wgMaximumMovedPages;
3367 // Check permissions
3368 if ( !$this->userCan( 'move-subpages' ) ) {
3369 return array( 'cant-move-subpages' );
3371 // Do the source and target namespaces support subpages?
3372 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3373 return array( 'namespace-nosubpages',
3374 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3376 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3377 return array( 'namespace-nosubpages',
3378 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3381 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3384 foreach ( $subpages as $oldSubpage ) {
3386 if ( $count > $wgMaximumMovedPages ) {
3387 $retval[$oldSubpage->getPrefixedTitle()] =
3388 array( 'movepage-max-pages',
3389 $wgMaximumMovedPages );
3393 // We don't know whether this function was called before
3394 // or after moving the root page, so check both
3396 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3397 $oldSubpage->getArticleID() == $nt->getArticleId() )
3399 // When moving a page to a subpage of itself,
3400 // don't move it twice
3403 $newPageName = preg_replace(
3404 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3405 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3406 $oldSubpage->getDBkey() );
3407 if ( $oldSubpage->isTalkPage() ) {
3408 $newNs = $nt->getTalkPage()->getNamespace();
3410 $newNs = $nt->getSubjectPage()->getNamespace();
3412 # Bug 14385: we need makeTitleSafe because the new page names may
3413 # be longer than 255 characters.
3414 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3416 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3417 if ( $success === true ) {
3418 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3420 $retval[$oldSubpage->getPrefixedText()] = $success;
3427 * Checks if this page is just a one-rev redirect.
3428 * Adds lock, so don't use just for light purposes.
3432 public function isSingleRevRedirect() {
3433 $dbw = wfGetDB( DB_MASTER
);
3435 $row = $dbw->selectRow( 'page',
3436 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3439 array( 'FOR UPDATE' )
3441 # Cache some fields we may want
3442 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3443 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3444 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3445 if ( !$this->mRedirect
) {
3448 # Does the article have a history?
3449 $row = $dbw->selectField( array( 'page', 'revision' ),
3451 array( 'page_namespace' => $this->getNamespace(),
3452 'page_title' => $this->getDBkey(),
3454 'page_latest != rev_id'
3457 array( 'FOR UPDATE' )
3459 # Return true if there was no history
3460 return ( $row === false );
3464 * Checks if $this can be moved to a given Title
3465 * - Selects for update, so don't call it unless you mean business
3467 * @param $nt Title the new title to check
3470 public function isValidMoveTarget( $nt ) {
3471 # Is it an existing file?
3472 if ( $nt->getNamespace() == NS_FILE
) {
3473 $file = wfLocalFile( $nt );
3474 if ( $file->exists() ) {
3475 wfDebug( __METHOD__
. ": file exists\n" );
3479 # Is it a redirect with no history?
3480 if ( !$nt->isSingleRevRedirect() ) {
3481 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3484 # Get the article text
3485 $rev = Revision
::newFromTitle( $nt );
3486 $text = $rev->getText();
3487 # Does the redirect point to the source?
3488 # Or is it a broken self-redirect, usually caused by namespace collisions?
3490 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3491 $redirTitle = Title
::newFromText( $m[1] );
3492 if ( !is_object( $redirTitle ) ||
3493 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3494 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3495 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3500 wfDebug( __METHOD__
. ": failsafe\n" );
3507 * Can this title be added to a user's watchlist?
3509 * @return Bool TRUE or FALSE
3511 public function isWatchable() {
3512 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3516 * Get categories to which this Title belongs and return an array of
3517 * categories' names.
3519 * @return Array of parents in the form:
3520 * $parent => $currentarticle
3522 public function getParentCategories() {
3527 $titleKey = $this->getArticleId();
3529 if ( $titleKey === 0 ) {
3533 $dbr = wfGetDB( DB_SLAVE
);
3535 $res = $dbr->select( 'categorylinks', '*',
3537 'cl_from' => $titleKey,
3543 if ( $dbr->numRows( $res ) > 0 ) {
3544 foreach ( $res as $row ) {
3545 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3546 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3553 * Get a tree of parent categories
3555 * @param $children Array with the children in the keys, to check for circular refs
3556 * @return Array Tree of parent categories
3558 public function getParentCategoryTree( $children = array() ) {
3560 $parents = $this->getParentCategories();
3563 foreach ( $parents as $parent => $current ) {
3564 if ( array_key_exists( $parent, $children ) ) {
3565 # Circular reference
3566 $stack[$parent] = array();
3568 $nt = Title
::newFromText( $parent );
3570 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3580 * Get an associative array for selecting this title from
3583 * @return Array suitable for the $where parameter of DB::select()
3585 public function pageCond() {
3586 if ( $this->mArticleID
> 0 ) {
3587 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3588 return array( 'page_id' => $this->mArticleID
);
3590 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3595 * Get the revision ID of the previous revision
3597 * @param $revId Int Revision ID. Get the revision that was before this one.
3598 * @param $flags Int Title::GAID_FOR_UPDATE
3599 * @return Int|Bool Old revision ID, or FALSE if none exists
3601 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3602 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3603 return $db->selectField( 'revision', 'rev_id',
3605 'rev_page' => $this->getArticleId( $flags ),
3606 'rev_id < ' . intval( $revId )
3609 array( 'ORDER BY' => 'rev_id DESC' )
3614 * Get the revision ID of the next revision
3616 * @param $revId Int Revision ID. Get the revision that was after this one.
3617 * @param $flags Int Title::GAID_FOR_UPDATE
3618 * @return Int|Bool Next revision ID, or FALSE if none exists
3620 public function getNextRevisionID( $revId, $flags = 0 ) {
3621 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3622 return $db->selectField( 'revision', 'rev_id',
3624 'rev_page' => $this->getArticleId( $flags ),
3625 'rev_id > ' . intval( $revId )
3628 array( 'ORDER BY' => 'rev_id' )
3633 * Get the first revision of the page
3635 * @param $flags Int Title::GAID_FOR_UPDATE
3636 * @return Revision|Null if page doesn't exist
3638 public function getFirstRevision( $flags = 0 ) {
3639 $pageId = $this->getArticleId( $flags );
3641 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3642 $row = $db->selectRow( 'revision', '*',
3643 array( 'rev_page' => $pageId ),
3645 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3648 return new Revision( $row );
3655 * Get the oldest revision timestamp of this page
3657 * @param $flags Int Title::GAID_FOR_UPDATE
3658 * @return String: MW timestamp
3660 public function getEarliestRevTime( $flags = 0 ) {
3661 $rev = $this->getFirstRevision( $flags );
3662 return $rev ?
$rev->getTimestamp() : null;
3666 * Check if this is a new page
3670 public function isNewPage() {
3671 $dbr = wfGetDB( DB_SLAVE
);
3672 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3676 * Get the number of revisions between the given revision.
3677 * Used for diffs and other things that really need it.
3679 * @param $old int|Revision Old revision or rev ID (first before range)
3680 * @param $new int|Revision New revision or rev ID (first after range)
3681 * @return Int Number of revisions between these revisions.
3683 public function countRevisionsBetween( $old, $new ) {
3684 if ( !( $old instanceof Revision
) ) {
3685 $old = Revision
::newFromTitle( $this, (int)$old );
3687 if ( !( $new instanceof Revision
) ) {
3688 $new = Revision
::newFromTitle( $this, (int)$new );
3690 if ( !$old ||
!$new ) {
3691 return 0; // nothing to compare
3693 $dbr = wfGetDB( DB_SLAVE
);
3694 return (int)$dbr->selectField( 'revision', 'count(*)',
3696 'rev_page' => $this->getArticleId(),
3697 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3698 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3705 * Get the number of authors between the given revision IDs.
3706 * Used for diffs and other things that really need it.
3708 * @param $old int|Revision Old revision or rev ID (first before range)
3709 * @param $new int|Revision New revision or rev ID (first after range)
3710 * @param $limit Int Maximum number of authors
3711 * @return Int Number of revision authors between these revisions.
3713 public function countAuthorsBetween( $old, $new, $limit ) {
3714 if ( !( $old instanceof Revision
) ) {
3715 $old = Revision
::newFromTitle( $this, (int)$old );
3717 if ( !( $new instanceof Revision
) ) {
3718 $new = Revision
::newFromTitle( $this, (int)$new );
3720 if ( !$old ||
!$new ) {
3721 return 0; // nothing to compare
3723 $dbr = wfGetDB( DB_SLAVE
);
3724 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3726 'rev_page' => $this->getArticleID(),
3727 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3728 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3730 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3732 return (int)$dbr->numRows( $res );
3736 * Compare with another title.
3738 * @param $title Title
3741 public function equals( Title
$title ) {
3742 // Note: === is necessary for proper matching of number-like titles.
3743 return $this->getInterwiki() === $title->getInterwiki()
3744 && $this->getNamespace() == $title->getNamespace()
3745 && $this->getDBkey() === $title->getDBkey();
3749 * Callback for usort() to do title sorts by (namespace, title)
3754 * @return Integer: result of string comparison, or namespace comparison
3756 public static function compare( $a, $b ) {
3757 if ( $a->getNamespace() == $b->getNamespace() ) {
3758 return strcmp( $a->getText(), $b->getText() );
3760 return $a->getNamespace() - $b->getNamespace();
3765 * Return a string representation of this title
3767 * @return String representation of this title
3769 public function __toString() {
3770 return $this->getPrefixedText();
3774 * Check if page exists. For historical reasons, this function simply
3775 * checks for the existence of the title in the page table, and will
3776 * thus return false for interwiki links, special pages and the like.
3777 * If you want to know if a title can be meaningfully viewed, you should
3778 * probably call the isKnown() method instead.
3782 public function exists() {
3783 return $this->getArticleId() != 0;
3787 * Should links to this title be shown as potentially viewable (i.e. as
3788 * "bluelinks"), even if there's no record by this title in the page
3791 * This function is semi-deprecated for public use, as well as somewhat
3792 * misleadingly named. You probably just want to call isKnown(), which
3793 * calls this function internally.
3795 * (ISSUE: Most of these checks are cheap, but the file existence check
3796 * can potentially be quite expensive. Including it here fixes a lot of
3797 * existing code, but we might want to add an optional parameter to skip
3798 * it and any other expensive checks.)
3802 public function isAlwaysKnown() {
3803 if ( $this->mInterwiki
!= '' ) {
3804 return true; // any interwiki link might be viewable, for all we know
3806 switch( $this->mNamespace
) {
3809 // file exists, possibly in a foreign repo
3810 return (bool)wfFindFile( $this );
3812 // valid special page
3813 return SpecialPageFactory
::exists( $this->getDBkey() );
3815 // selflink, possibly with fragment
3816 return $this->mDbkeyform
== '';
3818 // known system message
3819 return $this->getDefaultMessageText() !== false;
3826 * Does this title refer to a page that can (or might) be meaningfully
3827 * viewed? In particular, this function may be used to determine if
3828 * links to the title should be rendered as "bluelinks" (as opposed to
3829 * "redlinks" to non-existent pages).
3833 public function isKnown() {
3834 return $this->isAlwaysKnown() ||
$this->exists();
3838 * Does this page have source text?
3842 public function hasSourceText() {
3843 if ( $this->exists() ) {
3847 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3848 // If the page doesn't exist but is a known system message, default
3849 // message content will be displayed, same for language subpages
3850 return $this->getDefaultMessageText() !== false;
3857 * Get the default message text or false if the message doesn't exist
3859 * @return String or false
3861 public function getDefaultMessageText() {
3864 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
3868 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3869 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3871 if ( $message->exists() ) {
3872 return $message->plain();
3879 * Is this in a namespace that allows actual pages?
3882 * @internal note -- uses hardcoded namespace index instead of constants
3884 public function canExist() {
3885 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3889 * Update page_touched timestamps and send squid purge messages for
3890 * pages linking to this title. May be sent to the job queue depending
3891 * on the number of links. Typically called on create and delete.
3893 public function touchLinks() {
3894 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3897 if ( $this->getNamespace() == NS_CATEGORY
) {
3898 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3904 * Get the last touched timestamp
3906 * @param $db DatabaseBase: optional db
3907 * @return String last-touched timestamp
3909 public function getTouched( $db = null ) {
3910 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
3911 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3916 * Get the timestamp when this page was updated since the user last saw it.
3919 * @return String|Null
3921 public function getNotificationTimestamp( $user = null ) {
3922 global $wgUser, $wgShowUpdatedMarker;
3923 // Assume current user if none given
3927 // Check cache first
3928 $uid = $user->getId();
3929 // avoid isset here, as it'll return false for null entries
3930 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
3931 return $this->mNotificationTimestamp
[$uid];
3933 if ( !$uid ||
!$wgShowUpdatedMarker ) {
3934 return $this->mNotificationTimestamp
[$uid] = false;
3936 // Don't cache too much!
3937 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3938 $this->mNotificationTimestamp
= array();
3940 $dbr = wfGetDB( DB_SLAVE
);
3941 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3942 'wl_notificationtimestamp',
3943 array( 'wl_namespace' => $this->getNamespace(),
3944 'wl_title' => $this->getDBkey(),
3945 'wl_user' => $user->getId()
3949 return $this->mNotificationTimestamp
[$uid];
3953 * Get the trackback URL for this page
3955 * @return String Trackback URL
3957 public function trackbackURL() {
3958 global $wgScriptPath, $wgServer, $wgScriptExtension;
3960 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3961 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3965 * Get the trackback RDF for this page
3967 * @return String Trackback RDF
3969 public function trackbackRDF() {
3970 $url = htmlspecialchars( $this->getFullURL() );
3971 $title = htmlspecialchars( $this->getText() );
3972 $tburl = $this->trackbackURL();
3974 // Autodiscovery RDF is placed in comments so HTML validator
3975 // won't barf. This is a rather icky workaround, but seems
3976 // frequently used by this kind of RDF thingy.
3978 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3980 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3981 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3982 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3985 dc:identifier=\"$url\"
3987 trackback:ping=\"$tburl\" />
3993 * Generate strings used for xml 'id' names in monobook tabs
3995 * @param $prepend string defaults to 'nstab-'
3996 * @return String XML 'id' name
3998 public function getNamespaceKey( $prepend = 'nstab-' ) {
4000 // Gets the subject namespace if this title
4001 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4002 // Checks if cononical namespace name exists for namespace
4003 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4004 // Uses canonical namespace name
4005 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4007 // Uses text of namespace
4008 $namespaceKey = $this->getSubjectNsText();
4010 // Makes namespace key lowercase
4011 $namespaceKey = $wgContLang->lc( $namespaceKey );
4013 if ( $namespaceKey == '' ) {
4014 $namespaceKey = 'main';
4016 // Changes file to image for backwards compatibility
4017 if ( $namespaceKey == 'file' ) {
4018 $namespaceKey = 'image';
4020 return $prepend . $namespaceKey;
4024 * Returns true if this is a special page.
4028 public function isSpecialPage() {
4029 return $this->getNamespace() == NS_SPECIAL
;
4033 * Returns true if this title resolves to the named special page
4035 * @param $name String The special page name
4038 public function isSpecial( $name ) {
4039 if ( $this->getNamespace() == NS_SPECIAL
) {
4040 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4041 if ( $name == $thisName ) {
4049 * If the Title refers to a special page alias which is not the local default, resolve
4050 * the alias, and localise the name as necessary. Otherwise, return $this
4054 public function fixSpecialName() {
4055 if ( $this->getNamespace() == NS_SPECIAL
) {
4056 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4057 if ( $canonicalName ) {
4058 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName );
4059 if ( $localName != $this->mDbkeyform
) {
4060 return Title
::makeTitle( NS_SPECIAL
, $localName );
4068 * Is this Title in a namespace which contains content?
4069 * In other words, is this a content page, for the purposes of calculating
4074 public function isContentPage() {
4075 return MWNamespace
::isContent( $this->getNamespace() );
4079 * Get all extant redirects to this Title
4081 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4082 * @return Array of Title redirects to this title
4084 public function getRedirectsHere( $ns = null ) {
4087 $dbr = wfGetDB( DB_SLAVE
);
4089 'rd_namespace' => $this->getNamespace(),
4090 'rd_title' => $this->getDBkey(),
4093 if ( !is_null( $ns ) ) {
4094 $where['page_namespace'] = $ns;
4097 $res = $dbr->select(
4098 array( 'redirect', 'page' ),
4099 array( 'page_namespace', 'page_title' ),
4104 foreach ( $res as $row ) {
4105 $redirs[] = self
::newFromRow( $row );
4111 * Check if this Title is a valid redirect target
4115 public function isValidRedirectTarget() {
4116 global $wgInvalidRedirectTargets;
4118 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4119 if ( $this->isSpecial( 'Userlogout' ) ) {
4123 foreach ( $wgInvalidRedirectTargets as $target ) {
4124 if ( $this->isSpecial( $target ) ) {
4133 * Get a backlink cache object
4135 * @return object BacklinkCache
4137 function getBacklinkCache() {
4138 if ( is_null( $this->mBacklinkCache
) ) {
4139 $this->mBacklinkCache
= new BacklinkCache( $this );
4141 return $this->mBacklinkCache
;
4145 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4149 public function canUseNoindex() {
4150 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4152 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4153 ?
$wgContentNamespaces
4154 : $wgExemptFromUserRobotsControl;
4156 return !in_array( $this->mNamespace
, $bannedNamespaces );
4161 * Returns restriction types for the current Title
4163 * @return array applicable restriction types
4165 public function getRestrictionTypes() {
4166 if ( $this->getNamespace() == NS_SPECIAL
) {
4170 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4172 if ( $this->getNamespace() != NS_FILE
) {
4173 # Remove the upload restriction for non-file titles
4174 $types = array_diff( $types, array( 'upload' ) );
4177 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4179 wfDebug( __METHOD__
. ': applicable restriction types for ' .
4180 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4185 * Get a filtered list of all restriction types supported by this wiki.
4186 * @param bool $exists True to get all restriction types that apply to
4187 * titles that do exist, False for all restriction types that apply to
4188 * titles that do not exist
4191 public static function getFilteredRestrictionTypes( $exists = true ) {
4192 global $wgRestrictionTypes;
4193 $types = $wgRestrictionTypes;
4195 # Remove the create restriction for existing titles
4196 $types = array_diff( $types, array( 'create' ) );
4198 # Only the create and upload restrictions apply to non-existing titles
4199 $types = array_intersect( $types, array( 'create', 'upload' ) );
4205 * Returns the raw sort key to be used for categories, with the specified
4206 * prefix. This will be fed to Collation::getSortKey() to get a
4207 * binary sortkey that can be used for actual sorting.
4209 * @param $prefix string The prefix to be used, specified using
4210 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4214 public function getCategorySortkey( $prefix = '' ) {
4215 $unprefixed = $this->getText();
4216 if ( $prefix !== '' ) {
4217 # Separate with a line feed, so the unprefixed part is only used as
4218 # a tiebreaker when two pages have the exact same prefix.
4219 # In UCA, tab is the only character that can sort above LF
4220 # so we strip both of them from the original prefix.
4221 $prefix = strtr( $prefix, "\n\t", ' ' );
4222 return "$prefix\n$unprefixed";
4229 * A BadTitle is generated in MediaWiki::parseTitle() if the title is invalid; the
4230 * software uses this to display an error page. Internally it's basically a Title
4231 * for an empty special page
4233 class BadTitle
extends Title
{
4234 public function __construct(){
4235 $this->mTextform
= '';
4236 $this->mUrlform
= '';
4237 $this->mDbkeyform
= '';
4238 $this->mNamespace
= NS_SPECIAL
; // Stops talk page link, etc, being shown
4241 public function exists(){
4245 public function getPrefixedText(){
4249 public function getText(){
4253 public function getPrefixedURL(){
4257 public function getPrefixedDBKey(){