8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
16 define ( 'GAID_FOR_UPDATE', 1 );
19 * Represents a title within MediaWiki.
20 * Optionally may contain an interwiki designation or namespace.
21 * @note This class can fetch various kinds of data from the database;
22 * however, it does so inefficiently.
24 * @internal documentation reviewed 15 Mar 2010
27 /** @name Static cache variables */
29 static private $titleCache=array();
30 static private $interwikiCache=array();
34 * Title::newFromText maintains a cache to avoid expensive re-normalization of
35 * commonly used titles. On a batch operation this can become a memory leak
36 * if not bounded. After hitting this many titles reset the cache.
38 const CACHE_MAX
= 1000;
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 of getTitleProtection
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
83 /* private */ function __construct() {}
86 * Create a new Title from a prefixed DB key
88 * @param $key \type{\string} The database key, which has underscores
89 * instead of spaces, possibly including namespace and
91 * @return \type{Title} the new object, or NULL on an error
93 public static function newFromDBkey( $key ) {
95 $t->mDbkeyform
= $key;
96 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 The new object, 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];
132 * Convert things like é ā or 〗 into normalized(bug 14952) text
134 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
137 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
138 $t->mDefaultNamespace
= $defaultNamespace;
140 static $cachedcount = 0 ;
141 if( $t->secureAndSplit() ) {
142 if( $defaultNamespace == NS_MAIN
) {
143 if( $cachedcount >= self
::CACHE_MAX
) {
144 # Avoid memory leaks on mass operations...
145 Title
::$titleCache = array();
149 Title
::$titleCache[$text] =& $t;
159 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
161 * Example of wrong and broken code:
162 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
164 * Example of right code:
165 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
167 * Create a new Title from URL-encoded text. Ensures that
168 * the given title's length does not exceed the maximum.
170 * @param $url \type{\string} the title, as might be taken from a URL
171 * @return \type{Title} the new object, or NULL on an error
173 public static function newFromURL( $url ) {
174 global $wgLegalTitleChars;
177 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
178 # but some URLs used it as a space replacement and they still come
179 # from some external search tools.
180 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
181 $url = str_replace( '+', ' ', $url );
184 $t->mDbkeyform
= str_replace( ' ', '_', $url );
185 if( $t->secureAndSplit() ) {
193 * Create a new Title from an article ID
195 * @param $id \type{\int} the page_id corresponding to the Title to create
196 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
197 * @return \type{Title} the new object, or NULL on an error
199 public static function newFromID( $id, $flags = 0 ) {
200 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
201 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
202 if( $row !== false ) {
203 $title = Title
::newFromRow( $row );
211 * Make an array of titles from an array of IDs
213 * @param $ids \type{\arrayof{\int}} Array of IDs
214 * @return \type{\arrayof{Title}} Array of Titles
216 public static function newFromIDs( $ids ) {
217 if ( !count( $ids ) ) {
220 $dbr = wfGetDB( DB_SLAVE
);
221 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
222 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
225 foreach( $res as $row ) {
226 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
232 * Make a Title object from a DB row
234 * @param $row \type{Row} (needs at least page_title,page_namespace)
235 * @return \type{Title} corresponding Title
237 public static function newFromRow( $row ) {
238 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
240 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
241 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
242 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
243 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
249 * Create a new Title from a namespace index and a DB key.
250 * It's assumed that $ns and $title are *valid*, for instance when
251 * they came directly from the database or a special page name.
252 * For convenience, spaces are converted to underscores so that
253 * eg user_text fields can be used directly.
255 * @param $ns \type{\int} the namespace of the article
256 * @param $title \type{\string} the unprefixed database key form
257 * @param $fragment \type{\string} The link fragment (after the "#")
258 * @return \type{Title} the new object
260 public static function &makeTitle( $ns, $title, $fragment = '' ) {
263 $t->mFragment
= $fragment;
264 $t->mNamespace
= $ns = intval( $ns );
265 $t->mDbkeyform
= str_replace( ' ', '_', $title );
266 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
267 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
268 $t->mTextform
= str_replace( '_', ' ', $title );
273 * Create a new Title from a namespace index and a DB key.
274 * The parameters will be checked for validity, which is a bit slower
275 * than makeTitle() but safer for user-provided data.
277 * @param $ns \type{\int} the namespace of the article
278 * @param $title \type{\string} the database key form
279 * @param $fragment \type{\string} The link fragment (after the "#")
280 * @return \type{Title} the new object, or NULL on an error
282 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
284 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
285 if( $t->secureAndSplit() ) {
293 * Create a new Title for the Main Page
295 * @return \type{Title} the new object
297 public static function newMainPage() {
298 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
299 // Don't give fatal errors if the message is broken
301 $title = Title
::newFromText( 'Main Page' );
307 * Extract a redirect destination from a string and return the
308 * Title, or null if the text doesn't contain a valid redirect
309 * This will only return the very next target, useful for
310 * the redirect table and other checks that don't need full recursion
312 * @param $text \type{\string} Text with possible redirect
313 * @return \type{Title} The corresponding Title
315 public static function newFromRedirect( $text ) {
316 return self
::newFromRedirectInternal( $text );
320 * Extract a redirect destination from a string and return the
321 * Title, or null if the text doesn't contain a valid redirect
322 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
323 * in order to provide (hopefully) the Title of the final destination instead of another redirect
325 * @param $text \type{\string} Text with possible redirect
326 * @return \type{Title} The corresponding Title
328 public static function newFromRedirectRecurse( $text ) {
329 $titles = self
::newFromRedirectArray( $text );
330 return $titles ?
array_pop( $titles ) : null;
334 * Extract a redirect destination from a string and return an
335 * array of Titles, or null if the text doesn't contain a valid redirect
336 * The last element in the array is the final destination after all redirects
337 * have been resolved (up to $wgMaxRedirects times)
339 * @param $text \type{\string} Text with possible redirect
340 * @return \type{\array} Array of Titles, with the destination last
342 public static function newFromRedirectArray( $text ) {
343 global $wgMaxRedirects;
344 // are redirects disabled?
345 if( $wgMaxRedirects < 1 )
347 $title = self
::newFromRedirectInternal( $text );
348 if( is_null( $title ) )
350 // recursive check to follow double redirects
351 $recurse = $wgMaxRedirects;
352 $titles = array( $title );
353 while( --$recurse > 0 ) {
354 if( $title->isRedirect() ) {
355 $article = new Article( $title, 0 );
356 $newtitle = $article->getRedirectTarget();
360 // Redirects to some special pages are not permitted
361 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
362 // the new title passes the checks, so make that our current title so that further recursion can be checked
364 $titles[] = $newtitle;
373 * Really extract the redirect destination
374 * Do not call this function directly, use one of the newFromRedirect* functions above
376 * @param $text \type{\string} Text with possible redirect
377 * @return \type{Title} The corresponding Title
379 protected static function newFromRedirectInternal( $text ) {
380 $redir = MagicWord
::get( 'redirect' );
382 if( $redir->matchStartAndRemove( $text ) ) {
383 // Extract the first link and see if it's usable
384 // Ensure that it really does come directly after #REDIRECT
385 // Some older redirects included a colon, so don't freak about that!
387 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
388 // Strip preceding colon used to "escape" categories, etc.
389 // and URL-decode links
390 if( strpos( $m[1], '%' ) !== false ) {
391 // Match behavior of inline link parsing here;
392 // don't interpret + as " " most of the time!
393 // It might be safe to just use rawurldecode instead, though.
394 $m[1] = urldecode( ltrim( $m[1], ':' ) );
396 $title = Title
::newFromText( $m[1] );
397 // If the title is a redirect to bad special pages or is invalid, return null
398 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
407 #----------------------------------------------------------------------------
409 #----------------------------------------------------------------------------
412 * Get the prefixed DB key associated with an ID
414 * @param $id \type{\int} the page_id of the article
415 * @return \type{Title} an object representing the article, or NULL
416 * if no such article was found
418 public static function nameOf( $id ) {
419 $dbr = wfGetDB( DB_SLAVE
);
421 $s = $dbr->selectRow( 'page',
422 array( 'page_namespace','page_title' ),
423 array( 'page_id' => $id ),
425 if ( $s === false ) { return null; }
427 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
432 * Get a regex character class describing the legal characters in a link
434 * @return \type{\string} the list of characters, not delimited
436 public static function legalChars() {
437 global $wgLegalTitleChars;
438 return $wgLegalTitleChars;
442 * Get a string representation of a title suitable for
443 * including in a search index
445 * @param $ns \type{\int} a namespace index
446 * @param $title \type{\string} text-form main part
447 * @return \type{\string} a stripped-down title string ready for the
450 public static function indexTitle( $ns, $title ) {
453 $lc = SearchEngine
::legalSearchChars() . '&#;';
454 $t = $wgContLang->normalizeForSearch( $title );
455 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
456 $t = $wgContLang->lc( $t );
459 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
460 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
462 $t = preg_replace( "/\\s+/", ' ', $t );
464 if ( $ns == NS_FILE
) {
465 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
471 * Make a prefixed DB key from a DB key and a namespace index
473 * @param $ns \type{\int} numerical representation of the namespace
474 * @param $title \type{\string} the DB key form the title
475 * @param $fragment \type{\string} The link fragment (after the "#")
476 * @return \type{\string} the prefixed form of the title
478 public static function makeName( $ns, $title, $fragment = '' ) {
481 $namespace = $wgContLang->getNsText( $ns );
482 $name = $namespace == '' ?
$title : "$namespace:$title";
483 if ( strval( $fragment ) != '' ) {
484 $name .= '#' . $fragment;
490 * Determine whether the object refers to a page within
493 * @return \type{\bool} TRUE if this is an in-project interwiki link
494 * or a wikilink, FALSE otherwise
496 public function isLocal() {
497 if ( $this->mInterwiki
!= '' ) {
498 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
505 * Determine whether the object refers to a page within
506 * this project and is transcludable.
508 * @return \type{\bool} TRUE if this is transcludable
510 public function isTrans() {
511 if ($this->mInterwiki
== '')
514 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
518 * Escape a text fragment, say from a link, for a URL
520 * @param $fragment string containing a URL or link fragment (after the "#")
521 * @return String: escaped string
523 static function escapeFragmentForURL( $fragment ) {
524 # Note that we don't urlencode the fragment. urlencoded Unicode
525 # fragments appear not to work in IE (at least up to 7) or in at least
526 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
527 # to care if they aren't encoded.
528 return Sanitizer
::escapeId( $fragment, 'noninitial' );
531 #----------------------------------------------------------------------------
533 #----------------------------------------------------------------------------
535 /** Simple accessors */
537 * Get the text form (spaces not underscores) of the main part
539 * @return \type{\string} Main part of the title
541 public function getText() { return $this->mTextform
; }
544 * Get the URL-encoded form of the main part
546 * @return \type{\string} Main part of the title, URL-encoded
548 public function getPartialURL() { return $this->mUrlform
; }
551 * Get the main part with underscores
553 * @return \type{\string} Main part of the title, with underscores
555 public function getDBkey() { return $this->mDbkeyform
; }
558 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
560 * @return \type{\int} Namespace index
562 public function getNamespace() { return $this->mNamespace
; }
565 * Get the namespace text
567 * @return \type{\string} Namespace text
569 public function getNsText() {
572 if ( $this->mInterwiki
!= '' ) {
573 // This probably shouldn't even happen. ohh man, oh yuck.
574 // But for interwiki transclusion it sometimes does.
575 // Shit. Shit shit shit.
577 // Use the canonical namespaces if possible to try to
578 // resolve a foreign namespace.
579 if( MWNamespace
::exists( $this->mNamespace
) ) {
580 return MWNamespace
::getCanonicalName( $this->mNamespace
);
583 return $wgContLang->getNsText( $this->mNamespace
);
587 * Get the DB key with the initial letter case as specified by the user
589 * @return \type{\string} DB key
591 function getUserCaseDBKey() {
592 return $this->mUserCaseDBKey
;
596 * Get the namespace text of the subject (rather than talk) page
598 * @return \type{\string} Namespace text
600 public function getSubjectNsText() {
602 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
606 * Get the namespace text of the talk page
608 * @return \type{\string} Namespace text
610 public function getTalkNsText() {
612 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
616 * Could this title have a corresponding talk page?
618 * @return \type{\bool} TRUE or FALSE
620 public function canTalk() {
621 return( MWNamespace
::canTalk( $this->mNamespace
) );
625 * Get the interwiki prefix (or null string)
627 * @return \type{\string} Interwiki prefix
629 public function getInterwiki() { return $this->mInterwiki
; }
632 * Get the Title fragment (i.e.\ the bit after the #) in text form
634 * @return \type{\string} Title fragment
636 public function getFragment() { return $this->mFragment
; }
639 * Get the fragment in URL form, including the "#" character if there is one
640 * @return \type{\string} Fragment in URL form
642 public function getFragmentForURL() {
643 if ( $this->mFragment
== '' ) {
646 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
651 * Get the default namespace index, for when there is no namespace
653 * @return \type{\int} Default namespace index
655 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
658 * Get title for search index
660 * @return \type{\string} a stripped-down title string ready for the
663 public function getIndexTitle() {
664 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
668 * Get the prefixed database key form
670 * @return \type{\string} the prefixed title, with underscores and
671 * any interwiki and namespace prefixes
673 public function getPrefixedDBkey() {
674 $s = $this->prefix( $this->mDbkeyform
);
675 $s = str_replace( ' ', '_', $s );
680 * Get the prefixed title with spaces.
681 * This is the form usually used for display
683 * @return \type{\string} the prefixed title, with spaces
685 public function getPrefixedText() {
686 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
687 $s = $this->prefix( $this->mTextform
);
688 $s = str_replace( '_', ' ', $s );
689 $this->mPrefixedText
= $s;
691 return $this->mPrefixedText
;
695 * Get the prefixed title with spaces, plus any fragment
696 * (part beginning with '#')
698 * @return \type{\string} the prefixed title, with spaces and
699 * the fragment, including '#'
701 public function getFullText() {
702 $text = $this->getPrefixedText();
703 if( $this->mFragment
!= '' ) {
704 $text .= '#' . $this->mFragment
;
710 * Get the base name, i.e. the leftmost parts before the /
712 * @return \type{\string} Base name
714 public function getBaseText() {
715 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
716 return $this->getText();
719 $parts = explode( '/', $this->getText() );
720 # Don't discard the real title if there's no subpage involved
721 if( count( $parts ) > 1 )
722 unset( $parts[ count( $parts ) - 1 ] );
723 return implode( '/', $parts );
727 * Get the lowest-level subpage name, i.e. the rightmost part after /
729 * @return \type{\string} Subpage name
731 public function getSubpageText() {
732 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
733 return( $this->mTextform
);
735 $parts = explode( '/', $this->mTextform
);
736 return( $parts[ count( $parts ) - 1 ] );
740 * Get a URL-encoded form of the subpage text
742 * @return \type{\string} URL-encoded subpage name
744 public function getSubpageUrlForm() {
745 $text = $this->getSubpageText();
746 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
751 * Get a URL-encoded title (not an actual URL) including interwiki
753 * @return \type{\string} the URL-encoded form
755 public function getPrefixedURL() {
756 $s = $this->prefix( $this->mDbkeyform
);
757 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
762 * Get a real URL referring to this title, with interwiki link and
765 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
766 * links. Can be specified as an associative array as well, e.g.,
767 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
768 * @param $variant \type{\string} language variant of url (for sr, zh..)
769 * @return \type{\string} the URL
771 public function getFullURL( $query = '', $variant = false ) {
772 global $wgContLang, $wgServer, $wgRequest;
774 if( is_array( $query ) ) {
775 $query = wfArrayToCGI( $query );
778 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
780 $url = $this->getLocalURL( $query, $variant );
782 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
783 // Correct fix would be to move the prepending elsewhere.
784 if ($wgRequest->getVal('action') != 'render') {
785 $url = $wgServer . $url;
788 $baseUrl = $interwiki->getURL( );
790 $namespace = wfUrlencode( $this->getNsText() );
791 if ( $namespace != '' ) {
792 # Can this actually happen? Interwikis shouldn't be parsed.
793 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
796 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
797 $url = wfAppendQuery( $url, $query );
800 # Finally, add the fragment.
801 $url .= $this->getFragmentForURL();
803 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
808 * Get a URL with no fragment or server name. If this page is generated
809 * with action=render, $wgServer is prepended.
811 * @param $query Mixed: an optional query string; if not specified,
812 * $wgArticlePath will be used. Can be specified as an associative array
813 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
815 * @param $variant \type{\string} language variant of url (for sr, zh..)
816 * @return \type{\string} the URL
818 public function getLocalURL( $query = '', $variant = false ) {
819 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
820 global $wgVariantArticlePath, $wgContLang, $wgUser;
822 if( is_array( $query ) ) {
823 $query = wfArrayToCGI( $query );
826 // internal links should point to same variant as current page (only anonymous users)
827 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
828 $pref = $wgContLang->getPreferredVariant(false);
829 if($pref != $wgContLang->getCode())
833 if ( $this->isExternal() ) {
834 $url = $this->getFullURL();
836 // This is currently only used for edit section links in the
837 // context of interwiki transclusion. In theory we should
838 // append the query to the end of any existing query string,
839 // but interwiki transclusion is already broken in that case.
843 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
844 if ( $query == '' ) {
845 if( $variant != false && $wgContLang->hasVariants() ) {
846 if( $wgVariantArticlePath == false ) {
847 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
849 $variantArticlePath = $wgVariantArticlePath;
851 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
852 $url = str_replace( '$1', $dbkey, $url );
854 $url = str_replace( '$1', $dbkey, $wgArticlePath );
857 global $wgActionPaths;
860 if( !empty( $wgActionPaths ) &&
861 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
863 $action = urldecode( $matches[2] );
864 if( isset( $wgActionPaths[$action] ) ) {
865 $query = $matches[1];
866 if( isset( $matches[4] ) ) $query .= $matches[4];
867 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
869 $url = wfAppendQuery( $url, $query );
873 if ( $url === false ) {
874 if ( $query == '-' ) {
877 $url = "{$wgScript}?title={$dbkey}&{$query}";
881 // FIXME: this causes breakage in various places when we
882 // actually expected a local URL and end up with dupe prefixes.
883 if ($wgRequest->getVal('action') == 'render') {
884 $url = $wgServer . $url;
887 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
892 * Get a URL that's the simplest URL that will be valid to link, locally,
893 * to the current Title. It includes the fragment, but does not include
894 * the server unless action=render is used (or the link is external). If
895 * there's a fragment but the prefixed text is empty, we just return a link
898 * The result obviously should not be URL-escaped, but does need to be
899 * HTML-escaped if it's being output in HTML.
901 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
902 * query string. Keys and values will be escaped.
903 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
904 * for external links. Default is "false" (same variant as current page,
905 * for anonymous users).
906 * @return \type{\string} the URL
908 public function getLinkUrl( $query = array(), $variant = false ) {
909 wfProfileIn( __METHOD__
);
910 if( $this->isExternal() ) {
911 $ret = $this->getFullURL( $query );
912 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
913 $ret = $this->getFragmentForURL();
915 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
917 wfProfileOut( __METHOD__
);
922 * Get an HTML-escaped version of the URL form, suitable for
923 * using in a link, without a server name or fragment
925 * @param $query \type{\string} an optional query string
926 * @return \type{\string} the URL
928 public function escapeLocalURL( $query = '' ) {
929 return htmlspecialchars( $this->getLocalURL( $query ) );
933 * Get an HTML-escaped version of the URL form, suitable for
934 * using in a link, including the server name and fragment
936 * @param $query \type{\string} an optional query string
937 * @return \type{\string} the URL
939 public function escapeFullURL( $query = '' ) {
940 return htmlspecialchars( $this->getFullURL( $query ) );
944 * Get the URL form for an internal link.
945 * - Used in various Squid-related code, in case we have a different
946 * internal hostname for the server from the exposed one.
948 * @param $query \type{\string} an optional query string
949 * @param $variant \type{\string} language variant of url (for sr, zh..)
950 * @return \type{\string} the URL
952 public function getInternalURL( $query = '', $variant = false ) {
953 global $wgInternalServer;
954 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
955 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
960 * Get the edit URL for this Title
962 * @return \type{\string} the URL, or a null string if this is an
965 public function getEditURL() {
966 if ( $this->mInterwiki
!= '' ) { return ''; }
967 $s = $this->getLocalURL( 'action=edit' );
973 * Get the HTML-escaped displayable text form.
974 * Used for the title field in <a> tags.
976 * @return \type{\string} the text, including any prefixes
978 public function getEscapedText() {
979 return htmlspecialchars( $this->getPrefixedText() );
983 * Is this Title interwiki?
985 * @return \type{\bool}
987 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
990 * Is this page "semi-protected" - the *only* protection is autoconfirm?
992 * @param $action \type{\string} Action to check (default: edit)
993 * @return \type{\bool}
995 public function isSemiProtected( $action = 'edit' ) {
996 if( $this->exists() ) {
997 $restrictions = $this->getRestrictions( $action );
998 if( count( $restrictions ) > 0 ) {
999 foreach( $restrictions as $restriction ) {
1000 if( strtolower( $restriction ) != 'autoconfirmed' )
1009 # If it doesn't exist, it can't be protected
1015 * Does the title correspond to a protected article?
1017 * @param $action \type{\string} the action the page is protected from,
1018 * by default checks all actions.
1019 * @return \type{\bool}
1021 public function isProtected( $action = '' ) {
1022 global $wgRestrictionLevels;
1024 $restrictionTypes = $this->getRestrictionTypes();
1026 # Special pages have inherent protection
1027 if( $this->getNamespace() == NS_SPECIAL
)
1030 # Check regular protection levels
1031 foreach( $restrictionTypes as $type ){
1032 if( $action == $type ||
$action == '' ) {
1033 $r = $this->getRestrictions( $type );
1034 foreach( $wgRestrictionLevels as $level ) {
1035 if( in_array( $level, $r ) && $level != '' ) {
1046 * Is this a conversion table for the LanguageConverter?
1048 * @return \type{\bool}
1050 public function isConversionTable() {
1051 if($this->getNamespace() == NS_MEDIAWIKI
1052 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1060 * Is $wgUser watching this page?
1062 * @return \type{\bool}
1064 public function userIsWatching() {
1067 if ( is_null( $this->mWatched
) ) {
1068 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1069 $this->mWatched
= false;
1071 $this->mWatched
= $wgUser->isWatched( $this );
1074 return $this->mWatched
;
1078 * Can $wgUser perform $action on this page?
1079 * This skips potentially expensive cascading permission checks
1080 * as well as avoids expensive error formatting
1082 * Suitable for use for nonessential UI controls in common cases, but
1083 * _not_ for functional access control.
1085 * May provide false positives, but should never provide a false negative.
1087 * @param $action \type{\string} action that permission needs to be checked for
1088 * @return \type{\bool}
1090 public function quickUserCan( $action ) {
1091 return $this->userCan( $action, false );
1095 * Determines if $wgUser is unable to edit this page because it has been protected
1096 * by $wgNamespaceProtection.
1098 * @return \type{\bool}
1100 public function isNamespaceProtected() {
1101 global $wgNamespaceProtection, $wgUser;
1102 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1103 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1104 if( $right != '' && !$wgUser->isAllowed( $right ) )
1112 * Can $wgUser perform $action on this page?
1114 * @param $action \type{\string} action that permission needs to be checked for
1115 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1116 * @return \type{\bool}
1118 public function userCan( $action, $doExpensiveQueries = true ) {
1120 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1124 * Can $user perform $action on this page?
1126 * FIXME: This *does not* check throttles (User::pingLimiter()).
1128 * @param $action \type{\string}action that permission needs to be checked for
1129 * @param $user \type{User} user to check
1130 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1131 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1132 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1134 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1135 if( !StubObject
::isRealObject( $user ) ) {
1136 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1138 $wgUser->_unstub( '', 5 );
1141 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1145 global $wgEmailConfirmToEdit;
1147 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1148 $errors[] = array( 'confirmedittext' );
1151 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1152 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1153 $block = $user->mBlock
;
1155 // This is from OutputPage::blockedPage
1156 // Copied at r23888 by werdna
1158 $id = $user->blockedBy();
1159 $reason = $user->blockedFor();
1160 if( $reason == '' ) {
1161 $reason = wfMsg( 'blockednoreason' );
1165 if ( is_numeric( $id ) ) {
1166 $name = User
::whoIs( $id );
1171 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1172 $blockid = $block->mId
;
1173 $blockExpiry = $user->mBlock
->mExpiry
;
1174 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1176 if ( $blockExpiry == 'infinity' ) {
1177 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1178 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1180 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1181 if ( strpos( $option, ':' ) == false )
1184 list ($show, $value) = explode( ":", $option );
1186 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1187 $blockExpiry = $show;
1192 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1195 $intended = $user->mBlock
->mAddress
;
1197 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1198 $blockid, $blockExpiry, $intended, $blockTimestamp );
1201 // Remove the errors being ignored.
1203 foreach( $errors as $index => $error ) {
1204 $error_key = is_array($error) ?
$error[0] : $error;
1206 if (in_array( $error_key, $ignoreErrors )) {
1207 unset($errors[$index]);
1215 * Can $user perform $action on this page? This is an internal function,
1216 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1217 * checks on wfReadOnly() and blocks)
1219 * @param $action \type{\string} action that permission needs to be checked for
1220 * @param $user \type{User} user to check
1221 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1222 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1223 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1225 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1226 wfProfileIn( __METHOD__
);
1230 // First stop is permissions checks, which fail most often, and which are easiest to test.
1231 if ( $action == 'move' ) {
1232 if( !$user->isAllowed( 'move-rootuserpages' )
1233 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1235 // Show user page-specific message only if the user can move other pages
1236 $errors[] = array( 'cant-move-user-page' );
1239 // Check if user is allowed to move files if it's a file
1240 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1241 $errors[] = array( 'movenotallowedfile' );
1244 if( !$user->isAllowed( 'move' ) ) {
1245 // User can't move anything
1246 global $wgGroupPermissions;
1247 $userCanMove = false;
1248 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1249 $userCanMove = $wgGroupPermissions['user']['move'];
1251 $autoconfirmedCanMove = false;
1252 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1253 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1255 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1256 // custom message if logged-in users without any special rights can move
1257 $errors[] = array ( 'movenologintext' );
1259 $errors[] = array ('movenotallowed');
1262 } elseif ( $action == 'create' ) {
1263 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1264 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1266 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1268 } elseif( $action == 'move-target' ) {
1269 if( !$user->isAllowed( 'move' ) ) {
1270 // User can't move anything
1271 $errors[] = array ('movenotallowed');
1272 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1273 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1275 // Show user page-specific message only if the user can move other pages
1276 $errors[] = array( 'cant-move-to-user-page' );
1278 } elseif( !$user->isAllowed( $action ) ) {
1281 // We avoid expensive display logic for quickUserCan's and such
1284 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1285 User
::getGroupsWithPermission( $action ) );
1292 $wgLang->commaList( $groups ),
1296 $return = array( "badaccess-group0" );
1298 $errors[] = $return;
1301 # Short-circuit point
1302 if( $short && count($errors) > 0 ) {
1303 wfProfileOut( __METHOD__
);
1307 // Use getUserPermissionsErrors instead
1308 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1309 wfProfileOut( __METHOD__
);
1310 return $result ?
array() : array( array( 'badaccess-group0' ) );
1312 // Check getUserPermissionsErrors hook
1313 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1314 if( is_array($result) && count($result) && !is_array($result[0]) )
1315 $errors[] = $result; # A single array representing an error
1316 else if( is_array($result) && is_array($result[0]) )
1317 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1318 else if( $result !== '' && is_string($result) )
1319 $errors[] = array($result); # A string representing a message-id
1320 else if( $result === false )
1321 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1323 # Short-circuit point
1324 if( $short && count($errors) > 0 ) {
1325 wfProfileOut( __METHOD__
);
1328 // Check getUserPermissionsErrorsExpensive hook
1329 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1330 if( is_array($result) && count($result) && !is_array($result[0]) )
1331 $errors[] = $result; # A single array representing an error
1332 else if( is_array($result) && is_array($result[0]) )
1333 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1334 else if( $result !== '' && is_string($result) )
1335 $errors[] = array($result); # A string representing a message-id
1336 else if( $result === false )
1337 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1339 # Short-circuit point
1340 if( $short && count($errors) > 0 ) {
1341 wfProfileOut( __METHOD__
);
1345 # Only 'createaccount' and 'execute' can be performed on
1346 # special pages, which don't actually exist in the DB.
1347 $specialOKActions = array( 'createaccount', 'execute' );
1348 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1349 $errors[] = array('ns-specialprotected');
1352 # Check $wgNamespaceProtection for restricted namespaces
1353 if( $this->isNamespaceProtected() ) {
1354 $ns = $this->getNamespace() == NS_MAIN ?
1355 wfMsg( 'nstab-main' ) : $this->getNsText();
1356 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1357 array('protectedinterface') : array( 'namespaceprotected', $ns );
1360 # Protect css/js subpages of user pages
1361 # XXX: this might be better using restrictions
1362 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1363 # and $this->userCanEditJsSubpage() from working
1364 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1365 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1366 && $action != 'patrol'
1367 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1369 $errors[] = array('customcssjsprotected');
1370 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1371 && $action != 'patrol'
1372 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1374 $errors[] = array('customcssjsprotected');
1377 # Check against page_restrictions table requirements on this
1378 # page. The user must possess all required rights for this action.
1379 foreach( $this->getRestrictions($action) as $right ) {
1380 // Backwards compatibility, rewrite sysop -> protect
1381 if( $right == 'sysop' ) {
1384 if( $right != '' && !$user->isAllowed( $right ) ) {
1385 // Users with 'editprotected' permission can edit protected pages
1386 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1387 // Users with 'editprotected' permission cannot edit protected pages
1388 // with cascading option turned on.
1389 if( $this->mCascadeRestriction
) {
1390 $errors[] = array( 'protectedpagetext', $right );
1393 $errors[] = array( 'protectedpagetext', $right );
1397 # Short-circuit point
1398 if( $short && count($errors) > 0 ) {
1399 wfProfileOut( __METHOD__
);
1403 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1404 # We /could/ use the protection level on the source page, but it's fairly ugly
1405 # as we have to establish a precedence hierarchy for pages included by multiple
1406 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1407 # as they could remove the protection anyway.
1408 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1409 # Cascading protection depends on more than this page...
1410 # Several cascading protected pages may include this page...
1411 # Check each cascading level
1412 # This is only for protection restrictions, not for all actions
1413 if( isset($restrictions[$action]) ) {
1414 foreach( $restrictions[$action] as $right ) {
1415 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1416 if( $right != '' && !$user->isAllowed( $right ) ) {
1418 foreach( $cascadingSources as $page )
1419 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1420 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1425 # Short-circuit point
1426 if( $short && count($errors) > 0 ) {
1427 wfProfileOut( __METHOD__
);
1431 if( $action == 'protect' ) {
1432 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1433 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1437 if( $action == 'create' ) {
1438 $title_protection = $this->getTitleProtection();
1439 if( $title_protection ) {
1440 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1441 $title_protection['pt_create_perm'] = 'protect'; // B/C
1443 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed($title_protection['pt_create_perm']) ) {
1444 $errors[] = array( 'titleprotected', User
::whoIs($title_protection['pt_user']), $title_protection['pt_reason'] );
1447 } elseif( $action == 'move' ) {
1448 // Check for immobile pages
1449 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1450 // Specific message for this case
1451 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1452 } elseif( !$this->isMovable() ) {
1453 // Less specific message for rarer cases
1454 $errors[] = array( 'immobile-page' );
1456 } elseif( $action == 'move-target' ) {
1457 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1458 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1459 } elseif( !$this->isMovable() ) {
1460 $errors[] = array( 'immobile-target-page' );
1464 wfProfileOut( __METHOD__
);
1469 * Is this title subject to title protection?
1471 * @return \type{\mixed} An associative array representing any existent title
1472 * protection, or false if there's none.
1474 private function getTitleProtection() {
1475 // Can't protect pages in special namespaces
1476 if ( $this->getNamespace() < 0 ) {
1480 // Can't protect pages that exist.
1481 if ($this->exists()) {
1485 if ( !isset( $this->mTitleProtection
) ) {
1486 $dbr = wfGetDB( DB_SLAVE
);
1487 $res = $dbr->select( 'protected_titles', '*',
1488 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1491 // fetchRow returns false if there are no rows.
1492 $this->mTitleProtection
= $dbr->fetchRow( $res );
1494 return $this->mTitleProtection
;
1498 * Update the title protection status
1500 * @param $create_perm \type{\string} Permission required for creation
1501 * @param $reason \type{\string} Reason for protection
1502 * @param $expiry \type{\string} Expiry timestamp
1503 * @return boolean true
1505 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1506 global $wgUser,$wgContLang;
1508 if ($create_perm == implode(',',$this->getRestrictions('create'))
1509 && $expiry == $this->mRestrictionsExpiry
['create']) {
1514 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1516 $dbw = wfGetDB( DB_MASTER
);
1518 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1520 $expiry_description = '';
1521 if ( $encodedExpiry != 'infinity' ) {
1522 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1523 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1526 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1529 # Update protection table
1530 if ($create_perm != '' ) {
1531 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1533 'pt_namespace' => $namespace,
1534 'pt_title' => $title,
1535 'pt_create_perm' => $create_perm,
1536 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1537 'pt_expiry' => $encodedExpiry,
1538 'pt_user' => $wgUser->getId(),
1539 'pt_reason' => $reason,
1543 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1544 'pt_title' => $title ), __METHOD__
);
1546 # Update the protection log
1547 if( $dbw->affectedRows() ) {
1548 $log = new LogPage( 'protect' );
1550 if( $create_perm ) {
1551 $params = array("[create=$create_perm] $expiry_description",'');
1552 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1554 $log->addEntry( 'unprotect', $this, $reason );
1562 * Remove any title protection due to page existing
1564 public function deleteTitleProtection() {
1565 $dbw = wfGetDB( DB_MASTER
);
1567 $dbw->delete( 'protected_titles',
1568 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1573 * Would anybody with sufficient privileges be able to move this page?
1574 * Some pages just aren't movable.
1576 * @return \type{\bool} TRUE or FALSE
1578 public function isMovable() {
1579 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1583 * Can $wgUser read this page?
1585 * @return \type{\bool}
1586 * @todo fold these checks into userCan()
1588 public function userCanRead() {
1589 global $wgUser, $wgGroupPermissions;
1591 static $useShortcut = null;
1593 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1594 if( is_null( $useShortcut ) ) {
1595 global $wgRevokePermissions;
1596 $useShortcut = true;
1597 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1598 # Not a public wiki, so no shortcut
1599 $useShortcut = false;
1600 } elseif( !empty( $wgRevokePermissions ) ) {
1602 * Iterate through each group with permissions being revoked (key not included since we don't care
1603 * what the group name is), then check if the read permission is being revoked. If it is, then
1604 * we don't use the shortcut below since the user might not be able to read, even though anon
1605 * reading is allowed.
1607 foreach( $wgRevokePermissions as $perms ) {
1608 if( !empty( $perms['read'] ) ) {
1609 # We might be removing the read right from the user, so no shortcut
1610 $useShortcut = false;
1618 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1619 if ( $result !== null ) {
1623 # Shortcut for public wikis, allows skipping quite a bit of code
1627 if( $wgUser->isAllowed( 'read' ) ) {
1630 global $wgWhitelistRead;
1633 * Always grant access to the login page.
1634 * Even anons need to be able to log in.
1636 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1641 * Bail out if there isn't whitelist
1643 if( !is_array($wgWhitelistRead) ) {
1648 * Check for explicit whitelisting
1650 $name = $this->getPrefixedText();
1651 $dbName = $this->getPrefixedDBKey();
1652 // Check with and without underscores
1653 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1657 * Old settings might have the title prefixed with
1658 * a colon for main-namespace pages
1660 if( $this->getNamespace() == NS_MAIN
) {
1661 if( in_array( ':' . $name, $wgWhitelistRead ) )
1666 * If it's a special page, ditch the subpage bit
1669 if( $this->getNamespace() == NS_SPECIAL
) {
1670 $name = $this->getDBkey();
1671 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1672 if ( $name === false ) {
1673 # Invalid special page, but we show standard login required message
1677 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1678 if( in_array( $pure, $wgWhitelistRead, true ) )
1687 * Is this a talk page of some sort?
1689 * @return \type{\bool}
1691 public function isTalkPage() {
1692 return MWNamespace
::isTalk( $this->getNamespace() );
1696 * Is this a subpage?
1698 * @return \type{\bool}
1700 public function isSubpage() {
1701 return MWNamespace
::hasSubpages( $this->mNamespace
)
1702 ?
strpos( $this->getText(), '/' ) !== false
1707 * Does this have subpages? (Warning, usually requires an extra DB query.)
1709 * @return \type{\bool}
1711 public function hasSubpages() {
1712 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1717 # We dynamically add a member variable for the purpose of this method
1718 # alone to cache the result. There's no point in having it hanging
1719 # around uninitialized in every Title object; therefore we only add it
1720 # if needed and don't declare it statically.
1721 if( isset( $this->mHasSubpages
) ) {
1722 return $this->mHasSubpages
;
1725 $subpages = $this->getSubpages( 1 );
1726 if( $subpages instanceof TitleArray
)
1727 return $this->mHasSubpages
= (bool)$subpages->count();
1728 return $this->mHasSubpages
= false;
1732 * Get all subpages of this page.
1734 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1735 * @return mixed TitleArray, or empty array if this page's namespace
1736 * doesn't allow subpages
1738 public function getSubpages( $limit = -1 ) {
1739 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1742 $dbr = wfGetDB( DB_SLAVE
);
1743 $conds['page_namespace'] = $this->getNamespace();
1744 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1747 $options['LIMIT'] = $limit;
1748 return $this->mSubpages
= TitleArray
::newFromResult(
1749 $dbr->select( 'page',
1750 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1759 * Could this page contain custom CSS or JavaScript, based
1762 * @return \type{\bool}
1764 public function isCssOrJsPage() {
1765 return $this->mNamespace
== NS_MEDIAWIKI
1766 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1770 * Is this a .css or .js subpage of a user page?
1771 * @return \type{\bool}
1773 public function isCssJsSubpage() {
1774 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1778 * Is this a *valid* .css or .js subpage of a user page?
1779 * Check that the corresponding skin exists
1781 * @return \type{\bool}
1783 public function isValidCssJsSubpage() {
1784 if ( $this->isCssJsSubpage() ) {
1785 $name = $this->getSkinFromCssJsSubpage();
1786 if ( $name == 'common' ) return true;
1787 $skinNames = Skin
::getSkinNames();
1788 return array_key_exists( $name, $skinNames );
1795 * Trim down a .css or .js subpage title to get the corresponding skin name
1797 * @return string containing skin name from .css or .js subpage title
1799 public function getSkinFromCssJsSubpage() {
1800 $subpage = explode( '/', $this->mTextform
);
1801 $subpage = $subpage[ count( $subpage ) - 1 ];
1802 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1806 * Is this a .css subpage of a user page?
1808 * @return \type{\bool}
1810 public function isCssSubpage() {
1811 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1815 * Is this a .js subpage of a user page?
1817 * @return \type{\bool}
1819 public function isJsSubpage() {
1820 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1824 * Protect css subpages of user pages: can $wgUser edit
1827 * @return \type{\bool}
1828 * @todo XXX: this might be better using restrictions
1830 public function userCanEditCssSubpage() {
1832 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1833 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1836 * Protect js subpages of user pages: can $wgUser edit
1839 * @return \type{\bool}
1840 * @todo XXX: this might be better using restrictions
1842 public function userCanEditJsSubpage() {
1844 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1845 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1849 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1851 * @return \type{\bool} If the page is subject to cascading restrictions.
1853 public function isCascadeProtected() {
1854 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1855 return ( $sources > 0 );
1859 * Cascading protection: Get the source of any cascading restrictions on this page.
1861 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages
1862 * that the restrictions have come from.
1863 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1864 * objects of the pages from which cascading restrictions have come,
1865 * false for none, or true if such restrictions exist, but $get_pages was not set.
1866 * The restriction array is an array of each type, each of which contains a
1867 * array of unique groups.
1869 public function getCascadeProtectionSources( $get_pages = true ) {
1870 $pagerestrictions = array();
1872 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1873 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1874 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1875 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1878 wfProfileIn( __METHOD__
);
1880 $dbr = wfGetDB( DB_SLAVE
);
1882 if ( $this->getNamespace() == NS_FILE
) {
1883 $tables = array ('imagelinks', 'page_restrictions');
1884 $where_clauses = array(
1885 'il_to' => $this->getDBkey(),
1887 'pr_cascade' => 1 );
1889 $tables = array ('templatelinks', 'page_restrictions');
1890 $where_clauses = array(
1891 'tl_namespace' => $this->getNamespace(),
1892 'tl_title' => $this->getDBkey(),
1894 'pr_cascade' => 1 );
1898 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1899 $where_clauses[] = 'page_id=pr_page';
1902 $cols = array( 'pr_expiry' );
1905 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1907 $sources = $get_pages ?
array() : false;
1908 $now = wfTimestampNow();
1909 $purgeExpired = false;
1911 foreach( $res as $row ) {
1912 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1913 if( $expiry > $now ) {
1915 $page_id = $row->pr_page
;
1916 $page_ns = $row->page_namespace
;
1917 $page_title = $row->page_title
;
1918 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1919 # Add groups needed for each restriction type if its not already there
1920 # Make sure this restriction type still exists
1922 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1923 $pagerestrictions[$row->pr_type
] = array();
1926 if ( isset($pagerestrictions[$row->pr_type
]) &&
1927 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1928 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1934 // Trigger lazy purge of expired restrictions from the db
1935 $purgeExpired = true;
1938 if( $purgeExpired ) {
1939 Title
::purgeExpiredRestrictions();
1942 wfProfileOut( __METHOD__
);
1945 $this->mCascadeSources
= $sources;
1946 $this->mCascadingRestrictions
= $pagerestrictions;
1948 $this->mHasCascadingRestrictions
= $sources;
1950 return array( $sources, $pagerestrictions );
1954 * Returns cascading restrictions for the current article
1958 function areRestrictionsCascading() {
1959 if (!$this->mRestrictionsLoaded
) {
1960 $this->loadRestrictions();
1963 return $this->mCascadeRestriction
;
1967 * Loads a string into mRestrictions array
1969 * @param $res \type{Resource} restrictions as an SQL result.
1970 * @param $oldFashionedRestrictions string comma-separated list of page
1971 * restrictions from page table (pre 1.10)
1973 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1975 $dbr = wfGetDB( DB_SLAVE
);
1977 while( $row = $dbr->fetchObject( $res ) ) {
1981 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1985 * Compiles list of active page restrictions from both page table (pre 1.10)
1986 * and page_restrictions table
1988 * @param $rows array of db result objects
1989 * @param $oldFashionedRestrictions string comma-separated list of page
1990 * restrictions from page table (pre 1.10)
1992 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1993 $dbr = wfGetDB( DB_SLAVE
);
1995 $restrictionTypes = $this->getRestrictionTypes();
1997 foreach( $restrictionTypes as $type ){
1998 $this->mRestrictions
[$type] = array();
1999 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
2002 $this->mCascadeRestriction
= false;
2004 # Backwards-compatibility: also load the restrictions from the page record (old format).
2006 if ( $oldFashionedRestrictions === null ) {
2007 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2008 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2011 if ($oldFashionedRestrictions != '') {
2013 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2014 $temp = explode( '=', trim( $restrict ) );
2015 if(count($temp) == 1) {
2016 // old old format should be treated as edit/move restriction
2017 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2018 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2020 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2024 $this->mOldRestrictions
= true;
2028 if( count($rows) ) {
2029 # Current system - load second to make them override.
2030 $now = wfTimestampNow();
2031 $purgeExpired = false;
2033 foreach( $rows as $row ) {
2034 # Cycle through all the restrictions.
2036 // Don't take care of restrictions types that aren't allowed
2038 if( !in_array( $row->pr_type
, $restrictionTypes ) )
2041 // This code should be refactored, now that it's being used more generally,
2042 // But I don't really see any harm in leaving it in Block for now -werdna
2043 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2045 // Only apply the restrictions if they haven't expired!
2046 if ( !$expiry ||
$expiry > $now ) {
2047 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2048 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2050 $this->mCascadeRestriction |
= $row->pr_cascade
;
2052 // Trigger a lazy purge of expired restrictions
2053 $purgeExpired = true;
2057 if( $purgeExpired ) {
2058 Title
::purgeExpiredRestrictions();
2062 $this->mRestrictionsLoaded
= true;
2066 * Load restrictions from the page_restrictions table
2068 * @param $oldFashionedRestrictions string comma-separated list of page
2069 * restrictions from page table (pre 1.10)
2071 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2072 if( !$this->mRestrictionsLoaded
) {
2073 if ($this->exists()) {
2074 $dbr = wfGetDB( DB_SLAVE
);
2076 $res = $dbr->select( 'page_restrictions', '*',
2077 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2079 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2081 $title_protection = $this->getTitleProtection();
2083 if ($title_protection) {
2084 $now = wfTimestampNow();
2085 $expiry = Block
::decodeExpiry($title_protection['pt_expiry']);
2087 if (!$expiry ||
$expiry > $now) {
2088 // Apply the restrictions
2089 $this->mRestrictionsExpiry
['create'] = $expiry;
2090 $this->mRestrictions
['create'] = explode(',', trim($title_protection['pt_create_perm']) );
2091 } else { // Get rid of the old restrictions
2092 Title
::purgeExpiredRestrictions();
2095 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
2097 $this->mRestrictionsLoaded
= true;
2103 * Purge expired restrictions from the page_restrictions table
2105 static function purgeExpiredRestrictions() {
2106 $dbw = wfGetDB( DB_MASTER
);
2107 $dbw->delete( 'page_restrictions',
2108 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2111 $dbw->delete( 'protected_titles',
2112 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2117 * Accessor/initialisation for mRestrictions
2119 * @param $action \type{\string} action that permission needs to be checked for
2120 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2122 public function getRestrictions( $action ) {
2123 if( !$this->mRestrictionsLoaded
) {
2124 $this->loadRestrictions();
2126 return isset( $this->mRestrictions
[$action] )
2127 ?
$this->mRestrictions
[$action]
2132 * Get the expiry time for the restriction against a given action
2134 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2135 * or not protected at all, or false if the action is not recognised.
2137 public function getRestrictionExpiry( $action ) {
2138 if( !$this->mRestrictionsLoaded
) {
2139 $this->loadRestrictions();
2141 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2145 * Is there a version of this page in the deletion archive?
2147 * @return \type{\int} the number of archived revisions
2149 public function isDeleted() {
2150 if( $this->getNamespace() < 0 ) {
2153 $dbr = wfGetDB( DB_SLAVE
);
2154 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2155 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2158 if( $this->getNamespace() == NS_FILE
) {
2159 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2160 array( 'fa_name' => $this->getDBkey() ),
2169 * Is there a version of this page in the deletion archive?
2173 public function isDeletedQuick() {
2174 if( $this->getNamespace() < 0 ) {
2177 $dbr = wfGetDB( DB_SLAVE
);
2178 $deleted = (bool)$dbr->selectField( 'archive', '1',
2179 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2182 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2183 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2184 array( 'fa_name' => $this->getDBkey() ),
2192 * Get the article ID for this Title from the link cache,
2193 * adding it if necessary
2195 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2197 * @return \type{\int} the ID
2199 public function getArticleID( $flags = 0 ) {
2200 if( $this->getNamespace() < 0 ) {
2201 return $this->mArticleID
= 0;
2203 $linkCache = LinkCache
::singleton();
2204 if( $flags & GAID_FOR_UPDATE
) {
2205 $oldUpdate = $linkCache->forUpdate( true );
2206 $linkCache->clearLink( $this );
2207 $this->mArticleID
= $linkCache->addLinkObj( $this );
2208 $linkCache->forUpdate( $oldUpdate );
2210 if( -1 == $this->mArticleID
) {
2211 $this->mArticleID
= $linkCache->addLinkObj( $this );
2214 return $this->mArticleID
;
2218 * Is this an article that is a redirect page?
2219 * Uses link cache, adding it if necessary
2221 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2222 * @return \type{\bool}
2224 public function isRedirect( $flags = 0 ) {
2225 if( !is_null($this->mRedirect
) )
2226 return $this->mRedirect
;
2227 # Calling getArticleID() loads the field from cache as needed
2228 if( !$this->getArticleID($flags) ) {
2229 return $this->mRedirect
= false;
2231 $linkCache = LinkCache
::singleton();
2232 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2234 return $this->mRedirect
;
2238 * What is the length of this page?
2239 * Uses link cache, adding it if necessary
2241 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2242 * @return \type{\bool}
2244 public function getLength( $flags = 0 ) {
2245 if( $this->mLength
!= -1 )
2246 return $this->mLength
;
2247 # Calling getArticleID() loads the field from cache as needed
2248 if( !$this->getArticleID($flags) ) {
2249 return $this->mLength
= 0;
2251 $linkCache = LinkCache
::singleton();
2252 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2254 return $this->mLength
;
2258 * What is the page_latest field for this page?
2260 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2261 * @return \type{\int} or false if the page doesn't exist
2263 public function getLatestRevID( $flags = 0 ) {
2264 if( $this->mLatestID
!== false )
2265 return $this->mLatestID
;
2267 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2268 $this->mLatestID
= (int)$db->selectField(
2269 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2270 return $this->mLatestID
;
2274 * This clears some fields in this object, and clears any associated
2275 * keys in the "bad links" section of the link cache.
2277 * - This is called from Article::insertNewArticle() to allow
2278 * loading of the new page_id. It's also called from
2279 * Article::doDeleteArticle()
2281 * @param $newid \type{\int} the new Article ID
2283 public function resetArticleID( $newid ) {
2284 $linkCache = LinkCache
::singleton();
2285 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2287 if ( $newid === false ) {
2288 $this->mArticleID
= -1;
2290 $this->mArticleID
= intval( $newid );
2292 $this->mRestrictionsLoaded
= false;
2293 $this->mRestrictions
= array();
2294 $this->mRedirect
= null;
2295 $this->mLength
= -1;
2296 $this->mLatestID
= false;
2300 * Updates page_touched for this page; called from LinksUpdate.php
2302 * @return \type{\bool} true if the update succeded
2304 public function invalidateCache() {
2305 if( wfReadOnly() ) {
2308 $dbw = wfGetDB( DB_MASTER
);
2309 $success = $dbw->update( 'page',
2310 array( 'page_touched' => $dbw->timestamp() ),
2314 HTMLFileCache
::clearFileCache( $this );
2319 * Prefix some arbitrary text with the namespace or interwiki prefix
2322 * @param $name \type{\string} the text
2323 * @return \type{\string} the prefixed text
2326 /* private */ function prefix( $name ) {
2328 if ( $this->mInterwiki
!= '' ) {
2329 $p = $this->mInterwiki
. ':';
2331 if ( 0 != $this->mNamespace
) {
2332 $p .= $this->getNsText() . ':';
2338 * Returns a simple regex that will match on characters and sequences invalid in titles.
2339 * Note that this doesn't pick up many things that could be wrong with titles, but that
2340 * replacing this regex with something valid will make many titles valid.
2342 * @return string regex string
2344 static function getTitleInvalidRegex() {
2345 static $rxTc = false;
2347 # Matching titles will be held as illegal.
2349 # Any character not allowed is forbidden...
2350 '[^' . Title
::legalChars() . ']' .
2351 # URL percent encoding sequences interfere with the ability
2352 # to round-trip titles -- you can't link to them consistently.
2353 '|%[0-9A-Fa-f]{2}' .
2354 # XML/HTML character references produce similar issues.
2355 '|&[A-Za-z0-9\x80-\xff]+;' .
2357 '|&#x[0-9A-Fa-f]+;' .
2365 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2367 * @param $text string containing title to capitalize
2368 * @param $ns int namespace index, defaults to NS_MAIN
2369 * @return String containing capitalized title
2371 public static function capitalize( $text, $ns = NS_MAIN
) {
2374 if ( MWNamespace
::isCapitalized( $ns ) )
2375 return $wgContLang->ucfirst( $text );
2381 * Secure and split - main initialisation function for this object
2383 * Assumes that mDbkeyform has been set, and is urldecoded
2384 * and uses underscores, but not otherwise munged. This function
2385 * removes illegal characters, splits off the interwiki and
2386 * namespace prefixes, sets the other forms, and canonicalizes
2389 * @return \type{\bool} true on success
2391 private function secureAndSplit() {
2392 global $wgContLang, $wgLocalInterwiki;
2395 $rxTc = self
::getTitleInvalidRegex();
2397 $this->mInterwiki
= $this->mFragment
= '';
2398 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2400 $dbkey = $this->mDbkeyform
;
2402 # Strip Unicode bidi override characters.
2403 # Sometimes they slip into cut-n-pasted page titles, where the
2404 # override chars get included in list displays.
2405 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2407 # Clean up whitespace
2408 # Note: use of the /u option on preg_replace here will cause
2409 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2410 # conveniently disabling them.
2412 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2413 $dbkey = trim( $dbkey, '_' );
2415 if ( $dbkey == '' ) {
2419 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2420 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2424 $this->mDbkeyform
= $dbkey;
2426 # Initial colon indicates main namespace rather than specified default
2427 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2428 if ( ':' == $dbkey{0} ) {
2429 $this->mNamespace
= NS_MAIN
;
2430 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2431 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2434 # Namespace or interwiki prefix
2436 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2439 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2441 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2442 # Ordinary namespace
2444 $this->mNamespace
= $ns;
2445 # For Talk:X pages, check if X has a "namespace" prefix
2446 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2447 if( $wgContLang->getNsIndex( $x[1] ) )
2448 return false; # Disallow Talk:File:x type titles...
2449 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2450 return false; # Disallow Talk:Interwiki:x type titles...
2452 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2454 # Can't make a local interwiki link to an interwiki link.
2455 # That's just crazy!
2461 $this->mInterwiki
= $wgContLang->lc( $p );
2463 # Redundant interwiki prefix to the local wiki
2464 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2465 if( $dbkey == '' ) {
2466 # Can't have an empty self-link
2469 $this->mInterwiki
= '';
2471 # Do another namespace split...
2475 # If there's an initial colon after the interwiki, that also
2476 # resets the default namespace
2477 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2478 $this->mNamespace
= NS_MAIN
;
2479 $dbkey = substr( $dbkey, 1 );
2482 # If there's no recognized interwiki or namespace,
2483 # then let the colon expression be part of the title.
2488 # We already know that some pages won't be in the database!
2490 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2491 $this->mArticleID
= 0;
2493 $fragment = strstr( $dbkey, '#' );
2494 if ( false !== $fragment ) {
2495 $this->setFragment( $fragment );
2496 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2497 # remove whitespace again: prevents "Foo_bar_#"
2498 # becoming "Foo_bar_"
2499 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2502 # Reject illegal characters.
2504 if( preg_match( $rxTc, $dbkey ) ) {
2509 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2510 * reachable due to the way web browsers deal with 'relative' URLs.
2511 * Also, they conflict with subpage syntax. Forbid them explicitly.
2513 if ( strpos( $dbkey, '.' ) !== false &&
2514 ( $dbkey === '.' ||
$dbkey === '..' ||
2515 strpos( $dbkey, './' ) === 0 ||
2516 strpos( $dbkey, '../' ) === 0 ||
2517 strpos( $dbkey, '/./' ) !== false ||
2518 strpos( $dbkey, '/../' ) !== false ||
2519 substr( $dbkey, -2 ) == '/.' ||
2520 substr( $dbkey, -3 ) == '/..' ) )
2526 * Magic tilde sequences? Nu-uh!
2528 if( strpos( $dbkey, '~~~' ) !== false ) {
2533 * Limit the size of titles to 255 bytes.
2534 * This is typically the size of the underlying database field.
2535 * We make an exception for special pages, which don't need to be stored
2536 * in the database, and may edge over 255 bytes due to subpage syntax
2537 * for long titles, e.g. [[Special:Block/Long name]]
2539 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2540 strlen( $dbkey ) > 512 )
2546 * Normally, all wiki links are forced to have
2547 * an initial capital letter so [[foo]] and [[Foo]]
2548 * point to the same place.
2550 * Don't force it for interwikis, since the other
2551 * site might be case-sensitive.
2553 $this->mUserCaseDBKey
= $dbkey;
2554 if( $this->mInterwiki
== '') {
2555 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2559 * Can't make a link to a namespace alone...
2560 * "empty" local links can only be self-links
2561 * with a fragment identifier.
2564 $this->mInterwiki
== '' &&
2565 $this->mNamespace
!= NS_MAIN
) {
2568 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2569 // IP names are not allowed for accounts, and can only be referring to
2570 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2571 // there are numerous ways to present the same IP. Having sp:contribs scan
2572 // them all is silly and having some show the edits and others not is
2573 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2574 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2575 IP
::sanitizeIP( $dbkey ) : $dbkey;
2576 // Any remaining initial :s are illegal.
2577 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2582 $this->mDbkeyform
= $dbkey;
2583 $this->mUrlform
= wfUrlencode( $dbkey );
2585 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2591 * Set the fragment for this title. Removes the first character from the
2592 * specified fragment before setting, so it assumes you're passing it with
2595 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2596 * Still in active use privately.
2598 * @param $fragment \type{\string} text
2600 public function setFragment( $fragment ) {
2601 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2605 * Get a Title object associated with the talk page of this article
2607 * @return \type{Title} the object for the talk page
2609 public function getTalkPage() {
2610 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2614 * Get a title object associated with the subject page of this
2617 * @return \type{Title} the object for the subject page
2619 public function getSubjectPage() {
2620 // Is this the same title?
2621 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2622 if( $this->getNamespace() == $subjectNS ) {
2625 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2629 * Get an array of Title objects linking to this Title
2630 * Also stores the IDs in the link cache.
2632 * WARNING: do not use this function on arbitrary user-supplied titles!
2633 * On heavily-used templates it will max out the memory.
2635 * @param $options Array: may be FOR UPDATE
2636 * @param $table String: table name
2637 * @param $prefix String: fields prefix
2638 * @return \type{\arrayof{Title}} the Title objects linking here
2640 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2641 $linkCache = LinkCache
::singleton();
2643 if ( count( $options ) > 0 ) {
2644 $db = wfGetDB( DB_MASTER
);
2646 $db = wfGetDB( DB_SLAVE
);
2649 $res = $db->select( array( 'page', $table ),
2650 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2652 "{$prefix}_from=page_id",
2653 "{$prefix}_namespace" => $this->getNamespace(),
2654 "{$prefix}_title" => $this->getDBkey() ),
2659 if ( $db->numRows( $res ) ) {
2660 foreach( $res as $row ) {
2661 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2662 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2663 $retVal[] = $titleObj;
2667 $db->freeResult( $res );
2672 * Get an array of Title objects using this Title as a template
2673 * Also stores the IDs in the link cache.
2675 * WARNING: do not use this function on arbitrary user-supplied titles!
2676 * On heavily-used templates it will max out the memory.
2678 * @param $options Array: may be FOR UPDATE
2679 * @return \type{\arrayof{Title}} the Title objects linking here
2681 public function getTemplateLinksTo( $options = array() ) {
2682 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2686 * Get an array of Title objects referring to non-existent articles linked from this page
2688 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2689 * @return \type{\arrayof{Title}} the Title objects
2691 public function getBrokenLinksFrom() {
2692 if ( $this->getArticleId() == 0 ) {
2693 # All links from article ID 0 are false positives
2697 $dbr = wfGetDB( DB_SLAVE
);
2698 $res = $dbr->select(
2699 array( 'page', 'pagelinks' ),
2700 array( 'pl_namespace', 'pl_title' ),
2702 'pl_from' => $this->getArticleId(),
2703 'page_namespace IS NULL'
2705 __METHOD__
, array(),
2709 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2715 foreach( $res as $row ) {
2716 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2723 * Get a list of URLs to purge from the Squid cache when this
2726 * @return \type{\arrayof{\string}} the URLs
2728 public function getSquidURLs() {
2732 $this->getInternalURL(),
2733 $this->getInternalURL( 'action=history' )
2736 // purge variant urls as well
2737 if($wgContLang->hasVariants()){
2738 $variants = $wgContLang->getVariants();
2739 foreach($variants as $vCode){
2740 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2741 $urls[] = $this->getInternalURL('',$vCode);
2749 * Purge all applicable Squid URLs
2751 public function purgeSquid() {
2753 if ( $wgUseSquid ) {
2754 $urls = $this->getSquidURLs();
2755 $u = new SquidUpdate( $urls );
2761 * Move this page without authentication
2763 * @param $nt \type{Title} the new page Title
2764 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2766 public function moveNoAuth( &$nt ) {
2767 return $this->moveTo( $nt, false );
2771 * Check whether a given move operation would be valid.
2772 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2774 * @param $nt \type{Title} the new title
2775 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2777 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2778 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2780 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2785 // Normally we'd add this to $errors, but we'll get
2786 // lots of syntax errors if $nt is not an object
2787 return array(array('badtitletext'));
2789 if( $this->equals( $nt ) ) {
2790 $errors[] = array('selfmove');
2792 if( !$this->isMovable() ) {
2793 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2795 if ( $nt->getInterwiki() != '' ) {
2796 $errors[] = array( 'immobile-target-namespace-iw' );
2798 if ( !$nt->isMovable() ) {
2799 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2802 $oldid = $this->getArticleID();
2803 $newid = $nt->getArticleID();
2805 if ( strlen( $nt->getDBkey() ) < 1 ) {
2806 $errors[] = array('articleexists');
2808 if ( ( $this->getDBkey() == '' ) ||
2810 ( $nt->getDBkey() == '' ) ) {
2811 $errors[] = array('badarticleerror');
2814 // Image-specific checks
2815 if( $this->getNamespace() == NS_FILE
) {
2816 $file = wfLocalFile( $this );
2817 if( $file->exists() ) {
2818 if( $nt->getNamespace() != NS_FILE
) {
2819 $errors[] = array('imagenocrossnamespace');
2821 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2822 $errors[] = array('imageinvalidfilename');
2824 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2825 $errors[] = array('imagetypemismatch');
2828 $destfile = wfLocalFile( $nt );
2829 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2830 $errors[] = array( 'file-exists-sharedrepo' );
2836 $errors = wfMergeErrorArrays( $errors,
2837 $this->getUserPermissionsErrors('move', $wgUser),
2838 $this->getUserPermissionsErrors('edit', $wgUser),
2839 $nt->getUserPermissionsErrors('move-target', $wgUser),
2840 $nt->getUserPermissionsErrors('edit', $wgUser) );
2843 $match = EditPage
::matchSummarySpamRegex( $reason );
2844 if( $match !== false ) {
2845 // This is kind of lame, won't display nice
2846 $errors[] = array('spamprotectiontext');
2850 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2851 $errors[] = array('hookaborted', $err);
2854 # The move is allowed only if (1) the target doesn't exist, or
2855 # (2) the target is a redirect to the source, and has no history
2856 # (so we can undo bad moves right after they're done).
2858 if ( 0 != $newid ) { # Target exists; check for validity
2859 if ( ! $this->isValidMoveTarget( $nt ) ) {
2860 $errors[] = array('articleexists');
2863 $tp = $nt->getTitleProtection();
2864 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2865 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2866 $errors[] = array('cantmove-titleprotected');
2875 * Move a title to a new location
2877 * @param $nt \type{Title} the new title
2878 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2880 * @param $reason \type{\string} The reason for the move
2881 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2882 * Ignored if the user doesn't have the suppressredirect right.
2883 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2885 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2886 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2887 if( is_array( $err ) ) {
2891 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2892 $dbw = wfGetDB( DB_MASTER
);
2893 if( $this->getNamespace() == NS_FILE
) {
2894 $file = wfLocalFile( $this );
2895 if( $file->exists() ) {
2896 $status = $file->move( $nt );
2897 if( !$status->isOk() ) {
2898 return $status->getErrorsArray();
2903 $pageid = $this->getArticleID();
2904 $protected = $this->isProtected();
2905 if( $nt->exists() ) {
2906 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2907 $pageCountChange = ($createRedirect ?
0 : -1);
2908 } else { # Target didn't exist, do normal move.
2909 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2910 $pageCountChange = ($createRedirect ?
1 : 0);
2913 if( is_array( $err ) ) {
2916 $redirid = $this->getArticleID();
2918 // Category memberships include a sort key which may be customized.
2919 // If it's left as the default (the page title), we need to update
2920 // the sort key to match the new title.
2922 // Be careful to avoid resetting cl_timestamp, which may disturb
2923 // time-based lists on some sites.
2925 // Warning -- if the sort key is *explicitly* set to the old title,
2926 // we can't actually distinguish it from a default here, and it'll
2927 // be set to the new title even though it really shouldn't.
2928 // It'll get corrected on the next edit, but resetting cl_timestamp.
2929 $dbw->update( 'categorylinks',
2931 'cl_sortkey' => $nt->getPrefixedText(),
2932 'cl_timestamp=cl_timestamp' ),
2934 'cl_from' => $pageid,
2935 'cl_sortkey' => $this->getPrefixedText() ),
2939 # Protect the redirect title as the title used to be...
2940 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2942 'pr_page' => $redirid,
2943 'pr_type' => 'pr_type',
2944 'pr_level' => 'pr_level',
2945 'pr_cascade' => 'pr_cascade',
2946 'pr_user' => 'pr_user',
2947 'pr_expiry' => 'pr_expiry'
2949 array( 'pr_page' => $pageid ),
2953 # Update the protection log
2954 $log = new LogPage( 'protect' );
2955 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2956 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2957 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2961 $oldnamespace = $this->getNamespace() & ~
1;
2962 $newnamespace = $nt->getNamespace() & ~
1;
2963 $oldtitle = $this->getDBkey();
2964 $newtitle = $nt->getDBkey();
2966 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2967 WatchedItem
::duplicateEntries( $this, $nt );
2970 # Update search engine
2971 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2973 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2977 if( $this->isContentPage() && !$nt->isContentPage() ) {
2978 # No longer a content page
2979 # Not viewed, edited, removing
2980 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2981 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2982 # Now a content page
2983 # Not viewed, edited, adding
2984 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2985 } elseif( $pageCountChange ) {
2987 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2994 # Update message cache for interface messages
2995 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2996 global $wgMessageCache;
2998 # @bug 17860: old article can be deleted, if this the case,
2999 # delete it from message cache
3000 if ( $this->getArticleID() === 0 ) {
3001 $wgMessageCache->replace( $this->getDBkey(), false );
3003 $oldarticle = new Article( $this );
3004 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3007 $newarticle = new Article( $nt );
3008 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3012 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3017 * Move page to a title which is at present a redirect to the
3020 * @param $nt \type{Title} the page to move to, which should currently
3022 * @param $reason \type{\string} The reason for the move
3023 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3024 * Ignored if the user doesn't have the suppressredirect right
3026 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3027 global $wgUseSquid, $wgUser, $wgContLang;
3029 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3032 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3034 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3035 $comment = $wgContLang->truncate( $comment, 250 );
3037 $now = wfTimestampNow();
3038 $newid = $nt->getArticleID();
3039 $oldid = $this->getArticleID();
3040 $latest = $this->getLatestRevID();
3042 $dbw = wfGetDB( DB_MASTER
);
3044 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3045 $newns = $nt->getNamespace();
3046 $newdbk = $nt->getDBkey();
3048 # Delete the old redirect. We don't save it to history since
3049 # by definition if we've got here it's rather uninteresting.
3050 # We have to remove it so that the next step doesn't trigger
3051 # a conflict on the unique namespace+title index...
3052 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3053 if ( !$dbw->cascadingDeletes() ) {
3054 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3055 global $wgUseTrackbacks;
3056 if ($wgUseTrackbacks)
3057 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3058 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3059 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3060 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3061 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3062 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3063 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3064 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3066 // If the redirect was recently created, it may have an entry in recentchanges still
3067 $dbw->delete( 'recentchanges',
3068 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3072 # Save a null revision in the page's history notifying of the move
3073 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3074 $nullRevId = $nullRevision->insertOn( $dbw );
3076 $article = new Article( $this );
3077 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3079 # Change the name of the target page:
3080 $dbw->update( 'page',
3082 'page_touched' => $dbw->timestamp($now),
3083 'page_namespace' => $nt->getNamespace(),
3084 'page_title' => $nt->getDBkey(),
3085 'page_latest' => $nullRevId,
3087 /* WHERE */ array( 'page_id' => $oldid ),
3090 $nt->resetArticleID( $oldid );
3092 # Recreate the redirect, this time in the other direction.
3093 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3094 $mwRedir = MagicWord
::get( 'redirect' );
3095 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3096 $redirectArticle = new Article( $this );
3097 $newid = $redirectArticle->insertOn( $dbw );
3098 $redirectRevision = new Revision( array(
3100 'comment' => $comment,
3101 'text' => $redirectText ) );
3102 $redirectRevision->insertOn( $dbw );
3103 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3105 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3107 # Now, we record the link from the redirect to the new title.
3108 # It should have no other outgoing links...
3109 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3110 $dbw->insert( 'pagelinks',
3112 'pl_from' => $newid,
3113 'pl_namespace' => $nt->getNamespace(),
3114 'pl_title' => $nt->getDBkey() ),
3116 $redirectSuppressed = false;
3118 $this->resetArticleID( 0 );
3119 $redirectSuppressed = true;
3123 $log = new LogPage( 'move' );
3124 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3127 if ( $wgUseSquid ) {
3128 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3129 $u = new SquidUpdate( $urls );
3136 * Move page to non-existing title.
3138 * @param $nt \type{Title} the new Title
3139 * @param $reason \type{\string} The reason for the move
3140 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3141 * Ignored if the user doesn't have the suppressredirect right
3143 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3144 global $wgUseSquid, $wgUser, $wgContLang;
3146 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3148 $comment .= wfMsgExt( 'colon-separator',
3149 array( 'escapenoentities', 'content' ) );
3150 $comment .= $reason;
3152 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3153 $comment = $wgContLang->truncate( $comment, 250 );
3155 $newid = $nt->getArticleID();
3156 $oldid = $this->getArticleID();
3157 $latest = $this->getLatestRevId();
3159 $dbw = wfGetDB( DB_MASTER
);
3160 $now = $dbw->timestamp();
3162 # Save a null revision in the page's history notifying of the move
3163 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3164 if ( !is_object( $nullRevision ) ) {
3165 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3167 $nullRevId = $nullRevision->insertOn( $dbw );
3169 $article = new Article( $this );
3170 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3173 $dbw->update( 'page',
3175 'page_touched' => $now,
3176 'page_namespace' => $nt->getNamespace(),
3177 'page_title' => $nt->getDBkey(),
3178 'page_latest' => $nullRevId,
3180 /* WHERE */ array( 'page_id' => $oldid ),
3183 $nt->resetArticleID( $oldid );
3185 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3187 $mwRedir = MagicWord
::get( 'redirect' );
3188 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3189 $redirectArticle = new Article( $this );
3190 $newid = $redirectArticle->insertOn( $dbw );
3191 $redirectRevision = new Revision( array(
3193 'comment' => $comment,
3194 'text' => $redirectText ) );
3195 $redirectRevision->insertOn( $dbw );
3196 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3198 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3200 # Record the just-created redirect's linking to the page
3201 $dbw->insert( 'pagelinks',
3203 'pl_from' => $newid,
3204 'pl_namespace' => $nt->getNamespace(),
3205 'pl_title' => $nt->getDBkey() ),
3207 $redirectSuppressed = false;
3209 $this->resetArticleID( 0 );
3210 $redirectSuppressed = true;
3214 $log = new LogPage( 'move' );
3215 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3217 # Purge caches as per article creation
3218 Article
::onArticleCreate( $nt );
3220 # Purge old title from squid
3221 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3222 $this->purgeSquid();
3227 * Move this page's subpages to be subpages of $nt
3229 * @param $nt Title Move target
3230 * @param $auth bool Whether $wgUser's permissions should be checked
3231 * @param $reason string The reason for the move
3232 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3233 * Ignored if the user doesn't have the 'suppressredirect' right
3234 * @return mixed array with old page titles as keys, and strings (new page titles) or
3235 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3237 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3238 global $wgMaximumMovedPages;
3239 // Check permissions
3240 if( !$this->userCan( 'move-subpages' ) )
3241 return array( 'cant-move-subpages' );
3242 // Do the source and target namespaces support subpages?
3243 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3244 return array( 'namespace-nosubpages',
3245 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3246 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3247 return array( 'namespace-nosubpages',
3248 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3250 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3253 foreach( $subpages as $oldSubpage ) {
3255 if( $count > $wgMaximumMovedPages ) {
3256 $retval[$oldSubpage->getPrefixedTitle()] =
3257 array( 'movepage-max-pages',
3258 $wgMaximumMovedPages );
3262 // We don't know whether this function was called before
3263 // or after moving the root page, so check both
3265 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3266 $oldSubpage->getArticleID() == $nt->getArticleId() )
3267 // When moving a page to a subpage of itself,
3268 // don't move it twice
3270 $newPageName = preg_replace(
3271 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3272 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3273 $oldSubpage->getDBkey() );
3274 if( $oldSubpage->isTalkPage() ) {
3275 $newNs = $nt->getTalkPage()->getNamespace();
3277 $newNs = $nt->getSubjectPage()->getNamespace();
3279 # Bug 14385: we need makeTitleSafe because the new page names may
3280 # be longer than 255 characters.
3281 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3283 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3284 if( $success === true ) {
3285 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3287 $retval[$oldSubpage->getPrefixedText()] = $success;
3294 * Checks if this page is just a one-rev redirect.
3295 * Adds lock, so don't use just for light purposes.
3297 * @return \type{\bool}
3299 public function isSingleRevRedirect() {
3300 $dbw = wfGetDB( DB_MASTER
);
3302 $row = $dbw->selectRow( 'page',
3303 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3306 array( 'FOR UPDATE' )
3308 # Cache some fields we may want
3309 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3310 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3311 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3312 if( !$this->mRedirect
) {
3315 # Does the article have a history?
3316 $row = $dbw->selectField( array( 'page', 'revision'),
3318 array( 'page_namespace' => $this->getNamespace(),
3319 'page_title' => $this->getDBkey(),
3321 'page_latest != rev_id'
3324 array( 'FOR UPDATE' )
3326 # Return true if there was no history
3327 return ($row === false);
3331 * Checks if $this can be moved to a given Title
3332 * - Selects for update, so don't call it unless you mean business
3334 * @param $nt \type{Title} the new title to check
3335 * @return \type{\bool} TRUE or FALSE
3337 public function isValidMoveTarget( $nt ) {
3338 $dbw = wfGetDB( DB_MASTER
);
3339 # Is it an existsing file?
3340 if( $nt->getNamespace() == NS_FILE
) {
3341 $file = wfLocalFile( $nt );
3342 if( $file->exists() ) {
3343 wfDebug( __METHOD__
. ": file exists\n" );
3347 # Is it a redirect with no history?
3348 if( !$nt->isSingleRevRedirect() ) {
3349 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3352 # Get the article text
3353 $rev = Revision
::newFromTitle( $nt );
3354 $text = $rev->getText();
3355 # Does the redirect point to the source?
3356 # Or is it a broken self-redirect, usually caused by namespace collisions?
3358 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3359 $redirTitle = Title
::newFromText( $m[1] );
3360 if( !is_object( $redirTitle ) ||
3361 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3362 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3363 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3368 wfDebug( __METHOD__
. ": failsafe\n" );
3375 * Can this title be added to a user's watchlist?
3377 * @return \type{\bool} TRUE or FALSE
3379 public function isWatchable() {
3380 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3384 * Get categories to which this Title belongs and return an array of
3385 * categories' names.
3387 * @return \type{\array} array an array of parents in the form:
3388 * $parent => $currentarticle
3390 public function getParentCategories() {
3393 $titlekey = $this->getArticleId();
3394 $dbr = wfGetDB( DB_SLAVE
);
3395 $categorylinks = $dbr->tableName( 'categorylinks' );
3398 $sql = "SELECT * FROM $categorylinks"
3399 ." WHERE cl_from='$titlekey'"
3400 ." AND cl_from <> '0'"
3401 ." ORDER BY cl_sortkey";
3403 $res = $dbr->query( $sql );
3405 if( $dbr->numRows( $res ) > 0 ) {
3406 foreach( $res as $row )
3407 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3408 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3409 $dbr->freeResult( $res );
3417 * Get a tree of parent categories
3419 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3420 * @return \type{\array} Tree of parent categories
3422 public function getParentCategoryTree( $children = array() ) {
3424 $parents = $this->getParentCategories();
3427 foreach( $parents as $parent => $current ) {
3428 if ( array_key_exists( $parent, $children ) ) {
3429 # Circular reference
3430 $stack[$parent] = array();
3432 $nt = Title
::newFromText($parent);
3434 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3446 * Get an associative array for selecting this title from
3449 * @return \type{\array} Selection array
3451 public function pageCond() {
3452 if( $this->mArticleID
> 0 ) {
3453 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3454 return array( 'page_id' => $this->mArticleID
);
3456 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3461 * Get the revision ID of the previous revision
3463 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3464 * @param $flags \type{\int} GAID_FOR_UPDATE
3465 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3467 public function getPreviousRevisionID( $revId, $flags=0 ) {
3468 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3469 return $db->selectField( 'revision', 'rev_id',
3471 'rev_page' => $this->getArticleId($flags),
3472 'rev_id < ' . intval( $revId )
3475 array( 'ORDER BY' => 'rev_id DESC' )
3480 * Get the revision ID of the next revision
3482 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3483 * @param $flags \type{\int} GAID_FOR_UPDATE
3484 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3486 public function getNextRevisionID( $revId, $flags=0 ) {
3487 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3488 return $db->selectField( 'revision', 'rev_id',
3490 'rev_page' => $this->getArticleId($flags),
3491 'rev_id > ' . intval( $revId )
3494 array( 'ORDER BY' => 'rev_id' )
3499 * Get the first revision of the page
3501 * @param $flags \type{\int} GAID_FOR_UPDATE
3502 * @return Revision (or NULL if page doesn't exist)
3504 public function getFirstRevision( $flags=0 ) {
3505 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3506 $pageId = $this->getArticleId($flags);
3507 if( !$pageId ) return null;
3508 $row = $db->selectRow( 'revision', '*',
3509 array( 'rev_page' => $pageId ),
3511 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3516 return new Revision( $row );
3521 * Check if this is a new page
3525 public function isNewPage() {
3526 $dbr = wfGetDB( DB_SLAVE
);
3527 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3531 * Get the oldest revision timestamp of this page
3533 * @return String: MW timestamp
3535 public function getEarliestRevTime() {
3536 $dbr = wfGetDB( DB_SLAVE
);
3537 if( $this->exists() ) {
3538 $min = $dbr->selectField( 'revision',
3539 'MIN(rev_timestamp)',
3540 array( 'rev_page' => $this->getArticleId() ),
3542 return wfTimestampOrNull( TS_MW
, $min );
3548 * Get the number of revisions between the given revision IDs.
3549 * Used for diffs and other things that really need it.
3551 * @param $old \type{\int} Revision ID.
3552 * @param $new \type{\int} Revision ID.
3553 * @return \type{\int} Number of revisions between these IDs.
3555 public function countRevisionsBetween( $old, $new ) {
3556 $dbr = wfGetDB( DB_SLAVE
);
3557 return (int)$dbr->selectField( 'revision', 'count(*)',
3558 'rev_page = ' . intval( $this->getArticleId() ) .
3559 ' AND rev_id > ' . intval( $old ) .
3560 ' AND rev_id < ' . intval( $new ),
3566 * Compare with another title.
3568 * @param $title \type{Title}
3569 * @return \type{\bool} TRUE or FALSE
3571 public function equals( Title
$title ) {
3572 // Note: === is necessary for proper matching of number-like titles.
3573 return $this->getInterwiki() === $title->getInterwiki()
3574 && $this->getNamespace() == $title->getNamespace()
3575 && $this->getDBkey() === $title->getDBkey();
3579 * Callback for usort() to do title sorts by (namespace, title)
3581 * @return Integer: result of string comparison, or namespace comparison
3583 public static function compare( $a, $b ) {
3584 if( $a->getNamespace() == $b->getNamespace() ) {
3585 return strcmp( $a->getText(), $b->getText() );
3587 return $a->getNamespace() - $b->getNamespace();
3592 * Return a string representation of this title
3594 * @return \type{\string} String representation of this title
3596 public function __toString() {
3597 return $this->getPrefixedText();
3601 * Check if page exists. For historical reasons, this function simply
3602 * checks for the existence of the title in the page table, and will
3603 * thus return false for interwiki links, special pages and the like.
3604 * If you want to know if a title can be meaningfully viewed, you should
3605 * probably call the isKnown() method instead.
3607 * @return \type{\bool}
3609 public function exists() {
3610 return $this->getArticleId() != 0;
3614 * Should links to this title be shown as potentially viewable (i.e. as
3615 * "bluelinks"), even if there's no record by this title in the page
3618 * This function is semi-deprecated for public use, as well as somewhat
3619 * misleadingly named. You probably just want to call isKnown(), which
3620 * calls this function internally.
3622 * (ISSUE: Most of these checks are cheap, but the file existence check
3623 * can potentially be quite expensive. Including it here fixes a lot of
3624 * existing code, but we might want to add an optional parameter to skip
3625 * it and any other expensive checks.)
3627 * @return \type{\bool}
3629 public function isAlwaysKnown() {
3630 if( $this->mInterwiki
!= '' ) {
3631 return true; // any interwiki link might be viewable, for all we know
3633 switch( $this->mNamespace
) {
3636 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3638 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3640 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3642 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3643 // the full l10n of that language to be loaded. That takes much memory and
3644 // isn't needed. So we strip the language part away.
3645 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3646 return (bool)wfMsgWeirdKey( $basename ); // known system message
3653 * Does this title refer to a page that can (or might) be meaningfully
3654 * viewed? In particular, this function may be used to determine if
3655 * links to the title should be rendered as "bluelinks" (as opposed to
3656 * "redlinks" to non-existent pages).
3658 * @return \type{\bool}
3660 public function isKnown() {
3661 return $this->exists() ||
$this->isAlwaysKnown();
3665 * Does this page have source text?
3669 public function hasSourceText() {
3670 if ( $this->exists() )
3673 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3674 // If the page doesn't exist but is a known system message, default
3675 // message content will be displayed, same for language subpages
3676 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3677 // causes the full l10n of that language to be loaded. That takes much
3678 // memory and isn't needed. So we strip the language part away.
3679 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3680 return (bool)wfMsgWeirdKey( $basename );
3687 * Is this in a namespace that allows actual pages?
3689 * @return \type{\bool}
3690 * @internal note -- uses hardcoded namespace index instead of constants
3692 public function canExist() {
3693 return $this->mNamespace
>=0 && $this->mNamespace
!= NS_MEDIA
;
3697 * Update page_touched timestamps and send squid purge messages for
3698 * pages linking to this title. May be sent to the job queue depending
3699 * on the number of links. Typically called on create and delete.
3701 public function touchLinks() {
3702 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3705 if ( $this->getNamespace() == NS_CATEGORY
) {
3706 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3712 * Get the last touched timestamp
3714 * @param $db DatabaseBase: optional db
3715 * @return \type{\string} Last touched timestamp
3717 public function getTouched( $db = null ) {
3718 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3719 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3724 * Get the timestamp when this page was updated since the user last saw it.
3727 * @return Mixed: string/null
3729 public function getNotificationTimestamp( $user = null ) {
3730 global $wgUser, $wgShowUpdatedMarker;
3731 // Assume current user if none given
3732 if( !$user ) $user = $wgUser;
3733 // Check cache first
3734 $uid = $user->getId();
3735 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3736 return $this->mNotificationTimestamp
[$uid];
3738 if( !$uid ||
!$wgShowUpdatedMarker ) {
3739 return $this->mNotificationTimestamp
[$uid] = false;
3741 // Don't cache too much!
3742 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3743 $this->mNotificationTimestamp
= array();
3745 $dbr = wfGetDB( DB_SLAVE
);
3746 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3747 'wl_notificationtimestamp',
3748 array( 'wl_namespace' => $this->getNamespace(),
3749 'wl_title' => $this->getDBkey(),
3750 'wl_user' => $user->getId()
3754 return $this->mNotificationTimestamp
[$uid];
3758 * Get the trackback URL for this page
3760 * @return \type{\string} Trackback URL
3762 public function trackbackURL() {
3763 global $wgScriptPath, $wgServer, $wgScriptExtension;
3765 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3766 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3770 * Get the trackback RDF for this page
3772 * @return \type{\string} Trackback RDF
3774 public function trackbackRDF() {
3775 $url = htmlspecialchars($this->getFullURL());
3776 $title = htmlspecialchars($this->getText());
3777 $tburl = $this->trackbackURL();
3779 // Autodiscovery RDF is placed in comments so HTML validator
3780 // won't barf. This is a rather icky workaround, but seems
3781 // frequently used by this kind of RDF thingy.
3783 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3785 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3786 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3787 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3790 dc:identifier=\"$url\"
3792 trackback:ping=\"$tburl\" />
3798 * Generate strings used for xml 'id' names in monobook tabs
3800 * @param $prepend string defaults to 'nstab-'
3801 * @return \type{\string} XML 'id' name
3803 public function getNamespaceKey( $prepend = 'nstab-' ) {
3805 // Gets the subject namespace if this title
3806 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3807 // Checks if cononical namespace name exists for namespace
3808 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3809 // Uses canonical namespace name
3810 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3812 // Uses text of namespace
3813 $namespaceKey = $this->getSubjectNsText();
3815 // Makes namespace key lowercase
3816 $namespaceKey = $wgContLang->lc( $namespaceKey );
3818 if ( $namespaceKey == '' ) {
3819 $namespaceKey = 'main';
3821 // Changes file to image for backwards compatibility
3822 if ( $namespaceKey == 'file' ) {
3823 $namespaceKey = 'image';
3825 return $prepend . $namespaceKey;
3829 * Returns true if this is a special page.
3833 public function isSpecialPage( ) {
3834 return $this->getNamespace() == NS_SPECIAL
;
3838 * Returns true if this title resolves to the named special page
3840 * @param $name \type{\string} The special page name
3843 public function isSpecial( $name ) {
3844 if ( $this->getNamespace() == NS_SPECIAL
) {
3845 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3846 if ( $name == $thisName ) {
3854 * If the Title refers to a special page alias which is not the local default,
3856 * @return \type{Title} A new Title which points to the local default.
3857 * Otherwise, returns $this.
3859 public function fixSpecialName() {
3860 if ( $this->getNamespace() == NS_SPECIAL
) {
3861 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3862 if ( $canonicalName ) {
3863 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3864 if ( $localName != $this->mDbkeyform
) {
3865 return Title
::makeTitle( NS_SPECIAL
, $localName );
3873 * Is this Title in a namespace which contains content?
3874 * In other words, is this a content page, for the purposes of calculating
3877 * @return \type{\bool}
3879 public function isContentPage() {
3880 return MWNamespace
::isContent( $this->getNamespace() );
3884 * Get all extant redirects to this Title
3886 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3887 * NULL to consider all namespaces
3888 * @return \type{\arrayof{Title}} Redirects to this title
3890 public function getRedirectsHere( $ns = null ) {
3893 $dbr = wfGetDB( DB_SLAVE
);
3895 'rd_namespace' => $this->getNamespace(),
3896 'rd_title' => $this->getDBkey(),
3899 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3901 $res = $dbr->select(
3902 array( 'redirect', 'page' ),
3903 array( 'page_namespace', 'page_title' ),
3909 foreach( $res as $row ) {
3910 $redirs[] = self
::newFromRow( $row );
3916 * Check if this Title is a valid redirect target
3918 * @return \type{\bool}
3920 public function isValidRedirectTarget() {
3921 global $wgInvalidRedirectTargets;
3923 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3924 if( $this->isSpecial( 'Userlogout' ) ) {
3928 foreach( $wgInvalidRedirectTargets as $target ) {
3929 if( $this->isSpecial( $target ) ) {
3938 * Get a backlink cache object
3940 * @return object BacklinkCache
3942 function getBacklinkCache() {
3943 if ( is_null( $this->mBacklinkCache
) ) {
3944 $this->mBacklinkCache
= new BacklinkCache( $this );
3946 return $this->mBacklinkCache
;
3950 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3955 public function canUseNoindex(){
3956 global $wgArticleRobotPolicies, $wgContentNamespaces,
3957 $wgExemptFromUserRobotsControl;
3959 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3960 ?
$wgContentNamespaces
3961 : $wgExemptFromUserRobotsControl;
3963 return !in_array( $this->mNamespace
, $bannedNamespaces );
3968 * Returns restriction types for the current Title
3970 * @return array applicable restriction types
3972 public function getRestrictionTypes() {
3973 global $wgRestrictionTypes;
3974 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3976 if ( $this->getNamespace() == NS_FILE
) {
3977 $types[] = 'upload';
3980 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );