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 $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
61 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
62 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
63 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
64 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
65 # Don't change the following default, NS_MAIN is hardcoded in several
66 # places. See bug 696.
67 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
68 # Zero except in {{transclusion}} tags
69 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
70 var $mLength = -1; ///< The page length, 0 for special pages
71 var $mRedirect = null; ///< Is the article at this title a redirect?
72 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
73 var $mBacklinkCache = null; ///< Cache of links to this title
81 /* private */ function __construct() {}
84 * Create a new Title from a prefixed DB key
85 * @param $key \type{\string} The database key, which has underscores
86 * instead of spaces, possibly including namespace and
88 * @return \type{Title} the new object, or NULL on an error
90 public static function newFromDBkey( $key ) {
92 $t->mDbkeyform
= $key;
93 if( $t->secureAndSplit() )
100 * Create a new Title from text, such as what one would find in a link. De-
101 * codes any HTML entities in the text.
103 * @param $text string The link text; spaces, prefixes, and an
104 * initial ':' indicating the main namespace are accepted.
105 * @param $defaultNamespace int The namespace to use if none is speci-
106 * fied by a prefix. If you want to force a specific namespace even if
107 * $text might begin with a namespace prefix, use makeTitle() or
109 * @return Title The new object, or null on an error.
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
112 if( is_object( $text ) ) {
113 throw new MWException( 'Title::newFromText given an object' );
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
122 * In theory these are value objects and won't get changed...
124 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
125 return Title
::$titleCache[$text];
129 * Convert things like é ā or 〗 into real text...
131 $filteredText = Sanitizer
::decodeCharReferences( $text );
134 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace
= $defaultNamespace;
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN
) {
140 if( $cachedcount >= self
::CACHE_MAX
) {
141 # Avoid memory leaks on mass operations...
142 Title
::$titleCache = array();
146 Title
::$titleCache[$text] =& $t;
156 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
158 * Example of wrong and broken code:
159 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
161 * Example of right code:
162 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
164 * Create a new Title from URL-encoded text. Ensures that
165 * the given title's length does not exceed the maximum.
166 * @param $url \type{\string} the title, as might be taken from a URL
167 * @return \type{Title} the new object, or NULL on an error
169 public static function newFromURL( $url ) {
170 global $wgLegalTitleChars;
173 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
174 # but some URLs used it as a space replacement and they still come
175 # from some external search tools.
176 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
177 $url = str_replace( '+', ' ', $url );
180 $t->mDbkeyform
= str_replace( ' ', '_', $url );
181 if( $t->secureAndSplit() ) {
189 * Create a new Title from an article ID
191 * @param $id \type{\int} the page_id corresponding to the Title to create
192 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
193 * @return \type{Title} the new object, or NULL on an error
195 public static function newFromID( $id, $flags = 0 ) {
196 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
197 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
198 if( $row !== false ) {
199 $title = Title
::newFromRow( $row );
207 * Make an array of titles from an array of IDs
208 * @param $ids \type{\arrayof{\int}} Array of IDs
209 * @return \type{\arrayof{Title}} Array of Titles
211 public static function newFromIDs( $ids ) {
212 if ( !count( $ids ) ) {
215 $dbr = wfGetDB( DB_SLAVE
);
216 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
217 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
220 foreach( $res as $row ) {
221 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
227 * Make a Title object from a DB row
228 * @param $row \type{Row} (needs at least page_title,page_namespace)
229 * @return \type{Title} corresponding Title
231 public static function newFromRow( $row ) {
232 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
234 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
235 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
236 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
237 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
243 * Create a new Title from a namespace index and a DB key.
244 * It's assumed that $ns and $title are *valid*, for instance when
245 * they came directly from the database or a special page name.
246 * For convenience, spaces are converted to underscores so that
247 * eg user_text fields can be used directly.
249 * @param $ns \type{\int} the namespace of the article
250 * @param $title \type{\string} the unprefixed database key form
251 * @param $fragment \type{\string} The link fragment (after the "#")
252 * @return \type{Title} the new object
254 public static function &makeTitle( $ns, $title, $fragment = '' ) {
257 $t->mFragment
= $fragment;
258 $t->mNamespace
= $ns = intval( $ns );
259 $t->mDbkeyform
= str_replace( ' ', '_', $title );
260 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
261 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
262 $t->mTextform
= str_replace( '_', ' ', $title );
267 * Create a new Title from a namespace index and a DB key.
268 * The parameters will be checked for validity, which is a bit slower
269 * than makeTitle() but safer for user-provided data.
271 * @param $ns \type{\int} the namespace of the article
272 * @param $title \type{\string} the database key form
273 * @param $fragment \type{\string} The link fragment (after the "#")
274 * @return \type{Title} the new object, or NULL on an error
276 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
278 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
279 if( $t->secureAndSplit() ) {
287 * Create a new Title for the Main Page
288 * @return \type{Title} the new object
290 public static function newMainPage() {
291 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
292 // Don't give fatal errors if the message is broken
294 $title = Title
::newFromText( 'Main Page' );
300 * Extract a redirect destination from a string and return the
301 * Title, or null if the text doesn't contain a valid redirect
302 * This will only return the very next target, useful for
303 * the redirect table and other checks that don't need full recursion
305 * @param $text \type{\string} Text with possible redirect
306 * @return \type{Title} The corresponding Title
308 public static function newFromRedirect( $text ) {
309 return self
::newFromRedirectInternal( $text );
313 * Extract a redirect destination from a string and return the
314 * Title, or null if the text doesn't contain a valid redirect
315 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
316 * in order to provide (hopefully) the Title of the final destination instead of another redirect
318 * @param $text \type{\string} Text with possible redirect
319 * @return \type{Title} The corresponding Title
321 public static function newFromRedirectRecurse( $text ) {
322 $titles = self
::newFromRedirectArray( $text );
323 return $titles ?
array_pop( $titles ) : null;
327 * Extract a redirect destination from a string and return an
328 * array of Titles, or null if the text doesn't contain a valid redirect
329 * The last element in the array is the final destination after all redirects
330 * have been resolved (up to $wgMaxRedirects times)
332 * @param $text \type{\string} Text with possible redirect
333 * @return \type{\array} Array of Titles, with the destination last
335 public static function newFromRedirectArray( $text ) {
336 global $wgMaxRedirects;
337 // are redirects disabled?
338 if( $wgMaxRedirects < 1 )
340 $title = self
::newFromRedirectInternal( $text );
341 if( is_null( $title ) )
343 // recursive check to follow double redirects
344 $recurse = $wgMaxRedirects;
345 $titles = array( $title );
346 while( --$recurse > 0 ) {
347 if( $title->isRedirect() ) {
348 $article = new Article( $title, 0 );
349 $newtitle = $article->getRedirectTarget();
353 // Redirects to some special pages are not permitted
354 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
355 // the new title passes the checks, so make that our current title so that further recursion can be checked
357 $titles[] = $newtitle;
366 * Really extract the redirect destination
367 * Do not call this function directly, use one of the newFromRedirect* functions above
369 * @param $text \type{\string} Text with possible redirect
370 * @return \type{Title} The corresponding Title
372 protected static function newFromRedirectInternal( $text ) {
373 $redir = MagicWord
::get( 'redirect' );
375 if( $redir->matchStartAndRemove( $text ) ) {
376 // Extract the first link and see if it's usable
377 // Ensure that it really does come directly after #REDIRECT
378 // Some older redirects included a colon, so don't freak about that!
380 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
381 // Strip preceding colon used to "escape" categories, etc.
382 // and URL-decode links
383 if( strpos( $m[1], '%' ) !== false ) {
384 // Match behavior of inline link parsing here;
385 // don't interpret + as " " most of the time!
386 // It might be safe to just use rawurldecode instead, though.
387 $m[1] = urldecode( ltrim( $m[1], ':' ) );
389 $title = Title
::newFromText( $m[1] );
390 // If the title is a redirect to bad special pages or is invalid, return null
391 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
400 #----------------------------------------------------------------------------
402 #----------------------------------------------------------------------------
405 * Get the prefixed DB key associated with an ID
406 * @param $id \type{\int} the page_id of the article
407 * @return \type{Title} an object representing the article, or NULL
408 * if no such article was found
410 public static function nameOf( $id ) {
411 $dbr = wfGetDB( DB_SLAVE
);
413 $s = $dbr->selectRow( 'page',
414 array( 'page_namespace','page_title' ),
415 array( 'page_id' => $id ),
417 if ( $s === false ) { return null; }
419 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
424 * Get a regex character class describing the legal characters in a link
425 * @return \type{\string} the list of characters, not delimited
427 public static function legalChars() {
428 global $wgLegalTitleChars;
429 return $wgLegalTitleChars;
433 * Get a string representation of a title suitable for
434 * including in a search index
436 * @param $ns \type{\int} a namespace index
437 * @param $title \type{\string} text-form main part
438 * @return \type{\string} a stripped-down title string ready for the
441 public static function indexTitle( $ns, $title ) {
444 $lc = SearchEngine
::legalSearchChars() . '&#;';
445 $t = $wgContLang->normalizeForSearch( $title );
446 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
447 $t = $wgContLang->lc( $t );
450 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
451 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
453 $t = preg_replace( "/\\s+/", ' ', $t );
455 if ( $ns == NS_FILE
) {
456 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
462 * Make a prefixed DB key from a DB key and a namespace index
463 * @param $ns \type{\int} numerical representation of the namespace
464 * @param $title \type{\string} the DB key form the title
465 * @param $fragment \type{\string} The link fragment (after the "#")
466 * @return \type{\string} the prefixed form of the title
468 public static function makeName( $ns, $title, $fragment = '' ) {
471 $namespace = $wgContLang->getNsText( $ns );
472 $name = $namespace == '' ?
$title : "$namespace:$title";
473 if ( strval( $fragment ) != '' ) {
474 $name .= '#' . $fragment;
480 * Determine whether the object refers to a page within
483 * @return \type{\bool} TRUE if this is an in-project interwiki link
484 * or a wikilink, FALSE otherwise
486 public function isLocal() {
487 if ( $this->mInterwiki
!= '' ) {
488 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
495 * Determine whether the object refers to a page within
496 * this project and is transcludable.
498 * @return \type{\bool} TRUE if this is transcludable
500 public function isTrans() {
501 if ($this->mInterwiki
== '')
504 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
508 * Escape a text fragment, say from a link, for a URL
510 * @param $fragment string containing a URL or link fragment (after the "#")
511 * @return string escaped string
513 static function escapeFragmentForURL( $fragment ) {
514 # Note that we don't urlencode the fragment. urlencoded Unicode
515 # fragments appear not to work in IE (at least up to 7) or in at least
516 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
517 # to care if they aren't encoded.
518 return Sanitizer
::escapeId( $fragment, 'noninitial' );
521 #----------------------------------------------------------------------------
523 #----------------------------------------------------------------------------
525 /** Simple accessors */
527 * Get the text form (spaces not underscores) of the main part
528 * @return \type{\string} Main part of the title
530 public function getText() { return $this->mTextform
; }
532 * Get the URL-encoded form of the main part
533 * @return \type{\string} Main part of the title, URL-encoded
535 public function getPartialURL() { return $this->mUrlform
; }
537 * Get the main part with underscores
538 * @return \type{\string} Main part of the title, with underscores
540 public function getDBkey() { return $this->mDbkeyform
; }
542 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
543 * @return \type{\int} Namespace index
545 public function getNamespace() { return $this->mNamespace
; }
547 * Get the namespace text
548 * @return \type{\string} Namespace text
550 public function getNsText() {
553 if ( $this->mInterwiki
!= '' ) {
554 // This probably shouldn't even happen. ohh man, oh yuck.
555 // But for interwiki transclusion it sometimes does.
556 // Shit. Shit shit shit.
558 // Use the canonical namespaces if possible to try to
559 // resolve a foreign namespace.
560 if( MWNamespace
::exists( $this->mNamespace
) ) {
561 return MWNamespace
::getCanonicalName( $this->mNamespace
);
564 return $wgContLang->getNsText( $this->mNamespace
);
567 * Get the DB key with the initial letter case as specified by the user
568 * @return \type{\string} DB key
570 function getUserCaseDBKey() {
571 return $this->mUserCaseDBKey
;
574 * Get the namespace text of the subject (rather than talk) page
575 * @return \type{\string} Namespace text
577 public function getSubjectNsText() {
579 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
582 * Get the namespace text of the talk page
583 * @return \type{\string} Namespace text
585 public function getTalkNsText() {
587 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
590 * Could this title have a corresponding talk page?
591 * @return \type{\bool} TRUE or FALSE
593 public function canTalk() {
594 return( MWNamespace
::canTalk( $this->mNamespace
) );
597 * Get the interwiki prefix (or null string)
598 * @return \type{\string} Interwiki prefix
600 public function getInterwiki() { return $this->mInterwiki
; }
602 * Get the Title fragment (i.e.\ the bit after the #) in text form
603 * @return \type{\string} Title fragment
605 public function getFragment() { return $this->mFragment
; }
607 * Get the fragment in URL form, including the "#" character if there is one
608 * @return \type{\string} Fragment in URL form
610 public function getFragmentForURL() {
611 if ( $this->mFragment
== '' ) {
614 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
618 * Get the default namespace index, for when there is no namespace
619 * @return \type{\int} Default namespace index
621 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
624 * Get title for search index
625 * @return \type{\string} a stripped-down title string ready for the
628 public function getIndexTitle() {
629 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
633 * Get the prefixed database key form
634 * @return \type{\string} the prefixed title, with underscores and
635 * any interwiki and namespace prefixes
637 public function getPrefixedDBkey() {
638 $s = $this->prefix( $this->mDbkeyform
);
639 $s = str_replace( ' ', '_', $s );
644 * Get the prefixed title with spaces.
645 * This is the form usually used for display
646 * @return \type{\string} the prefixed title, with spaces
648 public function getPrefixedText() {
649 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
650 $s = $this->prefix( $this->mTextform
);
651 $s = str_replace( '_', ' ', $s );
652 $this->mPrefixedText
= $s;
654 return $this->mPrefixedText
;
658 * Get the prefixed title with spaces, plus any fragment
659 * (part beginning with '#')
660 * @return \type{\string} the prefixed title, with spaces and
661 * the fragment, including '#'
663 public function getFullText() {
664 $text = $this->getPrefixedText();
665 if( $this->mFragment
!= '' ) {
666 $text .= '#' . $this->mFragment
;
672 * Get the base name, i.e. the leftmost parts before the /
673 * @return \type{\string} Base name
675 public function getBaseText() {
676 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
677 return $this->getText();
680 $parts = explode( '/', $this->getText() );
681 # Don't discard the real title if there's no subpage involved
682 if( count( $parts ) > 1 )
683 unset( $parts[ count( $parts ) - 1 ] );
684 return implode( '/', $parts );
688 * Get the lowest-level subpage name, i.e. the rightmost part after /
689 * @return \type{\string} Subpage name
691 public function getSubpageText() {
692 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
693 return( $this->mTextform
);
695 $parts = explode( '/', $this->mTextform
);
696 return( $parts[ count( $parts ) - 1 ] );
700 * Get a URL-encoded form of the subpage text
701 * @return \type{\string} URL-encoded subpage name
703 public function getSubpageUrlForm() {
704 $text = $this->getSubpageText();
705 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
710 * Get a URL-encoded title (not an actual URL) including interwiki
711 * @return \type{\string} the URL-encoded form
713 public function getPrefixedURL() {
714 $s = $this->prefix( $this->mDbkeyform
);
715 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
720 * Get a real URL referring to this title, with interwiki link and
723 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
724 * links. Can be specified as an associative array as well, e.g.,
725 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
726 * @param $variant \type{\string} language variant of url (for sr, zh..)
727 * @return \type{\string} the URL
729 public function getFullURL( $query = '', $variant = false ) {
730 global $wgContLang, $wgServer, $wgRequest;
732 if( is_array( $query ) ) {
733 $query = wfArrayToCGI( $query );
736 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
738 $url = $this->getLocalURL( $query, $variant );
740 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
741 // Correct fix would be to move the prepending elsewhere.
742 if ($wgRequest->getVal('action') != 'render') {
743 $url = $wgServer . $url;
746 $baseUrl = $interwiki->getURL( );
748 $namespace = wfUrlencode( $this->getNsText() );
749 if ( $namespace != '' ) {
750 # Can this actually happen? Interwikis shouldn't be parsed.
751 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
754 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
755 $url = wfAppendQuery( $url, $query );
758 # Finally, add the fragment.
759 $url .= $this->getFragmentForURL();
761 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
766 * Get a URL with no fragment or server name. If this page is generated
767 * with action=render, $wgServer is prepended.
768 * @param mixed $query an optional query string; if not specified,
769 * $wgArticlePath will be used. Can be specified as an associative array
770 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
772 * @param $variant \type{\string} language variant of url (for sr, zh..)
773 * @return \type{\string} the URL
775 public function getLocalURL( $query = '', $variant = false ) {
776 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
777 global $wgVariantArticlePath, $wgContLang, $wgUser;
779 if( is_array( $query ) ) {
780 $query = wfArrayToCGI( $query );
783 // internal links should point to same variant as current page (only anonymous users)
784 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
785 $pref = $wgContLang->getPreferredVariant(false);
786 if($pref != $wgContLang->getCode())
790 if ( $this->isExternal() ) {
791 $url = $this->getFullURL();
793 // This is currently only used for edit section links in the
794 // context of interwiki transclusion. In theory we should
795 // append the query to the end of any existing query string,
796 // but interwiki transclusion is already broken in that case.
800 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
801 if ( $query == '' ) {
802 if( $variant != false && $wgContLang->hasVariants() ) {
803 if( $wgVariantArticlePath == false ) {
804 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
806 $variantArticlePath = $wgVariantArticlePath;
808 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
809 $url = str_replace( '$1', $dbkey, $url );
811 $url = str_replace( '$1', $dbkey, $wgArticlePath );
814 global $wgActionPaths;
817 if( !empty( $wgActionPaths ) &&
818 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
820 $action = urldecode( $matches[2] );
821 if( isset( $wgActionPaths[$action] ) ) {
822 $query = $matches[1];
823 if( isset( $matches[4] ) ) $query .= $matches[4];
824 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
826 $url = wfAppendQuery( $url, $query );
830 if ( $url === false ) {
831 if ( $query == '-' ) {
834 $url = "{$wgScript}?title={$dbkey}&{$query}";
838 // FIXME: this causes breakage in various places when we
839 // actually expected a local URL and end up with dupe prefixes.
840 if ($wgRequest->getVal('action') == 'render') {
841 $url = $wgServer . $url;
844 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
849 * Get a URL that's the simplest URL that will be valid to link, locally,
850 * to the current Title. It includes the fragment, but does not include
851 * the server unless action=render is used (or the link is external). If
852 * there's a fragment but the prefixed text is empty, we just return a link
855 * The result obviously should not be URL-escaped, but does need to be
856 * HTML-escaped if it's being output in HTML.
858 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
859 * query string. Keys and values will be escaped.
860 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
861 * for external links. Default is "false" (same variant as current page,
862 * for anonymous users).
863 * @return \type{\string} the URL
865 public function getLinkUrl( $query = array(), $variant = false ) {
866 wfProfileIn( __METHOD__
);
867 if( $this->isExternal() ) {
868 $ret = $this->getFullURL( $query );
869 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
870 $ret = $this->getFragmentForURL();
872 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
874 wfProfileOut( __METHOD__
);
879 * Get an HTML-escaped version of the URL form, suitable for
880 * using in a link, without a server name or fragment
881 * @param $query \type{\string} an optional query string
882 * @return \type{\string} the URL
884 public function escapeLocalURL( $query = '' ) {
885 return htmlspecialchars( $this->getLocalURL( $query ) );
889 * Get an HTML-escaped version of the URL form, suitable for
890 * using in a link, including the server name and fragment
892 * @param $query \type{\string} an optional query string
893 * @return \type{\string} the URL
895 public function escapeFullURL( $query = '' ) {
896 return htmlspecialchars( $this->getFullURL( $query ) );
900 * Get the URL form for an internal link.
901 * - Used in various Squid-related code, in case we have a different
902 * internal hostname for the server from the exposed one.
904 * @param $query \type{\string} an optional query string
905 * @param $variant \type{\string} language variant of url (for sr, zh..)
906 * @return \type{\string} the URL
908 public function getInternalURL( $query = '', $variant = false ) {
909 global $wgInternalServer;
910 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
911 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
916 * Get the edit URL for this Title
917 * @return \type{\string} the URL, or a null string if this is an
920 public function getEditURL() {
921 if ( $this->mInterwiki
!= '' ) { return ''; }
922 $s = $this->getLocalURL( 'action=edit' );
928 * Get the HTML-escaped displayable text form.
929 * Used for the title field in <a> tags.
930 * @return \type{\string} the text, including any prefixes
932 public function getEscapedText() {
933 return htmlspecialchars( $this->getPrefixedText() );
937 * Is this Title interwiki?
938 * @return \type{\bool}
940 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
943 * Is this page "semi-protected" - the *only* protection is autoconfirm?
945 * @param $action \type{\string} Action to check (default: edit)
946 * @return \type{\bool}
948 public function isSemiProtected( $action = 'edit' ) {
949 if( $this->exists() ) {
950 $restrictions = $this->getRestrictions( $action );
951 if( count( $restrictions ) > 0 ) {
952 foreach( $restrictions as $restriction ) {
953 if( strtolower( $restriction ) != 'autoconfirmed' )
962 # If it doesn't exist, it can't be protected
968 * Does the title correspond to a protected article?
969 * @param $action \type{\string} the action the page is protected from,
970 * by default checks all actions.
971 * @return \type{\bool}
973 public function isProtected( $action = '' ) {
974 global $wgRestrictionLevels;
976 $restrictionTypes = $this->getRestrictionTypes();
978 # Special pages have inherent protection
979 if( $this->getNamespace() == NS_SPECIAL
)
982 # Check regular protection levels
983 foreach( $restrictionTypes as $type ){
984 if( $action == $type ||
$action == '' ) {
985 $r = $this->getRestrictions( $type );
986 foreach( $wgRestrictionLevels as $level ) {
987 if( in_array( $level, $r ) && $level != '' ) {
998 * Is this a conversion table for the LanguageConverter?
999 * @return \type{\bool}
1001 public function isConversionTable() {
1002 if($this->getNamespace() == NS_MEDIAWIKI
1003 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1011 * Is $wgUser watching this page?
1012 * @return \type{\bool}
1014 public function userIsWatching() {
1017 if ( is_null( $this->mWatched
) ) {
1018 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1019 $this->mWatched
= false;
1021 $this->mWatched
= $wgUser->isWatched( $this );
1024 return $this->mWatched
;
1028 * Can $wgUser perform $action on this page?
1029 * This skips potentially expensive cascading permission checks
1030 * as well as avoids expensive error formatting
1032 * Suitable for use for nonessential UI controls in common cases, but
1033 * _not_ for functional access control.
1035 * May provide false positives, but should never provide a false negative.
1037 * @param $action \type{\string} action that permission needs to be checked for
1038 * @return \type{\bool}
1040 public function quickUserCan( $action ) {
1041 return $this->userCan( $action, false );
1045 * Determines if $wgUser is unable to edit this page because it has been protected
1046 * by $wgNamespaceProtection.
1048 * @return \type{\bool}
1050 public function isNamespaceProtected() {
1051 global $wgNamespaceProtection, $wgUser;
1052 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1053 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1054 if( $right != '' && !$wgUser->isAllowed( $right ) )
1062 * Can $wgUser perform $action on this page?
1063 * @param $action \type{\string} action that permission needs to be checked for
1064 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1065 * @return \type{\bool}
1067 public function userCan( $action, $doExpensiveQueries = true ) {
1069 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1073 * Can $user perform $action on this page?
1075 * FIXME: This *does not* check throttles (User::pingLimiter()).
1077 * @param $action \type{\string}action that permission needs to be checked for
1078 * @param $user \type{User} user to check
1079 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1080 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1081 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1083 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1084 if( !StubObject
::isRealObject( $user ) ) {
1085 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1087 $wgUser->_unstub( '', 5 );
1090 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1094 global $wgEmailConfirmToEdit;
1096 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1097 $errors[] = array( 'confirmedittext' );
1100 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1101 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1102 $block = $user->mBlock
;
1104 // This is from OutputPage::blockedPage
1105 // Copied at r23888 by werdna
1107 $id = $user->blockedBy();
1108 $reason = $user->blockedFor();
1109 if( $reason == '' ) {
1110 $reason = wfMsg( 'blockednoreason' );
1114 if ( is_numeric( $id ) ) {
1115 $name = User
::whoIs( $id );
1120 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1121 $blockid = $block->mId
;
1122 $blockExpiry = $user->mBlock
->mExpiry
;
1123 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1125 if ( $blockExpiry == 'infinity' ) {
1126 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1127 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1129 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1130 if ( strpos( $option, ':' ) == false )
1133 list ($show, $value) = explode( ":", $option );
1135 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1136 $blockExpiry = $show;
1141 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1144 $intended = $user->mBlock
->mAddress
;
1146 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1147 $blockid, $blockExpiry, $intended, $blockTimestamp );
1150 // Remove the errors being ignored.
1152 foreach( $errors as $index => $error ) {
1153 $error_key = is_array($error) ?
$error[0] : $error;
1155 if (in_array( $error_key, $ignoreErrors )) {
1156 unset($errors[$index]);
1164 * Can $user perform $action on this page? This is an internal function,
1165 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1166 * checks on wfReadOnly() and blocks)
1168 * @param $action \type{\string} action that permission needs to be checked for
1169 * @param $user \type{User} user to check
1170 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1171 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1172 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1174 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1175 wfProfileIn( __METHOD__
);
1179 // First stop is permissions checks, which fail most often, and which are easiest to test.
1180 if ( $action == 'move' ) {
1181 if( !$user->isAllowed( 'move-rootuserpages' )
1182 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1184 // Show user page-specific message only if the user can move other pages
1185 $errors[] = array( 'cant-move-user-page' );
1188 // Check if user is allowed to move files if it's a file
1189 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1190 $errors[] = array( 'movenotallowedfile' );
1193 if( !$user->isAllowed( 'move' ) ) {
1194 // User can't move anything
1195 global $wgGroupPermissions;
1196 $userCanMove = false;
1197 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1198 $userCanMove = $wgGroupPermissions['user']['move'];
1200 $autoconfirmedCanMove = false;
1201 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1202 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1204 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1205 // custom message if logged-in users without any special rights can move
1206 $errors[] = array ( 'movenologintext' );
1208 $errors[] = array ('movenotallowed');
1211 } elseif ( $action == 'create' ) {
1212 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1213 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1215 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1217 } elseif( $action == 'move-target' ) {
1218 if( !$user->isAllowed( 'move' ) ) {
1219 // User can't move anything
1220 $errors[] = array ('movenotallowed');
1221 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1222 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1224 // Show user page-specific message only if the user can move other pages
1225 $errors[] = array( 'cant-move-to-user-page' );
1227 } elseif( !$user->isAllowed( $action ) ) {
1230 // We avoid expensive display logic for quickUserCan's and such
1233 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1234 User
::getGroupsWithPermission( $action ) );
1241 $wgLang->commaList( $groups ),
1245 $return = array( "badaccess-group0" );
1247 $errors[] = $return;
1250 # Short-circuit point
1251 if( $short && count($errors) > 0 ) {
1252 wfProfileOut( __METHOD__
);
1256 // Use getUserPermissionsErrors instead
1257 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1258 wfProfileOut( __METHOD__
);
1259 return $result ?
array() : array( array( 'badaccess-group0' ) );
1261 // Check getUserPermissionsErrors hook
1262 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1263 if( is_array($result) && count($result) && !is_array($result[0]) )
1264 $errors[] = $result; # A single array representing an error
1265 else if( is_array($result) && is_array($result[0]) )
1266 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1267 else if( $result !== '' && is_string($result) )
1268 $errors[] = array($result); # A string representing a message-id
1269 else if( $result === false )
1270 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1272 # Short-circuit point
1273 if( $short && count($errors) > 0 ) {
1274 wfProfileOut( __METHOD__
);
1277 // Check getUserPermissionsErrorsExpensive hook
1278 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1279 if( is_array($result) && count($result) && !is_array($result[0]) )
1280 $errors[] = $result; # A single array representing an error
1281 else if( is_array($result) && is_array($result[0]) )
1282 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1283 else if( $result !== '' && is_string($result) )
1284 $errors[] = array($result); # A string representing a message-id
1285 else if( $result === false )
1286 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1288 # Short-circuit point
1289 if( $short && count($errors) > 0 ) {
1290 wfProfileOut( __METHOD__
);
1294 # Only 'createaccount' and 'execute' can be performed on
1295 # special pages, which don't actually exist in the DB.
1296 $specialOKActions = array( 'createaccount', 'execute' );
1297 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1298 $errors[] = array('ns-specialprotected');
1301 # Check $wgNamespaceProtection for restricted namespaces
1302 if( $this->isNamespaceProtected() ) {
1303 $ns = $this->getNamespace() == NS_MAIN ?
1304 wfMsg( 'nstab-main' ) : $this->getNsText();
1305 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1306 array('protectedinterface') : array( 'namespaceprotected', $ns );
1309 # Protect css/js subpages of user pages
1310 # XXX: this might be better using restrictions
1311 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1312 # and $this->userCanEditJsSubpage() from working
1313 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1314 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1315 && $action != 'patrol'
1316 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1318 $errors[] = array('customcssjsprotected');
1319 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1320 && $action != 'patrol'
1321 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1323 $errors[] = array('customcssjsprotected');
1326 # Check against page_restrictions table requirements on this
1327 # page. The user must possess all required rights for this action.
1328 foreach( $this->getRestrictions($action) as $right ) {
1329 // Backwards compatibility, rewrite sysop -> protect
1330 if( $right == 'sysop' ) {
1333 if( $right != '' && !$user->isAllowed( $right ) ) {
1334 // Users with 'editprotected' permission can edit protected pages
1335 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1336 // Users with 'editprotected' permission cannot edit protected pages
1337 // with cascading option turned on.
1338 if( $this->mCascadeRestriction
) {
1339 $errors[] = array( 'protectedpagetext', $right );
1342 $errors[] = array( 'protectedpagetext', $right );
1346 # Short-circuit point
1347 if( $short && count($errors) > 0 ) {
1348 wfProfileOut( __METHOD__
);
1352 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1353 # We /could/ use the protection level on the source page, but it's fairly ugly
1354 # as we have to establish a precedence hierarchy for pages included by multiple
1355 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1356 # as they could remove the protection anyway.
1357 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1358 # Cascading protection depends on more than this page...
1359 # Several cascading protected pages may include this page...
1360 # Check each cascading level
1361 # This is only for protection restrictions, not for all actions
1362 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1363 foreach( $restrictions[$action] as $right ) {
1364 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1365 if( $right != '' && !$user->isAllowed( $right ) ) {
1367 foreach( $cascadingSources as $page )
1368 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1369 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1374 # Short-circuit point
1375 if( $short && count($errors) > 0 ) {
1376 wfProfileOut( __METHOD__
);
1380 if( $action == 'protect' ) {
1381 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1382 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1386 if( $action == 'create' ) {
1387 $title_protection = $this->getTitleProtection();
1388 if( is_array($title_protection) ) {
1389 extract($title_protection); // is this extract() really needed?
1391 if( $pt_create_perm == 'sysop' ) {
1392 $pt_create_perm = 'protect'; // B/C
1394 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1395 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1398 } elseif( $action == 'move' ) {
1399 // Check for immobile pages
1400 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1401 // Specific message for this case
1402 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1403 } elseif( !$this->isMovable() ) {
1404 // Less specific message for rarer cases
1405 $errors[] = array( 'immobile-page' );
1407 } elseif( $action == 'move-target' ) {
1408 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1409 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1410 } elseif( !$this->isMovable() ) {
1411 $errors[] = array( 'immobile-target-page' );
1415 wfProfileOut( __METHOD__
);
1420 * Is this title subject to title protection?
1421 * @return \type{\mixed} An associative array representing any existent title
1422 * protection, or false if there's none.
1424 private function getTitleProtection() {
1425 // Can't protect pages in special namespaces
1426 if ( $this->getNamespace() < 0 ) {
1430 // Can't protect pages that exist.
1431 if ($this->exists()) {
1435 $dbr = wfGetDB( DB_SLAVE
);
1436 $res = $dbr->select( 'protected_titles', '*',
1437 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1440 if ($row = $dbr->fetchRow( $res )) {
1448 * Update the title protection status
1449 * @param $create_perm \type{\string} Permission required for creation
1450 * @param $reason \type{\string} Reason for protection
1451 * @param $expiry \type{\string} Expiry timestamp
1452 * @return boolean true
1454 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1455 global $wgUser,$wgContLang;
1457 if ($create_perm == implode(',',$this->getRestrictions('create'))
1458 && $expiry == $this->mRestrictionsExpiry
['create']) {
1463 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1465 $dbw = wfGetDB( DB_MASTER
);
1467 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1469 $expiry_description = '';
1470 if ( $encodedExpiry != 'infinity' ) {
1471 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1472 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1475 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1478 # Update protection table
1479 if ($create_perm != '' ) {
1480 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1482 'pt_namespace' => $namespace,
1483 'pt_title' => $title,
1484 'pt_create_perm' => $create_perm,
1485 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1486 'pt_expiry' => $encodedExpiry,
1487 'pt_user' => $wgUser->getId(),
1488 'pt_reason' => $reason,
1492 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1493 'pt_title' => $title ), __METHOD__
);
1495 # Update the protection log
1496 if( $dbw->affectedRows() ) {
1497 $log = new LogPage( 'protect' );
1499 if( $create_perm ) {
1500 $params = array("[create=$create_perm] $expiry_description",'');
1501 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1503 $log->addEntry( 'unprotect', $this, $reason );
1511 * Remove any title protection due to page existing
1513 public function deleteTitleProtection() {
1514 $dbw = wfGetDB( DB_MASTER
);
1516 $dbw->delete( 'protected_titles',
1517 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1522 * Would anybody with sufficient privileges be able to move this page?
1523 * Some pages just aren't movable.
1525 * @return \type{\bool} TRUE or FALSE
1527 public function isMovable() {
1528 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1532 * Can $wgUser read this page?
1533 * @return \type{\bool} TRUE or FALSE
1534 * @todo fold these checks into userCan()
1536 public function userCanRead() {
1537 global $wgUser, $wgGroupPermissions;
1539 static $useShortcut = null;
1541 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1542 if( is_null( $useShortcut ) ) {
1543 global $wgRevokePermissions;
1544 $useShortcut = true;
1545 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1546 # Not a public wiki, so no shortcut
1547 $useShortcut = false;
1548 } elseif( !empty( $wgRevokePermissions ) ) {
1550 * Iterate through each group with permissions being revoked (key not included since we don't care
1551 * what the group name is), then check if the read permission is being revoked. If it is, then
1552 * we don't use the shortcut below since the user might not be able to read, even though anon
1553 * reading is allowed.
1555 foreach( $wgRevokePermissions as $perms ) {
1556 if( !empty( $perms['read'] ) ) {
1557 # We might be removing the read right from the user, so no shortcut
1558 $useShortcut = false;
1566 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1567 if ( $result !== null ) {
1571 # Shortcut for public wikis, allows skipping quite a bit of code
1575 if( $wgUser->isAllowed( 'read' ) ) {
1578 global $wgWhitelistRead;
1581 * Always grant access to the login page.
1582 * Even anons need to be able to log in.
1584 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1589 * Bail out if there isn't whitelist
1591 if( !is_array($wgWhitelistRead) ) {
1596 * Check for explicit whitelisting
1598 $name = $this->getPrefixedText();
1599 $dbName = $this->getPrefixedDBKey();
1600 // Check with and without underscores
1601 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1605 * Old settings might have the title prefixed with
1606 * a colon for main-namespace pages
1608 if( $this->getNamespace() == NS_MAIN
) {
1609 if( in_array( ':' . $name, $wgWhitelistRead ) )
1614 * If it's a special page, ditch the subpage bit
1617 if( $this->getNamespace() == NS_SPECIAL
) {
1618 $name = $this->getDBkey();
1619 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1620 if ( $name === false ) {
1621 # Invalid special page, but we show standard login required message
1625 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1626 if( in_array( $pure, $wgWhitelistRead, true ) )
1635 * Is this a talk page of some sort?
1636 * @return \type{\bool} TRUE or FALSE
1638 public function isTalkPage() {
1639 return MWNamespace
::isTalk( $this->getNamespace() );
1643 * Is this a subpage?
1644 * @return \type{\bool} TRUE or FALSE
1646 public function isSubpage() {
1647 return MWNamespace
::hasSubpages( $this->mNamespace
)
1648 ?
strpos( $this->getText(), '/' ) !== false
1653 * Does this have subpages? (Warning, usually requires an extra DB query.)
1654 * @return \type{\bool} TRUE or FALSE
1656 public function hasSubpages() {
1657 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1662 # We dynamically add a member variable for the purpose of this method
1663 # alone to cache the result. There's no point in having it hanging
1664 # around uninitialized in every Title object; therefore we only add it
1665 # if needed and don't declare it statically.
1666 if( isset( $this->mHasSubpages
) ) {
1667 return $this->mHasSubpages
;
1670 $subpages = $this->getSubpages( 1 );
1671 if( $subpages instanceof TitleArray
)
1672 return $this->mHasSubpages
= (bool)$subpages->count();
1673 return $this->mHasSubpages
= false;
1677 * Get all subpages of this page.
1678 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1679 * @return mixed TitleArray, or empty array if this page's namespace
1680 * doesn't allow subpages
1682 public function getSubpages( $limit = -1 ) {
1683 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1686 $dbr = wfGetDB( DB_SLAVE
);
1687 $conds['page_namespace'] = $this->getNamespace();
1688 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1691 $options['LIMIT'] = $limit;
1692 return $this->mSubpages
= TitleArray
::newFromResult(
1693 $dbr->select( 'page',
1694 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1703 * Could this page contain custom CSS or JavaScript, based
1706 * @return \type{\bool} TRUE or FALSE
1708 public function isCssOrJsPage() {
1709 return $this->mNamespace
== NS_MEDIAWIKI
1710 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1714 * Is this a .css or .js subpage of a user page?
1715 * @return \type{\bool} TRUE or FALSE
1717 public function isCssJsSubpage() {
1718 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1721 * Is this a *valid* .css or .js subpage of a user page?
1722 * Check that the corresponding skin exists
1723 * @return \type{\bool} TRUE or FALSE
1725 public function isValidCssJsSubpage() {
1726 if ( $this->isCssJsSubpage() ) {
1727 $name = $this->getSkinFromCssJsSubpage();
1728 if ( $name == 'common' ) return true;
1729 $skinNames = Skin
::getSkinNames();
1730 return array_key_exists( $name, $skinNames );
1736 * Trim down a .css or .js subpage title to get the corresponding skin name
1737 * @return string containing skin name from .css or .js subpage title
1739 public function getSkinFromCssJsSubpage() {
1740 $subpage = explode( '/', $this->mTextform
);
1741 $subpage = $subpage[ count( $subpage ) - 1 ];
1742 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1745 * Is this a .css subpage of a user page?
1746 * @return \type{\bool} TRUE or FALSE
1748 public function isCssSubpage() {
1749 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1752 * Is this a .js subpage of a user page?
1753 * @return \type{\bool} TRUE or FALSE
1755 public function isJsSubpage() {
1756 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1759 * Protect css subpages of user pages: can $wgUser edit
1762 * @return \type{\bool} TRUE or FALSE
1763 * @todo XXX: this might be better using restrictions
1765 public function userCanEditCssSubpage() {
1767 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1768 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1771 * Protect js subpages of user pages: can $wgUser edit
1774 * @return \type{\bool} TRUE or FALSE
1775 * @todo XXX: this might be better using restrictions
1777 public function userCanEditJsSubpage() {
1779 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1780 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1784 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1786 * @return \type{\bool} If the page is subject to cascading restrictions.
1788 public function isCascadeProtected() {
1789 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1790 return ( $sources > 0 );
1794 * Cascading protection: Get the source of any cascading restrictions on this page.
1796 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1797 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1798 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1799 * The restriction array is an array of each type, each of which contains an array of unique groups.
1801 public function getCascadeProtectionSources( $get_pages = true ) {
1802 $pagerestrictions = array();
1804 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1805 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1806 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1807 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1810 wfProfileIn( __METHOD__
);
1812 $dbr = wfGetDB( DB_SLAVE
);
1814 if ( $this->getNamespace() == NS_FILE
) {
1815 $tables = array ('imagelinks', 'page_restrictions');
1816 $where_clauses = array(
1817 'il_to' => $this->getDBkey(),
1819 'pr_cascade' => 1 );
1821 $tables = array ('templatelinks', 'page_restrictions');
1822 $where_clauses = array(
1823 'tl_namespace' => $this->getNamespace(),
1824 'tl_title' => $this->getDBkey(),
1826 'pr_cascade' => 1 );
1830 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1831 $where_clauses[] = 'page_id=pr_page';
1834 $cols = array( 'pr_expiry' );
1837 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1839 $sources = $get_pages ?
array() : false;
1840 $now = wfTimestampNow();
1841 $purgeExpired = false;
1843 foreach( $res as $row ) {
1844 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1845 if( $expiry > $now ) {
1847 $page_id = $row->pr_page
;
1848 $page_ns = $row->page_namespace
;
1849 $page_title = $row->page_title
;
1850 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1851 # Add groups needed for each restriction type if its not already there
1852 # Make sure this restriction type still exists
1854 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1855 $pagerestrictions[$row->pr_type
] = array();
1858 if ( isset($pagerestrictions[$row->pr_type
]) &&
1859 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1860 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1866 // Trigger lazy purge of expired restrictions from the db
1867 $purgeExpired = true;
1870 if( $purgeExpired ) {
1871 Title
::purgeExpiredRestrictions();
1874 wfProfileOut( __METHOD__
);
1877 $this->mCascadeSources
= $sources;
1878 $this->mCascadingRestrictions
= $pagerestrictions;
1880 $this->mHasCascadingRestrictions
= $sources;
1882 return array( $sources, $pagerestrictions );
1886 * Returns cascading restrictions for the current article
1889 function areRestrictionsCascading() {
1890 if (!$this->mRestrictionsLoaded
) {
1891 $this->loadRestrictions();
1894 return $this->mCascadeRestriction
;
1898 * Loads a string into mRestrictions array
1899 * @param $res \type{Resource} restrictions as an SQL result.
1900 * @param $oldFashionedRestrictions string comma-separated list of page restrictions from page table (pre 1.10)
1902 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1904 $dbr = wfGetDB( DB_SLAVE
);
1906 while( $row = $dbr->fetchObject( $res ) ) {
1910 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1914 * Compiles list of active page restrictions from both page table (pre 1.10) and page_restrictions table
1915 * @param $rows array of db result objects
1916 * @param $oldFashionedRestrictions string comma-separated list of page restrictions from page table (pre 1.10)
1918 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1919 $dbr = wfGetDB( DB_SLAVE
);
1921 $restrictionTypes = $this->getRestrictionTypes();
1923 foreach( $restrictionTypes as $type ){
1924 $this->mRestrictions
[$type] = array();
1925 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1928 $this->mCascadeRestriction
= false;
1930 # Backwards-compatibility: also load the restrictions from the page record (old format).
1932 if ( $oldFashionedRestrictions === null ) {
1933 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1934 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1937 if ($oldFashionedRestrictions != '') {
1939 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1940 $temp = explode( '=', trim( $restrict ) );
1941 if(count($temp) == 1) {
1942 // old old format should be treated as edit/move restriction
1943 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1944 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1946 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1950 $this->mOldRestrictions
= true;
1954 if( count($rows) ) {
1955 # Current system - load second to make them override.
1956 $now = wfTimestampNow();
1957 $purgeExpired = false;
1959 foreach( $rows as $row ) {
1960 # Cycle through all the restrictions.
1962 // Don't take care of restrictions types that aren't allowed
1964 if( !in_array( $row->pr_type
, $restrictionTypes ) )
1967 // This code should be refactored, now that it's being used more generally,
1968 // But I don't really see any harm in leaving it in Block for now -werdna
1969 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1971 // Only apply the restrictions if they haven't expired!
1972 if ( !$expiry ||
$expiry > $now ) {
1973 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1974 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1976 $this->mCascadeRestriction |
= $row->pr_cascade
;
1978 // Trigger a lazy purge of expired restrictions
1979 $purgeExpired = true;
1983 if( $purgeExpired ) {
1984 Title
::purgeExpiredRestrictions();
1988 $this->mRestrictionsLoaded
= true;
1992 * Load restrictions from the page_restrictions table
1993 * @param $oldFashionedRestrictions string comma-separated list of page restrictions from page table (pre 1.10)
1995 public function loadRestrictions( $oldFashionedRestrictions = null ) {
1996 if( !$this->mRestrictionsLoaded
) {
1997 if ($this->exists()) {
1998 $dbr = wfGetDB( DB_SLAVE
);
2000 $res = $dbr->select( 'page_restrictions', '*',
2001 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2003 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2005 $title_protection = $this->getTitleProtection();
2007 if (is_array($title_protection)) {
2008 extract($title_protection);
2010 $now = wfTimestampNow();
2011 $expiry = Block
::decodeExpiry($pt_expiry);
2013 if (!$expiry ||
$expiry > $now) {
2014 // Apply the restrictions
2015 $this->mRestrictionsExpiry
['create'] = $expiry;
2016 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
2017 } else { // Get rid of the old restrictions
2018 Title
::purgeExpiredRestrictions();
2021 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
2023 $this->mRestrictionsLoaded
= true;
2029 * Purge expired restrictions from the page_restrictions table
2031 static function purgeExpiredRestrictions() {
2032 $dbw = wfGetDB( DB_MASTER
);
2033 $dbw->delete( 'page_restrictions',
2034 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2037 $dbw->delete( 'protected_titles',
2038 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2043 * Accessor/initialisation for mRestrictions
2045 * @param $action \type{\string} action that permission needs to be checked for
2046 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2048 public function getRestrictions( $action ) {
2049 if( !$this->mRestrictionsLoaded
) {
2050 $this->loadRestrictions();
2052 return isset( $this->mRestrictions
[$action] )
2053 ?
$this->mRestrictions
[$action]
2058 * Get the expiry time for the restriction against a given action
2059 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2060 * or not protected at all, or false if the action is not recognised.
2062 public function getRestrictionExpiry( $action ) {
2063 if( !$this->mRestrictionsLoaded
) {
2064 $this->loadRestrictions();
2066 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2070 * Is there a version of this page in the deletion archive?
2071 * @return \type{\int} the number of archived revisions
2073 public function isDeleted() {
2074 if( $this->getNamespace() < 0 ) {
2077 $dbr = wfGetDB( DB_SLAVE
);
2078 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2079 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2082 if( $this->getNamespace() == NS_FILE
) {
2083 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2084 array( 'fa_name' => $this->getDBkey() ),
2093 * Is there a version of this page in the deletion archive?
2096 public function isDeletedQuick() {
2097 if( $this->getNamespace() < 0 ) {
2100 $dbr = wfGetDB( DB_SLAVE
);
2101 $deleted = (bool)$dbr->selectField( 'archive', '1',
2102 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2105 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2106 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2107 array( 'fa_name' => $this->getDBkey() ),
2115 * Get the article ID for this Title from the link cache,
2116 * adding it if necessary
2117 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2119 * @return \type{\int} the ID
2121 public function getArticleID( $flags = 0 ) {
2122 if( $this->getNamespace() < 0 ) {
2123 return $this->mArticleID
= 0;
2125 $linkCache = LinkCache
::singleton();
2126 if( $flags & GAID_FOR_UPDATE
) {
2127 $oldUpdate = $linkCache->forUpdate( true );
2128 $linkCache->clearLink( $this );
2129 $this->mArticleID
= $linkCache->addLinkObj( $this );
2130 $linkCache->forUpdate( $oldUpdate );
2132 if( -1 == $this->mArticleID
) {
2133 $this->mArticleID
= $linkCache->addLinkObj( $this );
2136 return $this->mArticleID
;
2140 * Is this an article that is a redirect page?
2141 * Uses link cache, adding it if necessary
2142 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2143 * @return \type{\bool}
2145 public function isRedirect( $flags = 0 ) {
2146 if( !is_null($this->mRedirect
) )
2147 return $this->mRedirect
;
2148 # Calling getArticleID() loads the field from cache as needed
2149 if( !$this->getArticleID($flags) ) {
2150 return $this->mRedirect
= false;
2152 $linkCache = LinkCache
::singleton();
2153 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2155 return $this->mRedirect
;
2159 * What is the length of this page?
2160 * Uses link cache, adding it if necessary
2161 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2162 * @return \type{\bool}
2164 public function getLength( $flags = 0 ) {
2165 if( $this->mLength
!= -1 )
2166 return $this->mLength
;
2167 # Calling getArticleID() loads the field from cache as needed
2168 if( !$this->getArticleID($flags) ) {
2169 return $this->mLength
= 0;
2171 $linkCache = LinkCache
::singleton();
2172 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2174 return $this->mLength
;
2178 * What is the page_latest field for this page?
2179 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2180 * @return \type{\int} or false if the page doesn't exist
2182 public function getLatestRevID( $flags = 0 ) {
2183 if( $this->mLatestID
!== false )
2184 return $this->mLatestID
;
2186 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2187 $this->mLatestID
= (int)$db->selectField(
2188 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2189 return $this->mLatestID
;
2193 * This clears some fields in this object, and clears any associated
2194 * keys in the "bad links" section of the link cache.
2196 * - This is called from Article::insertNewArticle() to allow
2197 * loading of the new page_id. It's also called from
2198 * Article::doDeleteArticle()
2200 * @param $newid \type{\int} the new Article ID
2202 public function resetArticleID( $newid ) {
2203 $linkCache = LinkCache
::singleton();
2204 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2206 if ( $newid === false ) {
2207 $this->mArticleID
= -1;
2209 $this->mArticleID
= intval( $newid );
2211 $this->mRestrictionsLoaded
= false;
2212 $this->mRestrictions
= array();
2213 $this->mRedirect
= null;
2214 $this->mLength
= -1;
2215 $this->mLatestID
= false;
2219 * Updates page_touched for this page; called from LinksUpdate.php
2220 * @return \type{\bool} true if the update succeded
2222 public function invalidateCache() {
2223 if( wfReadOnly() ) {
2226 $dbw = wfGetDB( DB_MASTER
);
2227 $success = $dbw->update( 'page',
2228 array( 'page_touched' => $dbw->timestamp() ),
2232 HTMLFileCache
::clearFileCache( $this );
2237 * Prefix some arbitrary text with the namespace or interwiki prefix
2240 * @param $name \type{\string} the text
2241 * @return \type{\string} the prefixed text
2244 /* private */ function prefix( $name ) {
2246 if ( $this->mInterwiki
!= '' ) {
2247 $p = $this->mInterwiki
. ':';
2249 if ( 0 != $this->mNamespace
) {
2250 $p .= $this->getNsText() . ':';
2256 * Returns a simple regex that will match on characters and sequences invalid in titles.
2257 * Note that this doesn't pick up many things that could be wrong with titles, but that
2258 * replacing this regex with something valid will make many titles valid.
2259 * @return string regex string
2261 static function getTitleInvalidRegex() {
2262 static $rxTc = false;
2264 # Matching titles will be held as illegal.
2266 # Any character not allowed is forbidden...
2267 '[^' . Title
::legalChars() . ']' .
2268 # URL percent encoding sequences interfere with the ability
2269 # to round-trip titles -- you can't link to them consistently.
2270 '|%[0-9A-Fa-f]{2}' .
2271 # XML/HTML character references produce similar issues.
2272 '|&[A-Za-z0-9\x80-\xff]+;' .
2274 '|&#x[0-9A-Fa-f]+;' .
2282 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2283 * @param $text string containing title to capitalize
2284 * $param $ns int namespace index, defaults to NS_MAIN
2285 * @return $text string containing capitalized title
2287 public static function capitalize( $text, $ns = NS_MAIN
) {
2290 if ( MWNamespace
::isCapitalized( $ns ) )
2291 return $wgContLang->ucfirst( $text );
2297 * Secure and split - main initialisation function for this object
2299 * Assumes that mDbkeyform has been set, and is urldecoded
2300 * and uses underscores, but not otherwise munged. This function
2301 * removes illegal characters, splits off the interwiki and
2302 * namespace prefixes, sets the other forms, and canonicalizes
2304 * @return \type{\bool} true on success
2306 private function secureAndSplit() {
2307 global $wgContLang, $wgLocalInterwiki;
2310 $rxTc = self
::getTitleInvalidRegex();
2312 $this->mInterwiki
= $this->mFragment
= '';
2313 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2315 $dbkey = $this->mDbkeyform
;
2317 # Strip Unicode bidi override characters.
2318 # Sometimes they slip into cut-n-pasted page titles, where the
2319 # override chars get included in list displays.
2320 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2322 # Clean up whitespace
2323 # Note: use of the /u option on preg_replace here will cause
2324 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2325 # conveniently disabling them.
2327 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2328 $dbkey = trim( $dbkey, '_' );
2330 if ( $dbkey == '' ) {
2334 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2335 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2339 $this->mDbkeyform
= $dbkey;
2341 # Initial colon indicates main namespace rather than specified default
2342 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2343 if ( ':' == $dbkey{0} ) {
2344 $this->mNamespace
= NS_MAIN
;
2345 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2346 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2349 # Namespace or interwiki prefix
2351 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2354 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2356 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2357 # Ordinary namespace
2359 $this->mNamespace
= $ns;
2360 # For Talk:X pages, check if X has a "namespace" prefix
2361 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2362 if( $wgContLang->getNsIndex( $x[1] ) )
2363 return false; # Disallow Talk:File:x type titles...
2364 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2365 return false; # Disallow Talk:Interwiki:x type titles...
2367 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2369 # Can't make a local interwiki link to an interwiki link.
2370 # That's just crazy!
2376 $this->mInterwiki
= $wgContLang->lc( $p );
2378 # Redundant interwiki prefix to the local wiki
2379 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2380 if( $dbkey == '' ) {
2381 # Can't have an empty self-link
2384 $this->mInterwiki
= '';
2386 # Do another namespace split...
2390 # If there's an initial colon after the interwiki, that also
2391 # resets the default namespace
2392 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2393 $this->mNamespace
= NS_MAIN
;
2394 $dbkey = substr( $dbkey, 1 );
2397 # If there's no recognized interwiki or namespace,
2398 # then let the colon expression be part of the title.
2403 # We already know that some pages won't be in the database!
2405 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2406 $this->mArticleID
= 0;
2408 $fragment = strstr( $dbkey, '#' );
2409 if ( false !== $fragment ) {
2410 $this->setFragment( $fragment );
2411 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2412 # remove whitespace again: prevents "Foo_bar_#"
2413 # becoming "Foo_bar_"
2414 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2417 # Reject illegal characters.
2419 if( preg_match( $rxTc, $dbkey ) ) {
2424 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2425 * reachable due to the way web browsers deal with 'relative' URLs.
2426 * Also, they conflict with subpage syntax. Forbid them explicitly.
2428 if ( strpos( $dbkey, '.' ) !== false &&
2429 ( $dbkey === '.' ||
$dbkey === '..' ||
2430 strpos( $dbkey, './' ) === 0 ||
2431 strpos( $dbkey, '../' ) === 0 ||
2432 strpos( $dbkey, '/./' ) !== false ||
2433 strpos( $dbkey, '/../' ) !== false ||
2434 substr( $dbkey, -2 ) == '/.' ||
2435 substr( $dbkey, -3 ) == '/..' ) )
2441 * Magic tilde sequences? Nu-uh!
2443 if( strpos( $dbkey, '~~~' ) !== false ) {
2448 * Limit the size of titles to 255 bytes.
2449 * This is typically the size of the underlying database field.
2450 * We make an exception for special pages, which don't need to be stored
2451 * in the database, and may edge over 255 bytes due to subpage syntax
2452 * for long titles, e.g. [[Special:Block/Long name]]
2454 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2455 strlen( $dbkey ) > 512 )
2461 * Normally, all wiki links are forced to have
2462 * an initial capital letter so [[foo]] and [[Foo]]
2463 * point to the same place.
2465 * Don't force it for interwikis, since the other
2466 * site might be case-sensitive.
2468 $this->mUserCaseDBKey
= $dbkey;
2469 if( $this->mInterwiki
== '') {
2470 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2474 * Can't make a link to a namespace alone...
2475 * "empty" local links can only be self-links
2476 * with a fragment identifier.
2479 $this->mInterwiki
== '' &&
2480 $this->mNamespace
!= NS_MAIN
) {
2483 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2484 // IP names are not allowed for accounts, and can only be referring to
2485 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2486 // there are numerous ways to present the same IP. Having sp:contribs scan
2487 // them all is silly and having some show the edits and others not is
2488 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2489 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2490 IP
::sanitizeIP( $dbkey ) : $dbkey;
2491 // Any remaining initial :s are illegal.
2492 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2497 $this->mDbkeyform
= $dbkey;
2498 $this->mUrlform
= wfUrlencode( $dbkey );
2500 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2506 * Set the fragment for this title. Removes the first character from the
2507 * specified fragment before setting, so it assumes you're passing it with
2510 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2511 * Still in active use privately.
2513 * @param $fragment \type{\string} text
2515 public function setFragment( $fragment ) {
2516 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2520 * Get a Title object associated with the talk page of this article
2521 * @return \type{Title} the object for the talk page
2523 public function getTalkPage() {
2524 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2528 * Get a title object associated with the subject page of this
2531 * @return \type{Title} the object for the subject page
2533 public function getSubjectPage() {
2534 // Is this the same title?
2535 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2536 if( $this->getNamespace() == $subjectNS ) {
2539 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2543 * Get an array of Title objects linking to this Title
2544 * Also stores the IDs in the link cache.
2546 * WARNING: do not use this function on arbitrary user-supplied titles!
2547 * On heavily-used templates it will max out the memory.
2549 * @param array $options may be FOR UPDATE
2550 * @return \type{\arrayof{Title}} the Title objects linking here
2552 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2553 $linkCache = LinkCache
::singleton();
2555 if ( count( $options ) > 0 ) {
2556 $db = wfGetDB( DB_MASTER
);
2558 $db = wfGetDB( DB_SLAVE
);
2561 $res = $db->select( array( 'page', $table ),
2562 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2564 "{$prefix}_from=page_id",
2565 "{$prefix}_namespace" => $this->getNamespace(),
2566 "{$prefix}_title" => $this->getDBkey() ),
2571 if ( $db->numRows( $res ) ) {
2572 foreach( $res as $row ) {
2573 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2574 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2575 $retVal[] = $titleObj;
2579 $db->freeResult( $res );
2584 * Get an array of Title objects using this Title as a template
2585 * Also stores the IDs in the link cache.
2587 * WARNING: do not use this function on arbitrary user-supplied titles!
2588 * On heavily-used templates it will max out the memory.
2590 * @param array $options may be FOR UPDATE
2591 * @return \type{\arrayof{Title}} the Title objects linking here
2593 public function getTemplateLinksTo( $options = array() ) {
2594 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2598 * Get an array of Title objects referring to non-existent articles linked from this page
2600 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2601 * @return \type{\arrayof{Title}} the Title objects
2603 public function getBrokenLinksFrom() {
2604 if ( $this->getArticleId() == 0 ) {
2605 # All links from article ID 0 are false positives
2609 $dbr = wfGetDB( DB_SLAVE
);
2610 $res = $dbr->select(
2611 array( 'page', 'pagelinks' ),
2612 array( 'pl_namespace', 'pl_title' ),
2614 'pl_from' => $this->getArticleId(),
2615 'page_namespace IS NULL'
2617 __METHOD__
, array(),
2621 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2627 foreach( $res as $row ) {
2628 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2635 * Get a list of URLs to purge from the Squid cache when this
2638 * @return \type{\arrayof{\string}} the URLs
2640 public function getSquidURLs() {
2644 $this->getInternalURL(),
2645 $this->getInternalURL( 'action=history' )
2648 // purge variant urls as well
2649 if($wgContLang->hasVariants()){
2650 $variants = $wgContLang->getVariants();
2651 foreach($variants as $vCode){
2652 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2653 $urls[] = $this->getInternalURL('',$vCode);
2661 * Purge all applicable Squid URLs
2663 public function purgeSquid() {
2665 if ( $wgUseSquid ) {
2666 $urls = $this->getSquidURLs();
2667 $u = new SquidUpdate( $urls );
2673 * Move this page without authentication
2674 * @param &$nt \type{Title} the new page Title
2675 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2677 public function moveNoAuth( &$nt ) {
2678 return $this->moveTo( $nt, false );
2682 * Check whether a given move operation would be valid.
2683 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2684 * @param &$nt \type{Title} the new title
2685 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2687 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2688 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2690 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2695 // Normally we'd add this to $errors, but we'll get
2696 // lots of syntax errors if $nt is not an object
2697 return array(array('badtitletext'));
2699 if( $this->equals( $nt ) ) {
2700 $errors[] = array('selfmove');
2702 if( !$this->isMovable() ) {
2703 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2705 if ( $nt->getInterwiki() != '' ) {
2706 $errors[] = array( 'immobile-target-namespace-iw' );
2708 if ( !$nt->isMovable() ) {
2709 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2712 $oldid = $this->getArticleID();
2713 $newid = $nt->getArticleID();
2715 if ( strlen( $nt->getDBkey() ) < 1 ) {
2716 $errors[] = array('articleexists');
2718 if ( ( $this->getDBkey() == '' ) ||
2720 ( $nt->getDBkey() == '' ) ) {
2721 $errors[] = array('badarticleerror');
2724 // Image-specific checks
2725 if( $this->getNamespace() == NS_FILE
) {
2726 $file = wfLocalFile( $this );
2727 if( $file->exists() ) {
2728 if( $nt->getNamespace() != NS_FILE
) {
2729 $errors[] = array('imagenocrossnamespace');
2731 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2732 $errors[] = array('imageinvalidfilename');
2734 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2735 $errors[] = array('imagetypemismatch');
2738 $destfile = wfLocalFile( $nt );
2739 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2740 $errors[] = array( 'file-exists-sharedrepo' );
2746 $errors = wfMergeErrorArrays( $errors,
2747 $this->getUserPermissionsErrors('move', $wgUser),
2748 $this->getUserPermissionsErrors('edit', $wgUser),
2749 $nt->getUserPermissionsErrors('move-target', $wgUser),
2750 $nt->getUserPermissionsErrors('edit', $wgUser) );
2753 $match = EditPage
::matchSummarySpamRegex( $reason );
2754 if( $match !== false ) {
2755 // This is kind of lame, won't display nice
2756 $errors[] = array('spamprotectiontext');
2760 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2761 $errors[] = array('hookaborted', $err);
2764 # The move is allowed only if (1) the target doesn't exist, or
2765 # (2) the target is a redirect to the source, and has no history
2766 # (so we can undo bad moves right after they're done).
2768 if ( 0 != $newid ) { # Target exists; check for validity
2769 if ( ! $this->isValidMoveTarget( $nt ) ) {
2770 $errors[] = array('articleexists');
2773 $tp = $nt->getTitleProtection();
2774 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2775 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2776 $errors[] = array('cantmove-titleprotected');
2785 * Move a title to a new location
2786 * @param &$nt \type{Title} the new title
2787 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2789 * @param $reason \type{\string} The reason for the move
2790 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2791 * Ignored if the user doesn't have the suppressredirect right.
2792 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2794 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2795 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2796 if( is_array( $err ) ) {
2800 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2801 $dbw = wfGetDB( DB_MASTER
);
2802 if( $this->getNamespace() == NS_FILE
) {
2803 $file = wfLocalFile( $this );
2804 if( $file->exists() ) {
2805 $status = $file->move( $nt );
2806 if( !$status->isOk() ) {
2807 return $status->getErrorsArray();
2812 $pageid = $this->getArticleID();
2813 $protected = $this->isProtected();
2814 if( $nt->exists() ) {
2815 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2816 $pageCountChange = ($createRedirect ?
0 : -1);
2817 } else { # Target didn't exist, do normal move.
2818 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2819 $pageCountChange = ($createRedirect ?
1 : 0);
2822 if( is_array( $err ) ) {
2825 $redirid = $this->getArticleID();
2827 // Category memberships include a sort key which may be customized.
2828 // If it's left as the default (the page title), we need to update
2829 // the sort key to match the new title.
2831 // Be careful to avoid resetting cl_timestamp, which may disturb
2832 // time-based lists on some sites.
2834 // Warning -- if the sort key is *explicitly* set to the old title,
2835 // we can't actually distinguish it from a default here, and it'll
2836 // be set to the new title even though it really shouldn't.
2837 // It'll get corrected on the next edit, but resetting cl_timestamp.
2838 $dbw->update( 'categorylinks',
2840 'cl_sortkey' => $nt->getPrefixedText(),
2841 'cl_timestamp=cl_timestamp' ),
2843 'cl_from' => $pageid,
2844 'cl_sortkey' => $this->getPrefixedText() ),
2848 # Protect the redirect title as the title used to be...
2849 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2851 'pr_page' => $redirid,
2852 'pr_type' => 'pr_type',
2853 'pr_level' => 'pr_level',
2854 'pr_cascade' => 'pr_cascade',
2855 'pr_user' => 'pr_user',
2856 'pr_expiry' => 'pr_expiry'
2858 array( 'pr_page' => $pageid ),
2862 # Update the protection log
2863 $log = new LogPage( 'protect' );
2864 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2865 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2866 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2870 $oldnamespace = $this->getNamespace() & ~
1;
2871 $newnamespace = $nt->getNamespace() & ~
1;
2872 $oldtitle = $this->getDBkey();
2873 $newtitle = $nt->getDBkey();
2875 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2876 WatchedItem
::duplicateEntries( $this, $nt );
2879 # Update search engine
2880 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2882 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2886 if( $this->isContentPage() && !$nt->isContentPage() ) {
2887 # No longer a content page
2888 # Not viewed, edited, removing
2889 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2890 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2891 # Now a content page
2892 # Not viewed, edited, adding
2893 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2894 } elseif( $pageCountChange ) {
2896 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2903 # Update message cache for interface messages
2904 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2905 global $wgMessageCache;
2907 # @bug 17860: old article can be deleted, if this the case,
2908 # delete it from message cache
2909 if ( $this->getArticleID() === 0 ) {
2910 $wgMessageCache->replace( $this->getDBkey(), false );
2912 $oldarticle = new Article( $this );
2913 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2916 $newarticle = new Article( $nt );
2917 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2921 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2926 * Move page to a title which is at present a redirect to the
2929 * @param &$nt \type{Title} the page to move to, which should currently
2931 * @param $reason \type{\string} The reason for the move
2932 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2933 * Ignored if the user doesn't have the suppressredirect right
2935 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2936 global $wgUseSquid, $wgUser, $wgContLang;
2938 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2941 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2943 # Truncate for whole multibyte characters. +5 bytes for ellipsis
2944 $comment = $wgContLang->truncate( $comment, 250 );
2946 $now = wfTimestampNow();
2947 $newid = $nt->getArticleID();
2948 $oldid = $this->getArticleID();
2949 $latest = $this->getLatestRevID();
2951 $dbw = wfGetDB( DB_MASTER
);
2953 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
2954 $newns = $nt->getNamespace();
2955 $newdbk = $nt->getDBkey();
2957 # Delete the old redirect. We don't save it to history since
2958 # by definition if we've got here it's rather uninteresting.
2959 # We have to remove it so that the next step doesn't trigger
2960 # a conflict on the unique namespace+title index...
2961 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
2962 if ( !$dbw->cascadingDeletes() ) {
2963 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2964 global $wgUseTrackbacks;
2965 if ($wgUseTrackbacks)
2966 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2967 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2968 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2969 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2970 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2971 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2972 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2973 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2975 // If the redirect was recently created, it may have an entry in recentchanges still
2976 $dbw->delete( 'recentchanges',
2977 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
2981 # Save a null revision in the page's history notifying of the move
2982 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2983 $nullRevId = $nullRevision->insertOn( $dbw );
2985 $article = new Article( $this );
2986 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2988 # Change the name of the target page:
2989 $dbw->update( 'page',
2991 'page_touched' => $dbw->timestamp($now),
2992 'page_namespace' => $nt->getNamespace(),
2993 'page_title' => $nt->getDBkey(),
2994 'page_latest' => $nullRevId,
2996 /* WHERE */ array( 'page_id' => $oldid ),
2999 $nt->resetArticleID( $oldid );
3001 # Recreate the redirect, this time in the other direction.
3002 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3003 $mwRedir = MagicWord
::get( 'redirect' );
3004 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3005 $redirectArticle = new Article( $this );
3006 $newid = $redirectArticle->insertOn( $dbw );
3007 $redirectRevision = new Revision( array(
3009 'comment' => $comment,
3010 'text' => $redirectText ) );
3011 $redirectRevision->insertOn( $dbw );
3012 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3014 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3016 # Now, we record the link from the redirect to the new title.
3017 # It should have no other outgoing links...
3018 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3019 $dbw->insert( 'pagelinks',
3021 'pl_from' => $newid,
3022 'pl_namespace' => $nt->getNamespace(),
3023 'pl_title' => $nt->getDBkey() ),
3025 $redirectSuppressed = false;
3027 $this->resetArticleID( 0 );
3028 $redirectSuppressed = true;
3032 $log = new LogPage( 'move' );
3033 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3036 if ( $wgUseSquid ) {
3037 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3038 $u = new SquidUpdate( $urls );
3045 * Move page to non-existing title.
3046 * @param &$nt \type{Title} the new Title
3047 * @param $reason \type{\string} The reason for the move
3048 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3049 * Ignored if the user doesn't have the suppressredirect right
3051 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3052 global $wgUseSquid, $wgUser, $wgContLang;
3054 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3056 $comment .= wfMsgExt( 'colon-separator',
3057 array( 'escapenoentities', 'content' ) );
3058 $comment .= $reason;
3060 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3061 $comment = $wgContLang->truncate( $comment, 250 );
3063 $newid = $nt->getArticleID();
3064 $oldid = $this->getArticleID();
3065 $latest = $this->getLatestRevId();
3067 $dbw = wfGetDB( DB_MASTER
);
3068 $now = $dbw->timestamp();
3070 # Save a null revision in the page's history notifying of the move
3071 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3072 if ( !is_object( $nullRevision ) ) {
3073 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3075 $nullRevId = $nullRevision->insertOn( $dbw );
3077 $article = new Article( $this );
3078 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3081 $dbw->update( 'page',
3083 'page_touched' => $now,
3084 'page_namespace' => $nt->getNamespace(),
3085 'page_title' => $nt->getDBkey(),
3086 'page_latest' => $nullRevId,
3088 /* WHERE */ array( 'page_id' => $oldid ),
3091 $nt->resetArticleID( $oldid );
3093 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3095 $mwRedir = MagicWord
::get( 'redirect' );
3096 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3097 $redirectArticle = new Article( $this );
3098 $newid = $redirectArticle->insertOn( $dbw );
3099 $redirectRevision = new Revision( array(
3101 'comment' => $comment,
3102 'text' => $redirectText ) );
3103 $redirectRevision->insertOn( $dbw );
3104 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3106 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3108 # Record the just-created redirect's linking to the page
3109 $dbw->insert( 'pagelinks',
3111 'pl_from' => $newid,
3112 'pl_namespace' => $nt->getNamespace(),
3113 'pl_title' => $nt->getDBkey() ),
3115 $redirectSuppressed = false;
3117 $this->resetArticleID( 0 );
3118 $redirectSuppressed = true;
3122 $log = new LogPage( 'move' );
3123 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3125 # Purge caches as per article creation
3126 Article
::onArticleCreate( $nt );
3128 # Purge old title from squid
3129 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3130 $this->purgeSquid();
3135 * Move this page's subpages to be subpages of $nt
3136 * @param $nt Title Move target
3137 * @param $auth bool Whether $wgUser's permissions should be checked
3138 * @param $reason string The reason for the move
3139 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3140 * Ignored if the user doesn't have the 'suppressredirect' right
3141 * @return mixed array with old page titles as keys, and strings (new page titles) or
3142 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3144 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3145 global $wgMaximumMovedPages;
3146 // Check permissions
3147 if( !$this->userCan( 'move-subpages' ) )
3148 return array( 'cant-move-subpages' );
3149 // Do the source and target namespaces support subpages?
3150 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3151 return array( 'namespace-nosubpages',
3152 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3153 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3154 return array( 'namespace-nosubpages',
3155 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3157 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3160 foreach( $subpages as $oldSubpage ) {
3162 if( $count > $wgMaximumMovedPages ) {
3163 $retval[$oldSubpage->getPrefixedTitle()] =
3164 array( 'movepage-max-pages',
3165 $wgMaximumMovedPages );
3169 // We don't know whether this function was called before
3170 // or after moving the root page, so check both
3172 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3173 $oldSubpage->getArticleID() == $nt->getArticleId() )
3174 // When moving a page to a subpage of itself,
3175 // don't move it twice
3177 $newPageName = preg_replace(
3178 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3179 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3180 $oldSubpage->getDBkey() );
3181 if( $oldSubpage->isTalkPage() ) {
3182 $newNs = $nt->getTalkPage()->getNamespace();
3184 $newNs = $nt->getSubjectPage()->getNamespace();
3186 # Bug 14385: we need makeTitleSafe because the new page names may
3187 # be longer than 255 characters.
3188 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3190 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3191 if( $success === true ) {
3192 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3194 $retval[$oldSubpage->getPrefixedText()] = $success;
3201 * Checks if this page is just a one-rev redirect.
3202 * Adds lock, so don't use just for light purposes.
3204 * @return \type{\bool} TRUE or FALSE
3206 public function isSingleRevRedirect() {
3207 $dbw = wfGetDB( DB_MASTER
);
3209 $row = $dbw->selectRow( 'page',
3210 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3213 array( 'FOR UPDATE' )
3215 # Cache some fields we may want
3216 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3217 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3218 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3219 if( !$this->mRedirect
) {
3222 # Does the article have a history?
3223 $row = $dbw->selectField( array( 'page', 'revision'),
3225 array( 'page_namespace' => $this->getNamespace(),
3226 'page_title' => $this->getDBkey(),
3228 'page_latest != rev_id'
3231 array( 'FOR UPDATE' )
3233 # Return true if there was no history
3234 return ($row === false);
3238 * Checks if $this can be moved to a given Title
3239 * - Selects for update, so don't call it unless you mean business
3241 * @param &$nt \type{Title} the new title to check
3242 * @return \type{\bool} TRUE or FALSE
3244 public function isValidMoveTarget( $nt ) {
3245 $dbw = wfGetDB( DB_MASTER
);
3246 # Is it an existsing file?
3247 if( $nt->getNamespace() == NS_FILE
) {
3248 $file = wfLocalFile( $nt );
3249 if( $file->exists() ) {
3250 wfDebug( __METHOD__
. ": file exists\n" );
3254 # Is it a redirect with no history?
3255 if( !$nt->isSingleRevRedirect() ) {
3256 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3259 # Get the article text
3260 $rev = Revision
::newFromTitle( $nt );
3261 $text = $rev->getText();
3262 # Does the redirect point to the source?
3263 # Or is it a broken self-redirect, usually caused by namespace collisions?
3265 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3266 $redirTitle = Title
::newFromText( $m[1] );
3267 if( !is_object( $redirTitle ) ||
3268 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3269 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3270 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3275 wfDebug( __METHOD__
. ": failsafe\n" );
3282 * Can this title be added to a user's watchlist?
3284 * @return \type{\bool} TRUE or FALSE
3286 public function isWatchable() {
3287 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3291 * Get categories to which this Title belongs and return an array of
3292 * categories' names.
3294 * @return \type{\array} array an array of parents in the form:
3295 * $parent => $currentarticle
3297 public function getParentCategories() {
3300 $titlekey = $this->getArticleId();
3301 $dbr = wfGetDB( DB_SLAVE
);
3302 $categorylinks = $dbr->tableName( 'categorylinks' );
3305 $sql = "SELECT * FROM $categorylinks"
3306 ." WHERE cl_from='$titlekey'"
3307 ." AND cl_from <> '0'"
3308 ." ORDER BY cl_sortkey";
3310 $res = $dbr->query( $sql );
3312 if( $dbr->numRows( $res ) > 0 ) {
3313 foreach( $res as $row )
3314 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3315 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3316 $dbr->freeResult( $res );
3324 * Get a tree of parent categories
3325 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3326 * @return \type{\array} Tree of parent categories
3328 public function getParentCategoryTree( $children = array() ) {
3330 $parents = $this->getParentCategories();
3333 foreach( $parents as $parent => $current ) {
3334 if ( array_key_exists( $parent, $children ) ) {
3335 # Circular reference
3336 $stack[$parent] = array();
3338 $nt = Title
::newFromText($parent);
3340 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3352 * Get an associative array for selecting this title from
3355 * @return \type{\array} Selection array
3357 public function pageCond() {
3358 if( $this->mArticleID
> 0 ) {
3359 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3360 return array( 'page_id' => $this->mArticleID
);
3362 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3367 * Get the revision ID of the previous revision
3369 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3370 * @param $flags \type{\int} GAID_FOR_UPDATE
3371 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3373 public function getPreviousRevisionID( $revId, $flags=0 ) {
3374 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3375 return $db->selectField( 'revision', 'rev_id',
3377 'rev_page' => $this->getArticleId($flags),
3378 'rev_id < ' . intval( $revId )
3381 array( 'ORDER BY' => 'rev_id DESC' )
3386 * Get the revision ID of the next revision
3388 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3389 * @param $flags \type{\int} GAID_FOR_UPDATE
3390 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3392 public function getNextRevisionID( $revId, $flags=0 ) {
3393 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3394 return $db->selectField( 'revision', 'rev_id',
3396 'rev_page' => $this->getArticleId($flags),
3397 'rev_id > ' . intval( $revId )
3400 array( 'ORDER BY' => 'rev_id' )
3405 * Get the first revision of the page
3407 * @param $flags \type{\int} GAID_FOR_UPDATE
3408 * @return Revision (or NULL if page doesn't exist)
3410 public function getFirstRevision( $flags=0 ) {
3411 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3412 $pageId = $this->getArticleId($flags);
3413 if( !$pageId ) return null;
3414 $row = $db->selectRow( 'revision', '*',
3415 array( 'rev_page' => $pageId ),
3417 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3422 return new Revision( $row );
3427 * Check if this is a new page
3431 public function isNewPage() {
3432 $dbr = wfGetDB( DB_SLAVE
);
3433 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3437 * Get the oldest revision timestamp of this page
3439 * @return string, MW timestamp
3441 public function getEarliestRevTime() {
3442 $dbr = wfGetDB( DB_SLAVE
);
3443 if( $this->exists() ) {
3444 $min = $dbr->selectField( 'revision',
3445 'MIN(rev_timestamp)',
3446 array( 'rev_page' => $this->getArticleId() ),
3448 return wfTimestampOrNull( TS_MW
, $min );
3454 * Get the number of revisions between the given revision IDs.
3455 * Used for diffs and other things that really need it.
3457 * @param $old \type{\int} Revision ID.
3458 * @param $new \type{\int} Revision ID.
3459 * @return \type{\int} Number of revisions between these IDs.
3461 public function countRevisionsBetween( $old, $new ) {
3462 $dbr = wfGetDB( DB_SLAVE
);
3463 return (int)$dbr->selectField( 'revision', 'count(*)',
3464 'rev_page = ' . intval( $this->getArticleId() ) .
3465 ' AND rev_id > ' . intval( $old ) .
3466 ' AND rev_id < ' . intval( $new ),
3472 * Compare with another title.
3474 * @param \type{Title} $title
3475 * @return \type{\bool} TRUE or FALSE
3477 public function equals( Title
$title ) {
3478 // Note: === is necessary for proper matching of number-like titles.
3479 return $this->getInterwiki() === $title->getInterwiki()
3480 && $this->getNamespace() == $title->getNamespace()
3481 && $this->getDBkey() === $title->getDBkey();
3485 * Callback for usort() to do title sorts by (namespace, title)
3487 * @return int result of string comparison, or namespace comparison
3489 public static function compare( $a, $b ) {
3490 if( $a->getNamespace() == $b->getNamespace() ) {
3491 return strcmp( $a->getText(), $b->getText() );
3493 return $a->getNamespace() - $b->getNamespace();
3498 * Return a string representation of this title
3500 * @return \type{\string} String representation of this title
3502 public function __toString() {
3503 return $this->getPrefixedText();
3507 * Check if page exists. For historical reasons, this function simply
3508 * checks for the existence of the title in the page table, and will
3509 * thus return false for interwiki links, special pages and the like.
3510 * If you want to know if a title can be meaningfully viewed, you should
3511 * probably call the isKnown() method instead.
3513 * @return \type{\bool} TRUE or FALSE
3515 public function exists() {
3516 return $this->getArticleId() != 0;
3520 * Should links to this title be shown as potentially viewable (i.e. as
3521 * "bluelinks"), even if there's no record by this title in the page
3524 * This function is semi-deprecated for public use, as well as somewhat
3525 * misleadingly named. You probably just want to call isKnown(), which
3526 * calls this function internally.
3528 * (ISSUE: Most of these checks are cheap, but the file existence check
3529 * can potentially be quite expensive. Including it here fixes a lot of
3530 * existing code, but we might want to add an optional parameter to skip
3531 * it and any other expensive checks.)
3533 * @return \type{\bool} TRUE or FALSE
3535 public function isAlwaysKnown() {
3536 if( $this->mInterwiki
!= '' ) {
3537 return true; // any interwiki link might be viewable, for all we know
3539 switch( $this->mNamespace
) {
3542 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3544 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3546 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3548 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3549 // the full l10n of that language to be loaded. That takes much memory and
3550 // isn't needed. So we strip the language part away.
3551 // Also, extension messages which are not loaded, are shown as red, because
3552 // we don't call MessageCache::loadAllMessages.
3553 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3554 return wfMsgWeirdKey( $basename ); // known system message
3561 * Does this title refer to a page that can (or might) be meaningfully
3562 * viewed? In particular, this function may be used to determine if
3563 * links to the title should be rendered as "bluelinks" (as opposed to
3564 * "redlinks" to non-existent pages).
3566 * @return \type{\bool} TRUE or FALSE
3568 public function isKnown() {
3569 return $this->exists() ||
$this->isAlwaysKnown();
3573 * Is this in a namespace that allows actual pages?
3575 * @return \type{\bool} TRUE or FALSE
3576 * @internal note -- uses hardcoded namespace index instead of constants
3578 public function canExist() {
3579 return $this->mNamespace
>=0 && $this->mNamespace
!= NS_MEDIA
;
3583 * Update page_touched timestamps and send squid purge messages for
3584 * pages linking to this title. May be sent to the job queue depending
3585 * on the number of links. Typically called on create and delete.
3587 public function touchLinks() {
3588 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3591 if ( $this->getNamespace() == NS_CATEGORY
) {
3592 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3598 * Get the last touched timestamp
3599 * @param Database $db, optional db
3600 * @return \type{\string} Last touched timestamp
3602 public function getTouched( $db = null ) {
3603 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3604 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3609 * Get the timestamp when this page was updated since the user last saw it.
3611 * @return mixed string/NULL
3613 public function getNotificationTimestamp( $user = null ) {
3614 global $wgUser, $wgShowUpdatedMarker;
3615 // Assume current user if none given
3616 if( !$user ) $user = $wgUser;
3617 // Check cache first
3618 $uid = $user->getId();
3619 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3620 return $this->mNotificationTimestamp
[$uid];
3622 if( !$uid ||
!$wgShowUpdatedMarker ) {
3623 return $this->mNotificationTimestamp
[$uid] = false;
3625 // Don't cache too much!
3626 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3627 $this->mNotificationTimestamp
= array();
3629 $dbr = wfGetDB( DB_SLAVE
);
3630 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3631 'wl_notificationtimestamp',
3632 array( 'wl_namespace' => $this->getNamespace(),
3633 'wl_title' => $this->getDBkey(),
3634 'wl_user' => $user->getId()
3638 return $this->mNotificationTimestamp
[$uid];
3642 * Get the trackback URL for this page
3643 * @return \type{\string} Trackback URL
3645 public function trackbackURL() {
3646 global $wgScriptPath, $wgServer, $wgScriptExtension;
3648 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3649 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3653 * Get the trackback RDF for this page
3654 * @return \type{\string} Trackback RDF
3656 public function trackbackRDF() {
3657 $url = htmlspecialchars($this->getFullURL());
3658 $title = htmlspecialchars($this->getText());
3659 $tburl = $this->trackbackURL();
3661 // Autodiscovery RDF is placed in comments so HTML validator
3662 // won't barf. This is a rather icky workaround, but seems
3663 // frequently used by this kind of RDF thingy.
3665 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3667 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3668 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3669 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3672 dc:identifier=\"$url\"
3674 trackback:ping=\"$tburl\" />
3680 * Generate strings used for xml 'id' names in monobook tabs
3681 * @param $prepend string defaults to 'nstab-'
3682 * @return \type{\string} XML 'id' name
3684 public function getNamespaceKey( $prepend = 'nstab-' ) {
3686 // Gets the subject namespace if this title
3687 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3688 // Checks if cononical namespace name exists for namespace
3689 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3690 // Uses canonical namespace name
3691 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3693 // Uses text of namespace
3694 $namespaceKey = $this->getSubjectNsText();
3696 // Makes namespace key lowercase
3697 $namespaceKey = $wgContLang->lc( $namespaceKey );
3699 if ( $namespaceKey == '' ) {
3700 $namespaceKey = 'main';
3702 // Changes file to image for backwards compatibility
3703 if ( $namespaceKey == 'file' ) {
3704 $namespaceKey = 'image';
3706 return $prepend . $namespaceKey;
3710 * Returns true if this is a special page.
3713 public function isSpecialPage( ) {
3714 return $this->getNamespace() == NS_SPECIAL
;
3718 * Returns true if this title resolves to the named special page
3719 * @param $name \type{\string} The special page name
3722 public function isSpecial( $name ) {
3723 if ( $this->getNamespace() == NS_SPECIAL
) {
3724 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3725 if ( $name == $thisName ) {
3733 * If the Title refers to a special page alias which is not the local default,
3734 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3736 public function fixSpecialName() {
3737 if ( $this->getNamespace() == NS_SPECIAL
) {
3738 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3739 if ( $canonicalName ) {
3740 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3741 if ( $localName != $this->mDbkeyform
) {
3742 return Title
::makeTitle( NS_SPECIAL
, $localName );
3750 * Is this Title in a namespace which contains content?
3751 * In other words, is this a content page, for the purposes of calculating
3754 * @return \type{\bool} TRUE or FALSE
3756 public function isContentPage() {
3757 return MWNamespace
::isContent( $this->getNamespace() );
3761 * Get all extant redirects to this Title
3763 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3764 * NULL to consider all namespaces
3765 * @return \type{\arrayof{Title}} Redirects to this title
3767 public function getRedirectsHere( $ns = null ) {
3770 $dbr = wfGetDB( DB_SLAVE
);
3772 'rd_namespace' => $this->getNamespace(),
3773 'rd_title' => $this->getDBkey(),
3776 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3778 $res = $dbr->select(
3779 array( 'redirect', 'page' ),
3780 array( 'page_namespace', 'page_title' ),
3786 foreach( $res as $row ) {
3787 $redirs[] = self
::newFromRow( $row );
3793 * Check if this Title is a valid redirect target
3795 * @return \type{\bool} TRUE or FALSE
3797 public function isValidRedirectTarget() {
3798 global $wgInvalidRedirectTargets;
3800 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3801 if( $this->isSpecial( 'Userlogout' ) ) {
3805 foreach( $wgInvalidRedirectTargets as $target ) {
3806 if( $this->isSpecial( $target ) ) {
3815 * Get a backlink cache object
3816 * @return object BacklinkCache
3818 function getBacklinkCache() {
3819 if ( is_null( $this->mBacklinkCache
) ) {
3820 $this->mBacklinkCache
= new BacklinkCache( $this );
3822 return $this->mBacklinkCache
;
3826 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3830 public function canUseNoindex(){
3831 global $wgArticleRobotPolicies, $wgContentNamespaces,
3832 $wgExemptFromUserRobotsControl;
3834 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3835 ?
$wgContentNamespaces
3836 : $wgExemptFromUserRobotsControl;
3838 return !in_array( $this->mNamespace
, $bannedNamespaces );
3843 * Returns restriction types for the current Title
3844 * @return array applicable restriction types
3846 public function getRestrictionTypes() {
3847 global $wgRestrictionTypes;
3848 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3850 if ( $this->getNamespace() == NS_FILE
) {
3851 $types[] = 'upload';
3854 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );