8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
16 define ( 'GAID_FOR_UPDATE', 1 );
19 * Represents a title within MediaWiki.
20 * Optionally may contain an interwiki designation or namespace.
21 * @note This class can fetch various kinds of data from the database;
22 * however, it does so inefficiently.
24 * @internal documentation reviewed 15 Mar 2010
27 /** @name Static cache variables */
29 static private $titleCache=array();
30 static private $interwikiCache=array();
34 * Title::newFromText maintains a cache to avoid expensive re-normalization of
35 * commonly used titles. On a batch operation this can become a memory leak
36 * if not bounded. After hitting this many titles reset the cache.
38 const CACHE_MAX
= 1000;
42 * @name Private member variables
43 * Please use the accessor functions instead.
48 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; ///< URL-encoded form of the main part
50 var $mDbkeyform = ''; ///< Main part with underscores
51 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
54 var $mFragment; ///< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; ///< ID of most recent revision
57 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
61 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
62 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
63 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
64 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
65 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
66 # Don't change the following default, NS_MAIN is hardcoded in several
67 # places. See bug 696.
68 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
69 # Zero except in {{transclusion}} tags
70 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
71 var $mLength = -1; ///< The page length, 0 for special pages
72 var $mRedirect = null; ///< Is the article at this title a redirect?
73 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
74 var $mBacklinkCache = null; ///< Cache of links to this title
82 /* private */ function __construct() {}
85 * Create a new Title from a prefixed DB key
87 * @param $key \type{\string} The database key, which has underscores
88 * instead of spaces, possibly including namespace and
90 * @return \type{Title} the new object, or NULL on an error
92 public static function newFromDBkey( $key ) {
94 $t->mDbkeyform
= $key;
95 if( $t->secureAndSplit() )
102 * Create a new Title from text, such as what one would find in a link. De-
103 * codes any HTML entities in the text.
105 * @param $text string The link text; spaces, prefixes, and an
106 * initial ':' indicating the main namespace are accepted.
107 * @param $defaultNamespace int The namespace to use if none is speci-
108 * fied by a prefix. If you want to force a specific namespace even if
109 * $text might begin with a namespace prefix, use makeTitle() or
111 * @return Title The new object, or null on an error.
113 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
114 if( is_object( $text ) ) {
115 throw new MWException( 'Title::newFromText given an object' );
119 * Wiki pages often contain multiple links to the same page.
120 * Title normalization and parsing can become expensive on
121 * pages with many links, so we can save a little time by
124 * In theory these are value objects and won't get changed...
126 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
127 return Title
::$titleCache[$text];
131 * Convert things like é ā or 〗 into normalized(bug 14952) text
133 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
136 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
137 $t->mDefaultNamespace
= $defaultNamespace;
139 static $cachedcount = 0 ;
140 if( $t->secureAndSplit() ) {
141 if( $defaultNamespace == NS_MAIN
) {
142 if( $cachedcount >= self
::CACHE_MAX
) {
143 # Avoid memory leaks on mass operations...
144 Title
::$titleCache = array();
148 Title
::$titleCache[$text] =& $t;
158 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
160 * Example of wrong and broken code:
161 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
163 * Example of right code:
164 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
166 * Create a new Title from URL-encoded text. Ensures that
167 * the given title's length does not exceed the maximum.
169 * @param $url \type{\string} the title, as might be taken from a URL
170 * @return \type{Title} the new object, or NULL on an error
172 public static function newFromURL( $url ) {
173 global $wgLegalTitleChars;
176 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
177 # but some URLs used it as a space replacement and they still come
178 # from some external search tools.
179 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
180 $url = str_replace( '+', ' ', $url );
183 $t->mDbkeyform
= str_replace( ' ', '_', $url );
184 if( $t->secureAndSplit() ) {
192 * Create a new Title from an article ID
194 * @param $id \type{\int} the page_id corresponding to the Title to create
195 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
196 * @return \type{Title} the new object, or NULL on an error
198 public static function newFromID( $id, $flags = 0 ) {
199 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
200 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
201 if( $row !== false ) {
202 $title = Title
::newFromRow( $row );
210 * Make an array of titles from an array of IDs
212 * @param $ids \type{\arrayof{\int}} Array of IDs
213 * @return \type{\arrayof{Title}} Array of Titles
215 public static function newFromIDs( $ids ) {
216 if ( !count( $ids ) ) {
219 $dbr = wfGetDB( DB_SLAVE
);
220 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
221 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
224 foreach( $res as $row ) {
225 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
231 * Make a Title object from a DB row
233 * @param $row \type{Row} (needs at least page_title,page_namespace)
234 * @return \type{Title} corresponding Title
236 public static function newFromRow( $row ) {
237 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
239 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
240 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
241 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
242 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
248 * Create a new Title from a namespace index and a DB key.
249 * It's assumed that $ns and $title are *valid*, for instance when
250 * they came directly from the database or a special page name.
251 * For convenience, spaces are converted to underscores so that
252 * eg user_text fields can be used directly.
254 * @param $ns \type{\int} the namespace of the article
255 * @param $title \type{\string} the unprefixed database key form
256 * @param $fragment \type{\string} The link fragment (after the "#")
257 * @return \type{Title} the new object
259 public static function &makeTitle( $ns, $title, $fragment = '' ) {
262 $t->mFragment
= $fragment;
263 $t->mNamespace
= $ns = intval( $ns );
264 $t->mDbkeyform
= str_replace( ' ', '_', $title );
265 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
266 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
267 $t->mTextform
= str_replace( '_', ' ', $title );
272 * Create a new Title from a namespace index and a DB key.
273 * The parameters will be checked for validity, which is a bit slower
274 * than makeTitle() but safer for user-provided data.
276 * @param $ns \type{\int} the namespace of the article
277 * @param $title \type{\string} the database key form
278 * @param $fragment \type{\string} The link fragment (after the "#")
279 * @return \type{Title} the new object, or NULL on an error
281 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
283 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
284 if( $t->secureAndSplit() ) {
292 * Create a new Title for the Main Page
294 * @return \type{Title} the new object
296 public static function newMainPage() {
297 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
298 // Don't give fatal errors if the message is broken
300 $title = Title
::newFromText( 'Main Page' );
306 * Extract a redirect destination from a string and return the
307 * Title, or null if the text doesn't contain a valid redirect
308 * This will only return the very next target, useful for
309 * the redirect table and other checks that don't need full recursion
311 * @param $text \type{\string} Text with possible redirect
312 * @return \type{Title} The corresponding Title
314 public static function newFromRedirect( $text ) {
315 return self
::newFromRedirectInternal( $text );
319 * Extract a redirect destination from a string and return the
320 * Title, or null if the text doesn't contain a valid redirect
321 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
322 * in order to provide (hopefully) the Title of the final destination instead of another redirect
324 * @param $text \type{\string} Text with possible redirect
325 * @return \type{Title} The corresponding Title
327 public static function newFromRedirectRecurse( $text ) {
328 $titles = self
::newFromRedirectArray( $text );
329 return $titles ?
array_pop( $titles ) : null;
333 * Extract a redirect destination from a string and return an
334 * array of Titles, or null if the text doesn't contain a valid redirect
335 * The last element in the array is the final destination after all redirects
336 * have been resolved (up to $wgMaxRedirects times)
338 * @param $text \type{\string} Text with possible redirect
339 * @return \type{\array} Array of Titles, with the destination last
341 public static function newFromRedirectArray( $text ) {
342 global $wgMaxRedirects;
343 // are redirects disabled?
344 if( $wgMaxRedirects < 1 )
346 $title = self
::newFromRedirectInternal( $text );
347 if( is_null( $title ) )
349 // recursive check to follow double redirects
350 $recurse = $wgMaxRedirects;
351 $titles = array( $title );
352 while( --$recurse > 0 ) {
353 if( $title->isRedirect() ) {
354 $article = new Article( $title, 0 );
355 $newtitle = $article->getRedirectTarget();
359 // Redirects to some special pages are not permitted
360 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
361 // the new title passes the checks, so make that our current title so that further recursion can be checked
363 $titles[] = $newtitle;
372 * Really extract the redirect destination
373 * Do not call this function directly, use one of the newFromRedirect* functions above
375 * @param $text \type{\string} Text with possible redirect
376 * @return \type{Title} The corresponding Title
378 protected static function newFromRedirectInternal( $text ) {
379 $redir = MagicWord
::get( 'redirect' );
381 if( $redir->matchStartAndRemove( $text ) ) {
382 // Extract the first link and see if it's usable
383 // Ensure that it really does come directly after #REDIRECT
384 // Some older redirects included a colon, so don't freak about that!
386 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
387 // Strip preceding colon used to "escape" categories, etc.
388 // and URL-decode links
389 if( strpos( $m[1], '%' ) !== false ) {
390 // Match behavior of inline link parsing here;
391 // don't interpret + as " " most of the time!
392 // It might be safe to just use rawurldecode instead, though.
393 $m[1] = urldecode( ltrim( $m[1], ':' ) );
395 $title = Title
::newFromText( $m[1] );
396 // If the title is a redirect to bad special pages or is invalid, return null
397 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
406 #----------------------------------------------------------------------------
408 #----------------------------------------------------------------------------
411 * Get the prefixed DB key associated with an ID
413 * @param $id \type{\int} the page_id of the article
414 * @return \type{Title} an object representing the article, or NULL
415 * if no such article was found
417 public static function nameOf( $id ) {
418 $dbr = wfGetDB( DB_SLAVE
);
420 $s = $dbr->selectRow( 'page',
421 array( 'page_namespace','page_title' ),
422 array( 'page_id' => $id ),
424 if ( $s === false ) { return null; }
426 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
431 * Get a regex character class describing the legal characters in a link
433 * @return \type{\string} the list of characters, not delimited
435 public static function legalChars() {
436 global $wgLegalTitleChars;
437 return $wgLegalTitleChars;
441 * Get a string representation of a title suitable for
442 * including in a search index
444 * @param $ns \type{\int} a namespace index
445 * @param $title \type{\string} text-form main part
446 * @return \type{\string} a stripped-down title string ready for the
449 public static function indexTitle( $ns, $title ) {
452 $lc = SearchEngine
::legalSearchChars() . '&#;';
453 $t = $wgContLang->normalizeForSearch( $title );
454 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
455 $t = $wgContLang->lc( $t );
458 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
459 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
461 $t = preg_replace( "/\\s+/", ' ', $t );
463 if ( $ns == NS_FILE
) {
464 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
470 * Make a prefixed DB key from a DB key and a namespace index
472 * @param $ns \type{\int} numerical representation of the namespace
473 * @param $title \type{\string} the DB key form the title
474 * @param $fragment \type{\string} The link fragment (after the "#")
475 * @return \type{\string} the prefixed form of the title
477 public static function makeName( $ns, $title, $fragment = '' ) {
480 $namespace = $wgContLang->getNsText( $ns );
481 $name = $namespace == '' ?
$title : "$namespace:$title";
482 if ( strval( $fragment ) != '' ) {
483 $name .= '#' . $fragment;
489 * Determine whether the object refers to a page within
492 * @return \type{\bool} TRUE if this is an in-project interwiki link
493 * or a wikilink, FALSE otherwise
495 public function isLocal() {
496 if ( $this->mInterwiki
!= '' ) {
497 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
504 * Determine whether the object refers to a page within
505 * this project and is transcludable.
507 * @return \type{\bool} TRUE if this is transcludable
509 public function isTrans() {
510 if ($this->mInterwiki
== '')
513 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
517 * Escape a text fragment, say from a link, for a URL
519 * @param $fragment string containing a URL or link fragment (after the "#")
520 * @return String: escaped string
522 static function escapeFragmentForURL( $fragment ) {
523 # Note that we don't urlencode the fragment. urlencoded Unicode
524 # fragments appear not to work in IE (at least up to 7) or in at least
525 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
526 # to care if they aren't encoded.
527 return Sanitizer
::escapeId( $fragment, 'noninitial' );
530 #----------------------------------------------------------------------------
532 #----------------------------------------------------------------------------
534 /** Simple accessors */
536 * Get the text form (spaces not underscores) of the main part
538 * @return \type{\string} Main part of the title
540 public function getText() { return $this->mTextform
; }
543 * Get the URL-encoded form of the main part
545 * @return \type{\string} Main part of the title, URL-encoded
547 public function getPartialURL() { return $this->mUrlform
; }
550 * Get the main part with underscores
552 * @return \type{\string} Main part of the title, with underscores
554 public function getDBkey() { return $this->mDbkeyform
; }
557 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
559 * @return \type{\int} Namespace index
561 public function getNamespace() { return $this->mNamespace
; }
564 * Get the namespace text
566 * @return \type{\string} Namespace text
568 public function getNsText() {
571 if ( $this->mInterwiki
!= '' ) {
572 // This probably shouldn't even happen. ohh man, oh yuck.
573 // But for interwiki transclusion it sometimes does.
574 // Shit. Shit shit shit.
576 // Use the canonical namespaces if possible to try to
577 // resolve a foreign namespace.
578 if( MWNamespace
::exists( $this->mNamespace
) ) {
579 return MWNamespace
::getCanonicalName( $this->mNamespace
);
582 return $wgContLang->getNsText( $this->mNamespace
);
586 * Get the DB key with the initial letter case as specified by the user
588 * @return \type{\string} DB key
590 function getUserCaseDBKey() {
591 return $this->mUserCaseDBKey
;
595 * Get the namespace text of the subject (rather than talk) page
597 * @return \type{\string} Namespace text
599 public function getSubjectNsText() {
601 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
605 * Get the namespace text of the talk page
607 * @return \type{\string} Namespace text
609 public function getTalkNsText() {
611 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
615 * Could this title have a corresponding talk page?
617 * @return \type{\bool} TRUE or FALSE
619 public function canTalk() {
620 return( MWNamespace
::canTalk( $this->mNamespace
) );
624 * Get the interwiki prefix (or null string)
626 * @return \type{\string} Interwiki prefix
628 public function getInterwiki() { return $this->mInterwiki
; }
631 * Get the Title fragment (i.e.\ the bit after the #) in text form
633 * @return \type{\string} Title fragment
635 public function getFragment() { return $this->mFragment
; }
638 * Get the fragment in URL form, including the "#" character if there is one
639 * @return \type{\string} Fragment in URL form
641 public function getFragmentForURL() {
642 if ( $this->mFragment
== '' ) {
645 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
650 * Get the default namespace index, for when there is no namespace
652 * @return \type{\int} Default namespace index
654 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
657 * Get title for search index
659 * @return \type{\string} a stripped-down title string ready for the
662 public function getIndexTitle() {
663 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
667 * Get the prefixed database key form
669 * @return \type{\string} the prefixed title, with underscores and
670 * any interwiki and namespace prefixes
672 public function getPrefixedDBkey() {
673 $s = $this->prefix( $this->mDbkeyform
);
674 $s = str_replace( ' ', '_', $s );
679 * Get the prefixed title with spaces.
680 * This is the form usually used for display
682 * @return \type{\string} the prefixed title, with spaces
684 public function getPrefixedText() {
685 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
686 $s = $this->prefix( $this->mTextform
);
687 $s = str_replace( '_', ' ', $s );
688 $this->mPrefixedText
= $s;
690 return $this->mPrefixedText
;
694 * Get the prefixed title with spaces, plus any fragment
695 * (part beginning with '#')
697 * @return \type{\string} the prefixed title, with spaces and
698 * the fragment, including '#'
700 public function getFullText() {
701 $text = $this->getPrefixedText();
702 if( $this->mFragment
!= '' ) {
703 $text .= '#' . $this->mFragment
;
709 * Get the base name, i.e. the leftmost parts before the /
711 * @return \type{\string} Base name
713 public function getBaseText() {
714 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
715 return $this->getText();
718 $parts = explode( '/', $this->getText() );
719 # Don't discard the real title if there's no subpage involved
720 if( count( $parts ) > 1 )
721 unset( $parts[ count( $parts ) - 1 ] );
722 return implode( '/', $parts );
726 * Get the lowest-level subpage name, i.e. the rightmost part after /
728 * @return \type{\string} Subpage name
730 public function getSubpageText() {
731 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
732 return( $this->mTextform
);
734 $parts = explode( '/', $this->mTextform
);
735 return( $parts[ count( $parts ) - 1 ] );
739 * Get a URL-encoded form of the subpage text
741 * @return \type{\string} URL-encoded subpage name
743 public function getSubpageUrlForm() {
744 $text = $this->getSubpageText();
745 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
750 * Get a URL-encoded title (not an actual URL) including interwiki
752 * @return \type{\string} the URL-encoded form
754 public function getPrefixedURL() {
755 $s = $this->prefix( $this->mDbkeyform
);
756 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
761 * Get a real URL referring to this title, with interwiki link and
764 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
765 * links. Can be specified as an associative array as well, e.g.,
766 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
767 * @param $variant \type{\string} language variant of url (for sr, zh..)
768 * @return \type{\string} the URL
770 public function getFullURL( $query = '', $variant = false ) {
771 global $wgContLang, $wgServer, $wgRequest;
773 if( is_array( $query ) ) {
774 $query = wfArrayToCGI( $query );
777 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
779 $url = $this->getLocalURL( $query, $variant );
781 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
782 // Correct fix would be to move the prepending elsewhere.
783 if ($wgRequest->getVal('action') != 'render') {
784 $url = $wgServer . $url;
787 $baseUrl = $interwiki->getURL( );
789 $namespace = wfUrlencode( $this->getNsText() );
790 if ( $namespace != '' ) {
791 # Can this actually happen? Interwikis shouldn't be parsed.
792 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
795 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
796 $url = wfAppendQuery( $url, $query );
799 # Finally, add the fragment.
800 $url .= $this->getFragmentForURL();
802 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
807 * Get a URL with no fragment or server name. If this page is generated
808 * with action=render, $wgServer is prepended.
810 * @param $query Mixed: an optional query string; if not specified,
811 * $wgArticlePath will be used. Can be specified as an associative array
812 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
814 * @param $variant \type{\string} language variant of url (for sr, zh..)
815 * @return \type{\string} the URL
817 public function getLocalURL( $query = '', $variant = false ) {
818 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
819 global $wgVariantArticlePath, $wgContLang, $wgUser;
821 if( is_array( $query ) ) {
822 $query = wfArrayToCGI( $query );
825 // internal links should point to same variant as current page (only anonymous users)
826 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
827 $pref = $wgContLang->getPreferredVariant(false);
828 if($pref != $wgContLang->getCode())
832 if ( $this->isExternal() ) {
833 $url = $this->getFullURL();
835 // This is currently only used for edit section links in the
836 // context of interwiki transclusion. In theory we should
837 // append the query to the end of any existing query string,
838 // but interwiki transclusion is already broken in that case.
842 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
843 if ( $query == '' ) {
844 if( $variant != false && $wgContLang->hasVariants() ) {
845 if( $wgVariantArticlePath == false ) {
846 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
848 $variantArticlePath = $wgVariantArticlePath;
850 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
851 $url = str_replace( '$1', $dbkey, $url );
853 $url = str_replace( '$1', $dbkey, $wgArticlePath );
856 global $wgActionPaths;
859 if( !empty( $wgActionPaths ) &&
860 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
862 $action = urldecode( $matches[2] );
863 if( isset( $wgActionPaths[$action] ) ) {
864 $query = $matches[1];
865 if( isset( $matches[4] ) ) $query .= $matches[4];
866 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
868 $url = wfAppendQuery( $url, $query );
872 if ( $url === false ) {
873 if ( $query == '-' ) {
876 $url = "{$wgScript}?title={$dbkey}&{$query}";
880 // FIXME: this causes breakage in various places when we
881 // actually expected a local URL and end up with dupe prefixes.
882 if ($wgRequest->getVal('action') == 'render') {
883 $url = $wgServer . $url;
886 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
891 * Get a URL that's the simplest URL that will be valid to link, locally,
892 * to the current Title. It includes the fragment, but does not include
893 * the server unless action=render is used (or the link is external). If
894 * there's a fragment but the prefixed text is empty, we just return a link
897 * The result obviously should not be URL-escaped, but does need to be
898 * HTML-escaped if it's being output in HTML.
900 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
901 * query string. Keys and values will be escaped.
902 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
903 * for external links. Default is "false" (same variant as current page,
904 * for anonymous users).
905 * @return \type{\string} the URL
907 public function getLinkUrl( $query = array(), $variant = false ) {
908 wfProfileIn( __METHOD__
);
909 if( $this->isExternal() ) {
910 $ret = $this->getFullURL( $query );
911 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
912 $ret = $this->getFragmentForURL();
914 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
916 wfProfileOut( __METHOD__
);
921 * Get an HTML-escaped version of the URL form, suitable for
922 * using in a link, without a server name or fragment
924 * @param $query \type{\string} an optional query string
925 * @return \type{\string} the URL
927 public function escapeLocalURL( $query = '' ) {
928 return htmlspecialchars( $this->getLocalURL( $query ) );
932 * Get an HTML-escaped version of the URL form, suitable for
933 * using in a link, including the server name and fragment
935 * @param $query \type{\string} an optional query string
936 * @return \type{\string} the URL
938 public function escapeFullURL( $query = '' ) {
939 return htmlspecialchars( $this->getFullURL( $query ) );
943 * Get the URL form for an internal link.
944 * - Used in various Squid-related code, in case we have a different
945 * internal hostname for the server from the exposed one.
947 * @param $query \type{\string} an optional query string
948 * @param $variant \type{\string} language variant of url (for sr, zh..)
949 * @return \type{\string} the URL
951 public function getInternalURL( $query = '', $variant = false ) {
952 global $wgInternalServer;
953 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
954 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
959 * Get the edit URL for this Title
961 * @return \type{\string} the URL, or a null string if this is an
964 public function getEditURL() {
965 if ( $this->mInterwiki
!= '' ) { return ''; }
966 $s = $this->getLocalURL( 'action=edit' );
972 * Get the HTML-escaped displayable text form.
973 * Used for the title field in <a> tags.
975 * @return \type{\string} the text, including any prefixes
977 public function getEscapedText() {
978 return htmlspecialchars( $this->getPrefixedText() );
982 * Is this Title interwiki?
984 * @return \type{\bool}
986 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
989 * Is this page "semi-protected" - the *only* protection is autoconfirm?
991 * @param $action \type{\string} Action to check (default: edit)
992 * @return \type{\bool}
994 public function isSemiProtected( $action = 'edit' ) {
995 if( $this->exists() ) {
996 $restrictions = $this->getRestrictions( $action );
997 if( count( $restrictions ) > 0 ) {
998 foreach( $restrictions as $restriction ) {
999 if( strtolower( $restriction ) != 'autoconfirmed' )
1008 # If it doesn't exist, it can't be protected
1014 * Does the title correspond to a protected article?
1016 * @param $action \type{\string} the action the page is protected from,
1017 * by default checks all actions.
1018 * @return \type{\bool}
1020 public function isProtected( $action = '' ) {
1021 global $wgRestrictionLevels;
1023 $restrictionTypes = $this->getRestrictionTypes();
1025 # Special pages have inherent protection
1026 if( $this->getNamespace() == NS_SPECIAL
)
1029 # Check regular protection levels
1030 foreach( $restrictionTypes as $type ){
1031 if( $action == $type ||
$action == '' ) {
1032 $r = $this->getRestrictions( $type );
1033 foreach( $wgRestrictionLevels as $level ) {
1034 if( in_array( $level, $r ) && $level != '' ) {
1045 * Is this a conversion table for the LanguageConverter?
1047 * @return \type{\bool}
1049 public function isConversionTable() {
1050 if($this->getNamespace() == NS_MEDIAWIKI
1051 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1059 * Is $wgUser watching this page?
1061 * @return \type{\bool}
1063 public function userIsWatching() {
1066 if ( is_null( $this->mWatched
) ) {
1067 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1068 $this->mWatched
= false;
1070 $this->mWatched
= $wgUser->isWatched( $this );
1073 return $this->mWatched
;
1077 * Can $wgUser perform $action on this page?
1078 * This skips potentially expensive cascading permission checks
1079 * as well as avoids expensive error formatting
1081 * Suitable for use for nonessential UI controls in common cases, but
1082 * _not_ for functional access control.
1084 * May provide false positives, but should never provide a false negative.
1086 * @param $action \type{\string} action that permission needs to be checked for
1087 * @return \type{\bool}
1089 public function quickUserCan( $action ) {
1090 return $this->userCan( $action, false );
1094 * Determines if $wgUser is unable to edit this page because it has been protected
1095 * by $wgNamespaceProtection.
1097 * @return \type{\bool}
1099 public function isNamespaceProtected() {
1100 global $wgNamespaceProtection, $wgUser;
1101 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1102 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1103 if( $right != '' && !$wgUser->isAllowed( $right ) )
1111 * Can $wgUser perform $action on this page?
1113 * @param $action \type{\string} action that permission needs to be checked for
1114 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1115 * @return \type{\bool}
1117 public function userCan( $action, $doExpensiveQueries = true ) {
1119 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1123 * Can $user perform $action on this page?
1125 * FIXME: This *does not* check throttles (User::pingLimiter()).
1127 * @param $action \type{\string}action that permission needs to be checked for
1128 * @param $user \type{User} user to check
1129 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1130 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1131 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1133 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1134 if( !StubObject
::isRealObject( $user ) ) {
1135 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1137 $wgUser->_unstub( '', 5 );
1140 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1144 global $wgEmailConfirmToEdit;
1146 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1147 $errors[] = array( 'confirmedittext' );
1150 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1151 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1152 $block = $user->mBlock
;
1154 // This is from OutputPage::blockedPage
1155 // Copied at r23888 by werdna
1157 $id = $user->blockedBy();
1158 $reason = $user->blockedFor();
1159 if( $reason == '' ) {
1160 $reason = wfMsg( 'blockednoreason' );
1164 if ( is_numeric( $id ) ) {
1165 $name = User
::whoIs( $id );
1170 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1171 $blockid = $block->mId
;
1172 $blockExpiry = $user->mBlock
->mExpiry
;
1173 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1175 if ( $blockExpiry == 'infinity' ) {
1176 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1177 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1179 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1180 if ( strpos( $option, ':' ) == false )
1183 list ($show, $value) = explode( ":", $option );
1185 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1186 $blockExpiry = $show;
1191 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1194 $intended = $user->mBlock
->mAddress
;
1196 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1197 $blockid, $blockExpiry, $intended, $blockTimestamp );
1200 // Remove the errors being ignored.
1202 foreach( $errors as $index => $error ) {
1203 $error_key = is_array($error) ?
$error[0] : $error;
1205 if (in_array( $error_key, $ignoreErrors )) {
1206 unset($errors[$index]);
1214 * Can $user perform $action on this page? This is an internal function,
1215 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1216 * checks on wfReadOnly() and blocks)
1218 * @param $action \type{\string} action that permission needs to be checked for
1219 * @param $user \type{User} user to check
1220 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1221 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1222 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1224 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1225 wfProfileIn( __METHOD__
);
1229 // First stop is permissions checks, which fail most often, and which are easiest to test.
1230 if ( $action == 'move' ) {
1231 if( !$user->isAllowed( 'move-rootuserpages' )
1232 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1234 // Show user page-specific message only if the user can move other pages
1235 $errors[] = array( 'cant-move-user-page' );
1238 // Check if user is allowed to move files if it's a file
1239 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1240 $errors[] = array( 'movenotallowedfile' );
1243 if( !$user->isAllowed( 'move' ) ) {
1244 // User can't move anything
1245 global $wgGroupPermissions;
1246 $userCanMove = false;
1247 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1248 $userCanMove = $wgGroupPermissions['user']['move'];
1250 $autoconfirmedCanMove = false;
1251 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1252 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1254 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1255 // custom message if logged-in users without any special rights can move
1256 $errors[] = array ( 'movenologintext' );
1258 $errors[] = array ('movenotallowed');
1261 } elseif ( $action == 'create' ) {
1262 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1263 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1265 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1267 } elseif( $action == 'move-target' ) {
1268 if( !$user->isAllowed( 'move' ) ) {
1269 // User can't move anything
1270 $errors[] = array ('movenotallowed');
1271 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1272 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1274 // Show user page-specific message only if the user can move other pages
1275 $errors[] = array( 'cant-move-to-user-page' );
1277 } elseif( !$user->isAllowed( $action ) ) {
1280 // We avoid expensive display logic for quickUserCan's and such
1283 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1284 User
::getGroupsWithPermission( $action ) );
1291 $wgLang->commaList( $groups ),
1295 $return = array( "badaccess-group0" );
1297 $errors[] = $return;
1300 # Short-circuit point
1301 if( $short && count($errors) > 0 ) {
1302 wfProfileOut( __METHOD__
);
1306 // Use getUserPermissionsErrors instead
1307 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1308 wfProfileOut( __METHOD__
);
1309 return $result ?
array() : array( array( 'badaccess-group0' ) );
1311 // Check getUserPermissionsErrors hook
1312 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1313 if( is_array($result) && count($result) && !is_array($result[0]) )
1314 $errors[] = $result; # A single array representing an error
1315 else if( is_array($result) && is_array($result[0]) )
1316 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1317 else if( $result !== '' && is_string($result) )
1318 $errors[] = array($result); # A string representing a message-id
1319 else if( $result === false )
1320 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1322 # Short-circuit point
1323 if( $short && count($errors) > 0 ) {
1324 wfProfileOut( __METHOD__
);
1327 // Check getUserPermissionsErrorsExpensive hook
1328 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1329 if( is_array($result) && count($result) && !is_array($result[0]) )
1330 $errors[] = $result; # A single array representing an error
1331 else if( is_array($result) && is_array($result[0]) )
1332 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1333 else if( $result !== '' && is_string($result) )
1334 $errors[] = array($result); # A string representing a message-id
1335 else if( $result === false )
1336 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1338 # Short-circuit point
1339 if( $short && count($errors) > 0 ) {
1340 wfProfileOut( __METHOD__
);
1344 # Only 'createaccount' and 'execute' can be performed on
1345 # special pages, which don't actually exist in the DB.
1346 $specialOKActions = array( 'createaccount', 'execute' );
1347 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1348 $errors[] = array('ns-specialprotected');
1351 # Check $wgNamespaceProtection for restricted namespaces
1352 if( $this->isNamespaceProtected() ) {
1353 $ns = $this->getNamespace() == NS_MAIN ?
1354 wfMsg( 'nstab-main' ) : $this->getNsText();
1355 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1356 array('protectedinterface') : array( 'namespaceprotected', $ns );
1359 # Protect css/js subpages of user pages
1360 # XXX: this might be better using restrictions
1361 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1362 # and $this->userCanEditJsSubpage() from working
1363 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1364 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1365 && $action != 'patrol'
1366 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1368 $errors[] = array('customcssjsprotected');
1369 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1370 && $action != 'patrol'
1371 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1373 $errors[] = array('customcssjsprotected');
1376 # Check against page_restrictions table requirements on this
1377 # page. The user must possess all required rights for this action.
1378 foreach( $this->getRestrictions($action) as $right ) {
1379 // Backwards compatibility, rewrite sysop -> protect
1380 if( $right == 'sysop' ) {
1383 if( $right != '' && !$user->isAllowed( $right ) ) {
1384 // Users with 'editprotected' permission can edit protected pages
1385 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1386 // Users with 'editprotected' permission cannot edit protected pages
1387 // with cascading option turned on.
1388 if( $this->mCascadeRestriction
) {
1389 $errors[] = array( 'protectedpagetext', $right );
1392 $errors[] = array( 'protectedpagetext', $right );
1396 # Short-circuit point
1397 if( $short && count($errors) > 0 ) {
1398 wfProfileOut( __METHOD__
);
1402 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1403 # We /could/ use the protection level on the source page, but it's fairly ugly
1404 # as we have to establish a precedence hierarchy for pages included by multiple
1405 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1406 # as they could remove the protection anyway.
1407 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1408 # Cascading protection depends on more than this page...
1409 # Several cascading protected pages may include this page...
1410 # Check each cascading level
1411 # This is only for protection restrictions, not for all actions
1412 if( isset($restrictions[$action]) ) {
1413 foreach( $restrictions[$action] as $right ) {
1414 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1415 if( $right != '' && !$user->isAllowed( $right ) ) {
1417 foreach( $cascadingSources as $page )
1418 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1419 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1424 # Short-circuit point
1425 if( $short && count($errors) > 0 ) {
1426 wfProfileOut( __METHOD__
);
1430 if( $action == 'protect' ) {
1431 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1432 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1436 if( $action == 'create' ) {
1437 $title_protection = $this->getTitleProtection();
1438 if( is_array($title_protection) ) {
1439 extract($title_protection); // is this extract() really needed?
1441 if( $pt_create_perm == 'sysop' ) {
1442 $pt_create_perm = 'protect'; // B/C
1444 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1445 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1448 } elseif( $action == 'move' ) {
1449 // Check for immobile pages
1450 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1451 // Specific message for this case
1452 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1453 } elseif( !$this->isMovable() ) {
1454 // Less specific message for rarer cases
1455 $errors[] = array( 'immobile-page' );
1457 } elseif( $action == 'move-target' ) {
1458 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1459 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1460 } elseif( !$this->isMovable() ) {
1461 $errors[] = array( 'immobile-target-page' );
1465 wfProfileOut( __METHOD__
);
1470 * Is this title subject to title protection?
1472 * @return \type{\mixed} An associative array representing any existent title
1473 * protection, or false if there's none.
1475 private function getTitleProtection() {
1476 // Can't protect pages in special namespaces
1477 if ( $this->getNamespace() < 0 ) {
1481 // Can't protect pages that exist.
1482 if ($this->exists()) {
1486 $dbr = wfGetDB( DB_SLAVE
);
1487 $res = $dbr->select( 'protected_titles', '*',
1488 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1491 if ($row = $dbr->fetchRow( $res )) {
1499 * Update the title protection status
1501 * @param $create_perm \type{\string} Permission required for creation
1502 * @param $reason \type{\string} Reason for protection
1503 * @param $expiry \type{\string} Expiry timestamp
1504 * @return boolean true
1506 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1507 global $wgUser,$wgContLang;
1509 if ($create_perm == implode(',',$this->getRestrictions('create'))
1510 && $expiry == $this->mRestrictionsExpiry
['create']) {
1515 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1517 $dbw = wfGetDB( DB_MASTER
);
1519 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1521 $expiry_description = '';
1522 if ( $encodedExpiry != 'infinity' ) {
1523 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1524 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1527 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1530 # Update protection table
1531 if ($create_perm != '' ) {
1532 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1534 'pt_namespace' => $namespace,
1535 'pt_title' => $title,
1536 'pt_create_perm' => $create_perm,
1537 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1538 'pt_expiry' => $encodedExpiry,
1539 'pt_user' => $wgUser->getId(),
1540 'pt_reason' => $reason,
1544 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1545 'pt_title' => $title ), __METHOD__
);
1547 # Update the protection log
1548 if( $dbw->affectedRows() ) {
1549 $log = new LogPage( 'protect' );
1551 if( $create_perm ) {
1552 $params = array("[create=$create_perm] $expiry_description",'');
1553 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1555 $log->addEntry( 'unprotect', $this, $reason );
1563 * Remove any title protection due to page existing
1565 public function deleteTitleProtection() {
1566 $dbw = wfGetDB( DB_MASTER
);
1568 $dbw->delete( 'protected_titles',
1569 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1574 * Would anybody with sufficient privileges be able to move this page?
1575 * Some pages just aren't movable.
1577 * @return \type{\bool} TRUE or FALSE
1579 public function isMovable() {
1580 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1584 * Can $wgUser read this page?
1586 * @return \type{\bool}
1587 * @todo fold these checks into userCan()
1589 public function userCanRead() {
1590 global $wgUser, $wgGroupPermissions;
1592 static $useShortcut = null;
1594 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1595 if( is_null( $useShortcut ) ) {
1596 global $wgRevokePermissions;
1597 $useShortcut = true;
1598 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1599 # Not a public wiki, so no shortcut
1600 $useShortcut = false;
1601 } elseif( !empty( $wgRevokePermissions ) ) {
1603 * Iterate through each group with permissions being revoked (key not included since we don't care
1604 * what the group name is), then check if the read permission is being revoked. If it is, then
1605 * we don't use the shortcut below since the user might not be able to read, even though anon
1606 * reading is allowed.
1608 foreach( $wgRevokePermissions as $perms ) {
1609 if( !empty( $perms['read'] ) ) {
1610 # We might be removing the read right from the user, so no shortcut
1611 $useShortcut = false;
1619 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1620 if ( $result !== null ) {
1624 # Shortcut for public wikis, allows skipping quite a bit of code
1628 if( $wgUser->isAllowed( 'read' ) ) {
1631 global $wgWhitelistRead;
1634 * Always grant access to the login page.
1635 * Even anons need to be able to log in.
1637 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1642 * Bail out if there isn't whitelist
1644 if( !is_array($wgWhitelistRead) ) {
1649 * Check for explicit whitelisting
1651 $name = $this->getPrefixedText();
1652 $dbName = $this->getPrefixedDBKey();
1653 // Check with and without underscores
1654 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1658 * Old settings might have the title prefixed with
1659 * a colon for main-namespace pages
1661 if( $this->getNamespace() == NS_MAIN
) {
1662 if( in_array( ':' . $name, $wgWhitelistRead ) )
1667 * If it's a special page, ditch the subpage bit
1670 if( $this->getNamespace() == NS_SPECIAL
) {
1671 $name = $this->getDBkey();
1672 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1673 if ( $name === false ) {
1674 # Invalid special page, but we show standard login required message
1678 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1679 if( in_array( $pure, $wgWhitelistRead, true ) )
1688 * Is this a talk page of some sort?
1690 * @return \type{\bool}
1692 public function isTalkPage() {
1693 return MWNamespace
::isTalk( $this->getNamespace() );
1697 * Is this a subpage?
1699 * @return \type{\bool}
1701 public function isSubpage() {
1702 return MWNamespace
::hasSubpages( $this->mNamespace
)
1703 ?
strpos( $this->getText(), '/' ) !== false
1708 * Does this have subpages? (Warning, usually requires an extra DB query.)
1710 * @return \type{\bool}
1712 public function hasSubpages() {
1713 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1718 # We dynamically add a member variable for the purpose of this method
1719 # alone to cache the result. There's no point in having it hanging
1720 # around uninitialized in every Title object; therefore we only add it
1721 # if needed and don't declare it statically.
1722 if( isset( $this->mHasSubpages
) ) {
1723 return $this->mHasSubpages
;
1726 $subpages = $this->getSubpages( 1 );
1727 if( $subpages instanceof TitleArray
)
1728 return $this->mHasSubpages
= (bool)$subpages->count();
1729 return $this->mHasSubpages
= false;
1733 * Get all subpages of this page.
1735 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1736 * @return mixed TitleArray, or empty array if this page's namespace
1737 * doesn't allow subpages
1739 public function getSubpages( $limit = -1 ) {
1740 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1743 $dbr = wfGetDB( DB_SLAVE
);
1744 $conds['page_namespace'] = $this->getNamespace();
1745 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1748 $options['LIMIT'] = $limit;
1749 return $this->mSubpages
= TitleArray
::newFromResult(
1750 $dbr->select( 'page',
1751 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1760 * Could this page contain custom CSS or JavaScript, based
1763 * @return \type{\bool}
1765 public function isCssOrJsPage() {
1766 return $this->mNamespace
== NS_MEDIAWIKI
1767 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1771 * Is this a .css or .js subpage of a user page?
1772 * @return \type{\bool}
1774 public function isCssJsSubpage() {
1775 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1779 * Is this a *valid* .css or .js subpage of a user page?
1780 * Check that the corresponding skin exists
1782 * @return \type{\bool}
1784 public function isValidCssJsSubpage() {
1785 if ( $this->isCssJsSubpage() ) {
1786 $name = $this->getSkinFromCssJsSubpage();
1787 if ( $name == 'common' ) return true;
1788 $skinNames = Skin
::getSkinNames();
1789 return array_key_exists( $name, $skinNames );
1796 * Trim down a .css or .js subpage title to get the corresponding skin name
1798 * @return string containing skin name from .css or .js subpage title
1800 public function getSkinFromCssJsSubpage() {
1801 $subpage = explode( '/', $this->mTextform
);
1802 $subpage = $subpage[ count( $subpage ) - 1 ];
1803 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1807 * Is this a .css subpage of a user page?
1809 * @return \type{\bool}
1811 public function isCssSubpage() {
1812 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1816 * Is this a .js subpage of a user page?
1818 * @return \type{\bool}
1820 public function isJsSubpage() {
1821 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1825 * Protect css subpages of user pages: can $wgUser edit
1828 * @return \type{\bool}
1829 * @todo XXX: this might be better using restrictions
1831 public function userCanEditCssSubpage() {
1833 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1834 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1837 * Protect js subpages of user pages: can $wgUser edit
1840 * @return \type{\bool}
1841 * @todo XXX: this might be better using restrictions
1843 public function userCanEditJsSubpage() {
1845 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1846 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1850 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1852 * @return \type{\bool} If the page is subject to cascading restrictions.
1854 public function isCascadeProtected() {
1855 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1856 return ( $sources > 0 );
1860 * Cascading protection: Get the source of any cascading restrictions on this page.
1862 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages
1863 * that the restrictions have come from.
1864 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1865 * objects of the pages from which cascading restrictions have come,
1866 * false for none, or true if such restrictions exist, but $get_pages was not set.
1867 * The restriction array is an array of each type, each of which contains a
1868 * array of unique groups.
1870 public function getCascadeProtectionSources( $get_pages = true ) {
1871 $pagerestrictions = array();
1873 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1874 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1875 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1876 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1879 wfProfileIn( __METHOD__
);
1881 $dbr = wfGetDB( DB_SLAVE
);
1883 if ( $this->getNamespace() == NS_FILE
) {
1884 $tables = array ('imagelinks', 'page_restrictions');
1885 $where_clauses = array(
1886 'il_to' => $this->getDBkey(),
1888 'pr_cascade' => 1 );
1890 $tables = array ('templatelinks', 'page_restrictions');
1891 $where_clauses = array(
1892 'tl_namespace' => $this->getNamespace(),
1893 'tl_title' => $this->getDBkey(),
1895 'pr_cascade' => 1 );
1899 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1900 $where_clauses[] = 'page_id=pr_page';
1903 $cols = array( 'pr_expiry' );
1906 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1908 $sources = $get_pages ?
array() : false;
1909 $now = wfTimestampNow();
1910 $purgeExpired = false;
1912 foreach( $res as $row ) {
1913 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1914 if( $expiry > $now ) {
1916 $page_id = $row->pr_page
;
1917 $page_ns = $row->page_namespace
;
1918 $page_title = $row->page_title
;
1919 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1920 # Add groups needed for each restriction type if its not already there
1921 # Make sure this restriction type still exists
1923 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1924 $pagerestrictions[$row->pr_type
] = array();
1927 if ( isset($pagerestrictions[$row->pr_type
]) &&
1928 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1929 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1935 // Trigger lazy purge of expired restrictions from the db
1936 $purgeExpired = true;
1939 if( $purgeExpired ) {
1940 Title
::purgeExpiredRestrictions();
1943 wfProfileOut( __METHOD__
);
1946 $this->mCascadeSources
= $sources;
1947 $this->mCascadingRestrictions
= $pagerestrictions;
1949 $this->mHasCascadingRestrictions
= $sources;
1951 return array( $sources, $pagerestrictions );
1955 * Returns cascading restrictions for the current article
1959 function areRestrictionsCascading() {
1960 if (!$this->mRestrictionsLoaded
) {
1961 $this->loadRestrictions();
1964 return $this->mCascadeRestriction
;
1968 * Loads a string into mRestrictions array
1970 * @param $res \type{Resource} restrictions as an SQL result.
1971 * @param $oldFashionedRestrictions string comma-separated list of page
1972 * restrictions from page table (pre 1.10)
1974 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1976 $dbr = wfGetDB( DB_SLAVE
);
1978 while( $row = $dbr->fetchObject( $res ) ) {
1982 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1986 * Compiles list of active page restrictions from both page table (pre 1.10)
1987 * and page_restrictions table
1989 * @param $rows array of db result objects
1990 * @param $oldFashionedRestrictions string comma-separated list of page
1991 * restrictions from page table (pre 1.10)
1993 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1994 $dbr = wfGetDB( DB_SLAVE
);
1996 $restrictionTypes = $this->getRestrictionTypes();
1998 foreach( $restrictionTypes as $type ){
1999 $this->mRestrictions
[$type] = array();
2000 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
2003 $this->mCascadeRestriction
= false;
2005 # Backwards-compatibility: also load the restrictions from the page record (old format).
2007 if ( $oldFashionedRestrictions === null ) {
2008 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2009 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2012 if ($oldFashionedRestrictions != '') {
2014 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2015 $temp = explode( '=', trim( $restrict ) );
2016 if(count($temp) == 1) {
2017 // old old format should be treated as edit/move restriction
2018 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2019 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2021 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2025 $this->mOldRestrictions
= true;
2029 if( count($rows) ) {
2030 # Current system - load second to make them override.
2031 $now = wfTimestampNow();
2032 $purgeExpired = false;
2034 foreach( $rows as $row ) {
2035 # Cycle through all the restrictions.
2037 // Don't take care of restrictions types that aren't allowed
2039 if( !in_array( $row->pr_type
, $restrictionTypes ) )
2042 // This code should be refactored, now that it's being used more generally,
2043 // But I don't really see any harm in leaving it in Block for now -werdna
2044 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2046 // Only apply the restrictions if they haven't expired!
2047 if ( !$expiry ||
$expiry > $now ) {
2048 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2049 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2051 $this->mCascadeRestriction |
= $row->pr_cascade
;
2053 // Trigger a lazy purge of expired restrictions
2054 $purgeExpired = true;
2058 if( $purgeExpired ) {
2059 Title
::purgeExpiredRestrictions();
2063 $this->mRestrictionsLoaded
= true;
2067 * Load restrictions from the page_restrictions table
2069 * @param $oldFashionedRestrictions string comma-separated list of page
2070 * restrictions from page table (pre 1.10)
2072 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2073 if( !$this->mRestrictionsLoaded
) {
2074 if ($this->exists()) {
2075 $dbr = wfGetDB( DB_SLAVE
);
2077 $res = $dbr->select( 'page_restrictions', '*',
2078 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2080 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2082 $title_protection = $this->getTitleProtection();
2084 if (is_array($title_protection)) {
2085 extract($title_protection);
2087 $now = wfTimestampNow();
2088 $expiry = Block
::decodeExpiry($pt_expiry);
2090 if (!$expiry ||
$expiry > $now) {
2091 // Apply the restrictions
2092 $this->mRestrictionsExpiry
['create'] = $expiry;
2093 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
2094 } else { // Get rid of the old restrictions
2095 Title
::purgeExpiredRestrictions();
2098 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
2100 $this->mRestrictionsLoaded
= true;
2106 * Purge expired restrictions from the page_restrictions table
2108 static function purgeExpiredRestrictions() {
2109 $dbw = wfGetDB( DB_MASTER
);
2110 $dbw->delete( 'page_restrictions',
2111 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2114 $dbw->delete( 'protected_titles',
2115 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2120 * Accessor/initialisation for mRestrictions
2122 * @param $action \type{\string} action that permission needs to be checked for
2123 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2125 public function getRestrictions( $action ) {
2126 if( !$this->mRestrictionsLoaded
) {
2127 $this->loadRestrictions();
2129 return isset( $this->mRestrictions
[$action] )
2130 ?
$this->mRestrictions
[$action]
2135 * Get the expiry time for the restriction against a given action
2137 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2138 * or not protected at all, or false if the action is not recognised.
2140 public function getRestrictionExpiry( $action ) {
2141 if( !$this->mRestrictionsLoaded
) {
2142 $this->loadRestrictions();
2144 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2148 * Is there a version of this page in the deletion archive?
2150 * @return \type{\int} the number of archived revisions
2152 public function isDeleted() {
2153 if( $this->getNamespace() < 0 ) {
2156 $dbr = wfGetDB( DB_SLAVE
);
2157 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2158 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2161 if( $this->getNamespace() == NS_FILE
) {
2162 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2163 array( 'fa_name' => $this->getDBkey() ),
2172 * Is there a version of this page in the deletion archive?
2176 public function isDeletedQuick() {
2177 if( $this->getNamespace() < 0 ) {
2180 $dbr = wfGetDB( DB_SLAVE
);
2181 $deleted = (bool)$dbr->selectField( 'archive', '1',
2182 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2185 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2186 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2187 array( 'fa_name' => $this->getDBkey() ),
2195 * Get the article ID for this Title from the link cache,
2196 * adding it if necessary
2198 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2200 * @return \type{\int} the ID
2202 public function getArticleID( $flags = 0 ) {
2203 if( $this->getNamespace() < 0 ) {
2204 return $this->mArticleID
= 0;
2206 $linkCache = LinkCache
::singleton();
2207 if( $flags & GAID_FOR_UPDATE
) {
2208 $oldUpdate = $linkCache->forUpdate( true );
2209 $linkCache->clearLink( $this );
2210 $this->mArticleID
= $linkCache->addLinkObj( $this );
2211 $linkCache->forUpdate( $oldUpdate );
2213 if( -1 == $this->mArticleID
) {
2214 $this->mArticleID
= $linkCache->addLinkObj( $this );
2217 return $this->mArticleID
;
2221 * Is this an article that is a redirect page?
2222 * Uses link cache, adding it if necessary
2224 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2225 * @return \type{\bool}
2227 public function isRedirect( $flags = 0 ) {
2228 if( !is_null($this->mRedirect
) )
2229 return $this->mRedirect
;
2230 # Calling getArticleID() loads the field from cache as needed
2231 if( !$this->getArticleID($flags) ) {
2232 return $this->mRedirect
= false;
2234 $linkCache = LinkCache
::singleton();
2235 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2237 return $this->mRedirect
;
2241 * What is the length of this page?
2242 * Uses link cache, adding it if necessary
2244 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2245 * @return \type{\bool}
2247 public function getLength( $flags = 0 ) {
2248 if( $this->mLength
!= -1 )
2249 return $this->mLength
;
2250 # Calling getArticleID() loads the field from cache as needed
2251 if( !$this->getArticleID($flags) ) {
2252 return $this->mLength
= 0;
2254 $linkCache = LinkCache
::singleton();
2255 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2257 return $this->mLength
;
2261 * What is the page_latest field for this page?
2263 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2264 * @return \type{\int} or false if the page doesn't exist
2266 public function getLatestRevID( $flags = 0 ) {
2267 if( $this->mLatestID
!== false )
2268 return $this->mLatestID
;
2270 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2271 $this->mLatestID
= (int)$db->selectField(
2272 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2273 return $this->mLatestID
;
2277 * This clears some fields in this object, and clears any associated
2278 * keys in the "bad links" section of the link cache.
2280 * - This is called from Article::insertNewArticle() to allow
2281 * loading of the new page_id. It's also called from
2282 * Article::doDeleteArticle()
2284 * @param $newid \type{\int} the new Article ID
2286 public function resetArticleID( $newid ) {
2287 $linkCache = LinkCache
::singleton();
2288 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2290 if ( $newid === false ) {
2291 $this->mArticleID
= -1;
2293 $this->mArticleID
= intval( $newid );
2295 $this->mRestrictionsLoaded
= false;
2296 $this->mRestrictions
= array();
2297 $this->mRedirect
= null;
2298 $this->mLength
= -1;
2299 $this->mLatestID
= false;
2303 * Updates page_touched for this page; called from LinksUpdate.php
2305 * @return \type{\bool} true if the update succeded
2307 public function invalidateCache() {
2308 if( wfReadOnly() ) {
2311 $dbw = wfGetDB( DB_MASTER
);
2312 $success = $dbw->update( 'page',
2313 array( 'page_touched' => $dbw->timestamp() ),
2317 HTMLFileCache
::clearFileCache( $this );
2322 * Prefix some arbitrary text with the namespace or interwiki prefix
2325 * @param $name \type{\string} the text
2326 * @return \type{\string} the prefixed text
2329 /* private */ function prefix( $name ) {
2331 if ( $this->mInterwiki
!= '' ) {
2332 $p = $this->mInterwiki
. ':';
2334 if ( 0 != $this->mNamespace
) {
2335 $p .= $this->getNsText() . ':';
2341 * Returns a simple regex that will match on characters and sequences invalid in titles.
2342 * Note that this doesn't pick up many things that could be wrong with titles, but that
2343 * replacing this regex with something valid will make many titles valid.
2345 * @return string regex string
2347 static function getTitleInvalidRegex() {
2348 static $rxTc = false;
2350 # Matching titles will be held as illegal.
2352 # Any character not allowed is forbidden...
2353 '[^' . Title
::legalChars() . ']' .
2354 # URL percent encoding sequences interfere with the ability
2355 # to round-trip titles -- you can't link to them consistently.
2356 '|%[0-9A-Fa-f]{2}' .
2357 # XML/HTML character references produce similar issues.
2358 '|&[A-Za-z0-9\x80-\xff]+;' .
2360 '|&#x[0-9A-Fa-f]+;' .
2368 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2370 * @param $text string containing title to capitalize
2371 * @param $ns int namespace index, defaults to NS_MAIN
2372 * @return String containing capitalized title
2374 public static function capitalize( $text, $ns = NS_MAIN
) {
2377 if ( MWNamespace
::isCapitalized( $ns ) )
2378 return $wgContLang->ucfirst( $text );
2384 * Secure and split - main initialisation function for this object
2386 * Assumes that mDbkeyform has been set, and is urldecoded
2387 * and uses underscores, but not otherwise munged. This function
2388 * removes illegal characters, splits off the interwiki and
2389 * namespace prefixes, sets the other forms, and canonicalizes
2392 * @return \type{\bool} true on success
2394 private function secureAndSplit() {
2395 global $wgContLang, $wgLocalInterwiki;
2398 $rxTc = self
::getTitleInvalidRegex();
2400 $this->mInterwiki
= $this->mFragment
= '';
2401 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2403 $dbkey = $this->mDbkeyform
;
2405 # Strip Unicode bidi override characters.
2406 # Sometimes they slip into cut-n-pasted page titles, where the
2407 # override chars get included in list displays.
2408 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2410 # Clean up whitespace
2411 # Note: use of the /u option on preg_replace here will cause
2412 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2413 # conveniently disabling them.
2415 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2416 $dbkey = trim( $dbkey, '_' );
2418 if ( $dbkey == '' ) {
2422 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2423 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2427 $this->mDbkeyform
= $dbkey;
2429 # Initial colon indicates main namespace rather than specified default
2430 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2431 if ( ':' == $dbkey{0} ) {
2432 $this->mNamespace
= NS_MAIN
;
2433 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2434 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2437 # Namespace or interwiki prefix
2439 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2442 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2444 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2445 # Ordinary namespace
2447 $this->mNamespace
= $ns;
2448 # For Talk:X pages, check if X has a "namespace" prefix
2449 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2450 if( $wgContLang->getNsIndex( $x[1] ) )
2451 return false; # Disallow Talk:File:x type titles...
2452 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2453 return false; # Disallow Talk:Interwiki:x type titles...
2455 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2457 # Can't make a local interwiki link to an interwiki link.
2458 # That's just crazy!
2464 $this->mInterwiki
= $wgContLang->lc( $p );
2466 # Redundant interwiki prefix to the local wiki
2467 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2468 if( $dbkey == '' ) {
2469 # Can't have an empty self-link
2472 $this->mInterwiki
= '';
2474 # Do another namespace split...
2478 # If there's an initial colon after the interwiki, that also
2479 # resets the default namespace
2480 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2481 $this->mNamespace
= NS_MAIN
;
2482 $dbkey = substr( $dbkey, 1 );
2485 # If there's no recognized interwiki or namespace,
2486 # then let the colon expression be part of the title.
2491 # We already know that some pages won't be in the database!
2493 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2494 $this->mArticleID
= 0;
2496 $fragment = strstr( $dbkey, '#' );
2497 if ( false !== $fragment ) {
2498 $this->setFragment( $fragment );
2499 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2500 # remove whitespace again: prevents "Foo_bar_#"
2501 # becoming "Foo_bar_"
2502 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2505 # Reject illegal characters.
2507 if( preg_match( $rxTc, $dbkey ) ) {
2512 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2513 * reachable due to the way web browsers deal with 'relative' URLs.
2514 * Also, they conflict with subpage syntax. Forbid them explicitly.
2516 if ( strpos( $dbkey, '.' ) !== false &&
2517 ( $dbkey === '.' ||
$dbkey === '..' ||
2518 strpos( $dbkey, './' ) === 0 ||
2519 strpos( $dbkey, '../' ) === 0 ||
2520 strpos( $dbkey, '/./' ) !== false ||
2521 strpos( $dbkey, '/../' ) !== false ||
2522 substr( $dbkey, -2 ) == '/.' ||
2523 substr( $dbkey, -3 ) == '/..' ) )
2529 * Magic tilde sequences? Nu-uh!
2531 if( strpos( $dbkey, '~~~' ) !== false ) {
2536 * Limit the size of titles to 255 bytes.
2537 * This is typically the size of the underlying database field.
2538 * We make an exception for special pages, which don't need to be stored
2539 * in the database, and may edge over 255 bytes due to subpage syntax
2540 * for long titles, e.g. [[Special:Block/Long name]]
2542 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2543 strlen( $dbkey ) > 512 )
2549 * Normally, all wiki links are forced to have
2550 * an initial capital letter so [[foo]] and [[Foo]]
2551 * point to the same place.
2553 * Don't force it for interwikis, since the other
2554 * site might be case-sensitive.
2556 $this->mUserCaseDBKey
= $dbkey;
2557 if( $this->mInterwiki
== '') {
2558 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2562 * Can't make a link to a namespace alone...
2563 * "empty" local links can only be self-links
2564 * with a fragment identifier.
2567 $this->mInterwiki
== '' &&
2568 $this->mNamespace
!= NS_MAIN
) {
2571 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2572 // IP names are not allowed for accounts, and can only be referring to
2573 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2574 // there are numerous ways to present the same IP. Having sp:contribs scan
2575 // them all is silly and having some show the edits and others not is
2576 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2577 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2578 IP
::sanitizeIP( $dbkey ) : $dbkey;
2579 // Any remaining initial :s are illegal.
2580 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2585 $this->mDbkeyform
= $dbkey;
2586 $this->mUrlform
= wfUrlencode( $dbkey );
2588 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2594 * Set the fragment for this title. Removes the first character from the
2595 * specified fragment before setting, so it assumes you're passing it with
2598 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2599 * Still in active use privately.
2601 * @param $fragment \type{\string} text
2603 public function setFragment( $fragment ) {
2604 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2608 * Get a Title object associated with the talk page of this article
2610 * @return \type{Title} the object for the talk page
2612 public function getTalkPage() {
2613 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2617 * Get a title object associated with the subject page of this
2620 * @return \type{Title} the object for the subject page
2622 public function getSubjectPage() {
2623 // Is this the same title?
2624 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2625 if( $this->getNamespace() == $subjectNS ) {
2628 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2632 * Get an array of Title objects linking to this Title
2633 * Also stores the IDs in the link cache.
2635 * WARNING: do not use this function on arbitrary user-supplied titles!
2636 * On heavily-used templates it will max out the memory.
2638 * @param $options Array: may be FOR UPDATE
2639 * @param $table String: table name
2640 * @param $prefix String: fields prefix
2641 * @return \type{\arrayof{Title}} the Title objects linking here
2643 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2644 $linkCache = LinkCache
::singleton();
2646 if ( count( $options ) > 0 ) {
2647 $db = wfGetDB( DB_MASTER
);
2649 $db = wfGetDB( DB_SLAVE
);
2652 $res = $db->select( array( 'page', $table ),
2653 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2655 "{$prefix}_from=page_id",
2656 "{$prefix}_namespace" => $this->getNamespace(),
2657 "{$prefix}_title" => $this->getDBkey() ),
2662 if ( $db->numRows( $res ) ) {
2663 foreach( $res as $row ) {
2664 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2665 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2666 $retVal[] = $titleObj;
2670 $db->freeResult( $res );
2675 * Get an array of Title objects using this Title as a template
2676 * Also stores the IDs in the link cache.
2678 * WARNING: do not use this function on arbitrary user-supplied titles!
2679 * On heavily-used templates it will max out the memory.
2681 * @param $options Array: may be FOR UPDATE
2682 * @return \type{\arrayof{Title}} the Title objects linking here
2684 public function getTemplateLinksTo( $options = array() ) {
2685 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2689 * Get an array of Title objects referring to non-existent articles linked from this page
2691 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2692 * @return \type{\arrayof{Title}} the Title objects
2694 public function getBrokenLinksFrom() {
2695 if ( $this->getArticleId() == 0 ) {
2696 # All links from article ID 0 are false positives
2700 $dbr = wfGetDB( DB_SLAVE
);
2701 $res = $dbr->select(
2702 array( 'page', 'pagelinks' ),
2703 array( 'pl_namespace', 'pl_title' ),
2705 'pl_from' => $this->getArticleId(),
2706 'page_namespace IS NULL'
2708 __METHOD__
, array(),
2712 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2718 foreach( $res as $row ) {
2719 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2726 * Get a list of URLs to purge from the Squid cache when this
2729 * @return \type{\arrayof{\string}} the URLs
2731 public function getSquidURLs() {
2735 $this->getInternalURL(),
2736 $this->getInternalURL( 'action=history' )
2739 // purge variant urls as well
2740 if($wgContLang->hasVariants()){
2741 $variants = $wgContLang->getVariants();
2742 foreach($variants as $vCode){
2743 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2744 $urls[] = $this->getInternalURL('',$vCode);
2752 * Purge all applicable Squid URLs
2754 public function purgeSquid() {
2756 if ( $wgUseSquid ) {
2757 $urls = $this->getSquidURLs();
2758 $u = new SquidUpdate( $urls );
2764 * Move this page without authentication
2766 * @param $nt \type{Title} the new page Title
2767 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2769 public function moveNoAuth( &$nt ) {
2770 return $this->moveTo( $nt, false );
2774 * Check whether a given move operation would be valid.
2775 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2777 * @param $nt \type{Title} the new title
2778 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2780 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2781 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2783 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2788 // Normally we'd add this to $errors, but we'll get
2789 // lots of syntax errors if $nt is not an object
2790 return array(array('badtitletext'));
2792 if( $this->equals( $nt ) ) {
2793 $errors[] = array('selfmove');
2795 if( !$this->isMovable() ) {
2796 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2798 if ( $nt->getInterwiki() != '' ) {
2799 $errors[] = array( 'immobile-target-namespace-iw' );
2801 if ( !$nt->isMovable() ) {
2802 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2805 $oldid = $this->getArticleID();
2806 $newid = $nt->getArticleID();
2808 if ( strlen( $nt->getDBkey() ) < 1 ) {
2809 $errors[] = array('articleexists');
2811 if ( ( $this->getDBkey() == '' ) ||
2813 ( $nt->getDBkey() == '' ) ) {
2814 $errors[] = array('badarticleerror');
2817 // Image-specific checks
2818 if( $this->getNamespace() == NS_FILE
) {
2819 $file = wfLocalFile( $this );
2820 if( $file->exists() ) {
2821 if( $nt->getNamespace() != NS_FILE
) {
2822 $errors[] = array('imagenocrossnamespace');
2824 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2825 $errors[] = array('imageinvalidfilename');
2827 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2828 $errors[] = array('imagetypemismatch');
2831 $destfile = wfLocalFile( $nt );
2832 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2833 $errors[] = array( 'file-exists-sharedrepo' );
2839 $errors = wfMergeErrorArrays( $errors,
2840 $this->getUserPermissionsErrors('move', $wgUser),
2841 $this->getUserPermissionsErrors('edit', $wgUser),
2842 $nt->getUserPermissionsErrors('move-target', $wgUser),
2843 $nt->getUserPermissionsErrors('edit', $wgUser) );
2846 $match = EditPage
::matchSummarySpamRegex( $reason );
2847 if( $match !== false ) {
2848 // This is kind of lame, won't display nice
2849 $errors[] = array('spamprotectiontext');
2853 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2854 $errors[] = array('hookaborted', $err);
2857 # The move is allowed only if (1) the target doesn't exist, or
2858 # (2) the target is a redirect to the source, and has no history
2859 # (so we can undo bad moves right after they're done).
2861 if ( 0 != $newid ) { # Target exists; check for validity
2862 if ( ! $this->isValidMoveTarget( $nt ) ) {
2863 $errors[] = array('articleexists');
2866 $tp = $nt->getTitleProtection();
2867 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2868 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2869 $errors[] = array('cantmove-titleprotected');
2878 * Move a title to a new location
2880 * @param $nt \type{Title} the new title
2881 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2883 * @param $reason \type{\string} The reason for the move
2884 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2885 * Ignored if the user doesn't have the suppressredirect right.
2886 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2888 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2889 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2890 if( is_array( $err ) ) {
2894 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2895 $dbw = wfGetDB( DB_MASTER
);
2896 if( $this->getNamespace() == NS_FILE
) {
2897 $file = wfLocalFile( $this );
2898 if( $file->exists() ) {
2899 $status = $file->move( $nt );
2900 if( !$status->isOk() ) {
2901 return $status->getErrorsArray();
2906 $pageid = $this->getArticleID();
2907 $protected = $this->isProtected();
2908 if( $nt->exists() ) {
2909 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2910 $pageCountChange = ($createRedirect ?
0 : -1);
2911 } else { # Target didn't exist, do normal move.
2912 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2913 $pageCountChange = ($createRedirect ?
1 : 0);
2916 if( is_array( $err ) ) {
2919 $redirid = $this->getArticleID();
2921 // Category memberships include a sort key which may be customized.
2922 // If it's left as the default (the page title), we need to update
2923 // the sort key to match the new title.
2925 // Be careful to avoid resetting cl_timestamp, which may disturb
2926 // time-based lists on some sites.
2928 // Warning -- if the sort key is *explicitly* set to the old title,
2929 // we can't actually distinguish it from a default here, and it'll
2930 // be set to the new title even though it really shouldn't.
2931 // It'll get corrected on the next edit, but resetting cl_timestamp.
2932 $dbw->update( 'categorylinks',
2934 'cl_sortkey' => $nt->getPrefixedText(),
2935 'cl_timestamp=cl_timestamp' ),
2937 'cl_from' => $pageid,
2938 'cl_sortkey' => $this->getPrefixedText() ),
2942 # Protect the redirect title as the title used to be...
2943 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2945 'pr_page' => $redirid,
2946 'pr_type' => 'pr_type',
2947 'pr_level' => 'pr_level',
2948 'pr_cascade' => 'pr_cascade',
2949 'pr_user' => 'pr_user',
2950 'pr_expiry' => 'pr_expiry'
2952 array( 'pr_page' => $pageid ),
2956 # Update the protection log
2957 $log = new LogPage( 'protect' );
2958 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2959 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2960 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2964 $oldnamespace = $this->getNamespace() & ~
1;
2965 $newnamespace = $nt->getNamespace() & ~
1;
2966 $oldtitle = $this->getDBkey();
2967 $newtitle = $nt->getDBkey();
2969 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2970 WatchedItem
::duplicateEntries( $this, $nt );
2973 # Update search engine
2974 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2976 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2980 if( $this->isContentPage() && !$nt->isContentPage() ) {
2981 # No longer a content page
2982 # Not viewed, edited, removing
2983 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2984 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2985 # Now a content page
2986 # Not viewed, edited, adding
2987 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2988 } elseif( $pageCountChange ) {
2990 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2997 # Update message cache for interface messages
2998 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2999 global $wgMessageCache;
3001 # @bug 17860: old article can be deleted, if this the case,
3002 # delete it from message cache
3003 if ( $this->getArticleID() === 0 ) {
3004 $wgMessageCache->replace( $this->getDBkey(), false );
3006 $oldarticle = new Article( $this );
3007 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3010 $newarticle = new Article( $nt );
3011 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3015 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3020 * Move page to a title which is at present a redirect to the
3023 * @param $nt \type{Title} the page to move to, which should currently
3025 * @param $reason \type{\string} The reason for the move
3026 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3027 * Ignored if the user doesn't have the suppressredirect right
3029 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3030 global $wgUseSquid, $wgUser, $wgContLang;
3032 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3035 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3037 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3038 $comment = $wgContLang->truncate( $comment, 250 );
3040 $now = wfTimestampNow();
3041 $newid = $nt->getArticleID();
3042 $oldid = $this->getArticleID();
3043 $latest = $this->getLatestRevID();
3045 $dbw = wfGetDB( DB_MASTER
);
3047 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3048 $newns = $nt->getNamespace();
3049 $newdbk = $nt->getDBkey();
3051 # Delete the old redirect. We don't save it to history since
3052 # by definition if we've got here it's rather uninteresting.
3053 # We have to remove it so that the next step doesn't trigger
3054 # a conflict on the unique namespace+title index...
3055 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3056 if ( !$dbw->cascadingDeletes() ) {
3057 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3058 global $wgUseTrackbacks;
3059 if ($wgUseTrackbacks)
3060 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3061 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3062 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3063 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3064 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3065 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3066 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3067 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3069 // If the redirect was recently created, it may have an entry in recentchanges still
3070 $dbw->delete( 'recentchanges',
3071 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3075 # Save a null revision in the page's history notifying of the move
3076 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3077 $nullRevId = $nullRevision->insertOn( $dbw );
3079 $article = new Article( $this );
3080 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3082 # Change the name of the target page:
3083 $dbw->update( 'page',
3085 'page_touched' => $dbw->timestamp($now),
3086 'page_namespace' => $nt->getNamespace(),
3087 'page_title' => $nt->getDBkey(),
3088 'page_latest' => $nullRevId,
3090 /* WHERE */ array( 'page_id' => $oldid ),
3093 $nt->resetArticleID( $oldid );
3095 # Recreate the redirect, this time in the other direction.
3096 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3097 $mwRedir = MagicWord
::get( 'redirect' );
3098 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3099 $redirectArticle = new Article( $this );
3100 $newid = $redirectArticle->insertOn( $dbw );
3101 $redirectRevision = new Revision( array(
3103 'comment' => $comment,
3104 'text' => $redirectText ) );
3105 $redirectRevision->insertOn( $dbw );
3106 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3108 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3110 # Now, we record the link from the redirect to the new title.
3111 # It should have no other outgoing links...
3112 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3113 $dbw->insert( 'pagelinks',
3115 'pl_from' => $newid,
3116 'pl_namespace' => $nt->getNamespace(),
3117 'pl_title' => $nt->getDBkey() ),
3119 $redirectSuppressed = false;
3121 $this->resetArticleID( 0 );
3122 $redirectSuppressed = true;
3126 $log = new LogPage( 'move' );
3127 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3130 if ( $wgUseSquid ) {
3131 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3132 $u = new SquidUpdate( $urls );
3139 * Move page to non-existing title.
3141 * @param $nt \type{Title} the new Title
3142 * @param $reason \type{\string} The reason for the move
3143 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3144 * Ignored if the user doesn't have the suppressredirect right
3146 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3147 global $wgUseSquid, $wgUser, $wgContLang;
3149 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3151 $comment .= wfMsgExt( 'colon-separator',
3152 array( 'escapenoentities', 'content' ) );
3153 $comment .= $reason;
3155 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3156 $comment = $wgContLang->truncate( $comment, 250 );
3158 $newid = $nt->getArticleID();
3159 $oldid = $this->getArticleID();
3160 $latest = $this->getLatestRevId();
3162 $dbw = wfGetDB( DB_MASTER
);
3163 $now = $dbw->timestamp();
3165 # Save a null revision in the page's history notifying of the move
3166 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3167 if ( !is_object( $nullRevision ) ) {
3168 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3170 $nullRevId = $nullRevision->insertOn( $dbw );
3172 $article = new Article( $this );
3173 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3176 $dbw->update( 'page',
3178 'page_touched' => $now,
3179 'page_namespace' => $nt->getNamespace(),
3180 'page_title' => $nt->getDBkey(),
3181 'page_latest' => $nullRevId,
3183 /* WHERE */ array( 'page_id' => $oldid ),
3186 $nt->resetArticleID( $oldid );
3188 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3190 $mwRedir = MagicWord
::get( 'redirect' );
3191 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3192 $redirectArticle = new Article( $this );
3193 $newid = $redirectArticle->insertOn( $dbw );
3194 $redirectRevision = new Revision( array(
3196 'comment' => $comment,
3197 'text' => $redirectText ) );
3198 $redirectRevision->insertOn( $dbw );
3199 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3201 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3203 # Record the just-created redirect's linking to the page
3204 $dbw->insert( 'pagelinks',
3206 'pl_from' => $newid,
3207 'pl_namespace' => $nt->getNamespace(),
3208 'pl_title' => $nt->getDBkey() ),
3210 $redirectSuppressed = false;
3212 $this->resetArticleID( 0 );
3213 $redirectSuppressed = true;
3217 $log = new LogPage( 'move' );
3218 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3220 # Purge caches as per article creation
3221 Article
::onArticleCreate( $nt );
3223 # Purge old title from squid
3224 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3225 $this->purgeSquid();
3230 * Move this page's subpages to be subpages of $nt
3232 * @param $nt Title Move target
3233 * @param $auth bool Whether $wgUser's permissions should be checked
3234 * @param $reason string The reason for the move
3235 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3236 * Ignored if the user doesn't have the 'suppressredirect' right
3237 * @return mixed array with old page titles as keys, and strings (new page titles) or
3238 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3240 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3241 global $wgMaximumMovedPages;
3242 // Check permissions
3243 if( !$this->userCan( 'move-subpages' ) )
3244 return array( 'cant-move-subpages' );
3245 // Do the source and target namespaces support subpages?
3246 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3247 return array( 'namespace-nosubpages',
3248 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3249 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3250 return array( 'namespace-nosubpages',
3251 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3253 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3256 foreach( $subpages as $oldSubpage ) {
3258 if( $count > $wgMaximumMovedPages ) {
3259 $retval[$oldSubpage->getPrefixedTitle()] =
3260 array( 'movepage-max-pages',
3261 $wgMaximumMovedPages );
3265 // We don't know whether this function was called before
3266 // or after moving the root page, so check both
3268 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3269 $oldSubpage->getArticleID() == $nt->getArticleId() )
3270 // When moving a page to a subpage of itself,
3271 // don't move it twice
3273 $newPageName = preg_replace(
3274 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3275 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3276 $oldSubpage->getDBkey() );
3277 if( $oldSubpage->isTalkPage() ) {
3278 $newNs = $nt->getTalkPage()->getNamespace();
3280 $newNs = $nt->getSubjectPage()->getNamespace();
3282 # Bug 14385: we need makeTitleSafe because the new page names may
3283 # be longer than 255 characters.
3284 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3286 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3287 if( $success === true ) {
3288 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3290 $retval[$oldSubpage->getPrefixedText()] = $success;
3297 * Checks if this page is just a one-rev redirect.
3298 * Adds lock, so don't use just for light purposes.
3300 * @return \type{\bool}
3302 public function isSingleRevRedirect() {
3303 $dbw = wfGetDB( DB_MASTER
);
3305 $row = $dbw->selectRow( 'page',
3306 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3309 array( 'FOR UPDATE' )
3311 # Cache some fields we may want
3312 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3313 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3314 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3315 if( !$this->mRedirect
) {
3318 # Does the article have a history?
3319 $row = $dbw->selectField( array( 'page', 'revision'),
3321 array( 'page_namespace' => $this->getNamespace(),
3322 'page_title' => $this->getDBkey(),
3324 'page_latest != rev_id'
3327 array( 'FOR UPDATE' )
3329 # Return true if there was no history
3330 return ($row === false);
3334 * Checks if $this can be moved to a given Title
3335 * - Selects for update, so don't call it unless you mean business
3337 * @param $nt \type{Title} the new title to check
3338 * @return \type{\bool} TRUE or FALSE
3340 public function isValidMoveTarget( $nt ) {
3341 $dbw = wfGetDB( DB_MASTER
);
3342 # Is it an existsing file?
3343 if( $nt->getNamespace() == NS_FILE
) {
3344 $file = wfLocalFile( $nt );
3345 if( $file->exists() ) {
3346 wfDebug( __METHOD__
. ": file exists\n" );
3350 # Is it a redirect with no history?
3351 if( !$nt->isSingleRevRedirect() ) {
3352 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3355 # Get the article text
3356 $rev = Revision
::newFromTitle( $nt );
3357 $text = $rev->getText();
3358 # Does the redirect point to the source?
3359 # Or is it a broken self-redirect, usually caused by namespace collisions?
3361 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3362 $redirTitle = Title
::newFromText( $m[1] );
3363 if( !is_object( $redirTitle ) ||
3364 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3365 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3366 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3371 wfDebug( __METHOD__
. ": failsafe\n" );
3378 * Can this title be added to a user's watchlist?
3380 * @return \type{\bool} TRUE or FALSE
3382 public function isWatchable() {
3383 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3387 * Get categories to which this Title belongs and return an array of
3388 * categories' names.
3390 * @return \type{\array} array an array of parents in the form:
3391 * $parent => $currentarticle
3393 public function getParentCategories() {
3396 $titlekey = $this->getArticleId();
3397 $dbr = wfGetDB( DB_SLAVE
);
3398 $categorylinks = $dbr->tableName( 'categorylinks' );
3401 $sql = "SELECT * FROM $categorylinks"
3402 ." WHERE cl_from='$titlekey'"
3403 ." AND cl_from <> '0'"
3404 ." ORDER BY cl_sortkey";
3406 $res = $dbr->query( $sql );
3408 if( $dbr->numRows( $res ) > 0 ) {
3409 foreach( $res as $row )
3410 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3411 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3412 $dbr->freeResult( $res );
3420 * Get a tree of parent categories
3422 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3423 * @return \type{\array} Tree of parent categories
3425 public function getParentCategoryTree( $children = array() ) {
3427 $parents = $this->getParentCategories();
3430 foreach( $parents as $parent => $current ) {
3431 if ( array_key_exists( $parent, $children ) ) {
3432 # Circular reference
3433 $stack[$parent] = array();
3435 $nt = Title
::newFromText($parent);
3437 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3449 * Get an associative array for selecting this title from
3452 * @return \type{\array} Selection array
3454 public function pageCond() {
3455 if( $this->mArticleID
> 0 ) {
3456 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3457 return array( 'page_id' => $this->mArticleID
);
3459 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3464 * Get the revision ID of the previous revision
3466 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3467 * @param $flags \type{\int} GAID_FOR_UPDATE
3468 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3470 public function getPreviousRevisionID( $revId, $flags=0 ) {
3471 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3472 return $db->selectField( 'revision', 'rev_id',
3474 'rev_page' => $this->getArticleId($flags),
3475 'rev_id < ' . intval( $revId )
3478 array( 'ORDER BY' => 'rev_id DESC' )
3483 * Get the revision ID of the next revision
3485 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3486 * @param $flags \type{\int} GAID_FOR_UPDATE
3487 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3489 public function getNextRevisionID( $revId, $flags=0 ) {
3490 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3491 return $db->selectField( 'revision', 'rev_id',
3493 'rev_page' => $this->getArticleId($flags),
3494 'rev_id > ' . intval( $revId )
3497 array( 'ORDER BY' => 'rev_id' )
3502 * Get the first revision of the page
3504 * @param $flags \type{\int} GAID_FOR_UPDATE
3505 * @return Revision (or NULL if page doesn't exist)
3507 public function getFirstRevision( $flags=0 ) {
3508 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3509 $pageId = $this->getArticleId($flags);
3510 if( !$pageId ) return null;
3511 $row = $db->selectRow( 'revision', '*',
3512 array( 'rev_page' => $pageId ),
3514 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3519 return new Revision( $row );
3524 * Check if this is a new page
3528 public function isNewPage() {
3529 $dbr = wfGetDB( DB_SLAVE
);
3530 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3534 * Get the oldest revision timestamp of this page
3536 * @return String: MW timestamp
3538 public function getEarliestRevTime() {
3539 $dbr = wfGetDB( DB_SLAVE
);
3540 if( $this->exists() ) {
3541 $min = $dbr->selectField( 'revision',
3542 'MIN(rev_timestamp)',
3543 array( 'rev_page' => $this->getArticleId() ),
3545 return wfTimestampOrNull( TS_MW
, $min );
3551 * Get the number of revisions between the given revision IDs.
3552 * Used for diffs and other things that really need it.
3554 * @param $old \type{\int} Revision ID.
3555 * @param $new \type{\int} Revision ID.
3556 * @return \type{\int} Number of revisions between these IDs.
3558 public function countRevisionsBetween( $old, $new ) {
3559 $dbr = wfGetDB( DB_SLAVE
);
3560 return (int)$dbr->selectField( 'revision', 'count(*)',
3561 'rev_page = ' . intval( $this->getArticleId() ) .
3562 ' AND rev_id > ' . intval( $old ) .
3563 ' AND rev_id < ' . intval( $new ),
3569 * Compare with another title.
3571 * @param $title \type{Title}
3572 * @return \type{\bool} TRUE or FALSE
3574 public function equals( Title
$title ) {
3575 // Note: === is necessary for proper matching of number-like titles.
3576 return $this->getInterwiki() === $title->getInterwiki()
3577 && $this->getNamespace() == $title->getNamespace()
3578 && $this->getDBkey() === $title->getDBkey();
3582 * Callback for usort() to do title sorts by (namespace, title)
3584 * @return Integer: result of string comparison, or namespace comparison
3586 public static function compare( $a, $b ) {
3587 if( $a->getNamespace() == $b->getNamespace() ) {
3588 return strcmp( $a->getText(), $b->getText() );
3590 return $a->getNamespace() - $b->getNamespace();
3595 * Return a string representation of this title
3597 * @return \type{\string} String representation of this title
3599 public function __toString() {
3600 return $this->getPrefixedText();
3604 * Check if page exists. For historical reasons, this function simply
3605 * checks for the existence of the title in the page table, and will
3606 * thus return false for interwiki links, special pages and the like.
3607 * If you want to know if a title can be meaningfully viewed, you should
3608 * probably call the isKnown() method instead.
3610 * @return \type{\bool}
3612 public function exists() {
3613 return $this->getArticleId() != 0;
3617 * Should links to this title be shown as potentially viewable (i.e. as
3618 * "bluelinks"), even if there's no record by this title in the page
3621 * This function is semi-deprecated for public use, as well as somewhat
3622 * misleadingly named. You probably just want to call isKnown(), which
3623 * calls this function internally.
3625 * (ISSUE: Most of these checks are cheap, but the file existence check
3626 * can potentially be quite expensive. Including it here fixes a lot of
3627 * existing code, but we might want to add an optional parameter to skip
3628 * it and any other expensive checks.)
3630 * @return \type{\bool}
3632 public function isAlwaysKnown() {
3633 if( $this->mInterwiki
!= '' ) {
3634 return true; // any interwiki link might be viewable, for all we know
3636 switch( $this->mNamespace
) {
3639 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3641 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3643 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3645 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3646 // the full l10n of that language to be loaded. That takes much memory and
3647 // isn't needed. So we strip the language part away.
3648 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3649 return (bool)wfMsgWeirdKey( $basename ); // known system message
3656 * Does this title refer to a page that can (or might) be meaningfully
3657 * viewed? In particular, this function may be used to determine if
3658 * links to the title should be rendered as "bluelinks" (as opposed to
3659 * "redlinks" to non-existent pages).
3661 * @return \type{\bool}
3663 public function isKnown() {
3664 return $this->exists() ||
$this->isAlwaysKnown();
3668 * Does this page have source text?
3672 public function hasSourceText() {
3673 if ( $this->exists() )
3676 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3677 // If the page doesn't exist but is a known system message, default
3678 // message content will be displayed, same for language subpages
3679 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3680 // causes the full l10n of that language to be loaded. That takes much
3681 // memory and isn't needed. So we strip the language part away.
3682 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3683 return (bool)wfMsgWeirdKey( $basename );
3690 * Is this in a namespace that allows actual pages?
3692 * @return \type{\bool}
3693 * @internal note -- uses hardcoded namespace index instead of constants
3695 public function canExist() {
3696 return $this->mNamespace
>=0 && $this->mNamespace
!= NS_MEDIA
;
3700 * Update page_touched timestamps and send squid purge messages for
3701 * pages linking to this title. May be sent to the job queue depending
3702 * on the number of links. Typically called on create and delete.
3704 public function touchLinks() {
3705 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3708 if ( $this->getNamespace() == NS_CATEGORY
) {
3709 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3715 * Get the last touched timestamp
3717 * @param $db DatabaseBase: optional db
3718 * @return \type{\string} Last touched timestamp
3720 public function getTouched( $db = null ) {
3721 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3722 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3727 * Get the timestamp when this page was updated since the user last saw it.
3730 * @return Mixed: string/null
3732 public function getNotificationTimestamp( $user = null ) {
3733 global $wgUser, $wgShowUpdatedMarker;
3734 // Assume current user if none given
3735 if( !$user ) $user = $wgUser;
3736 // Check cache first
3737 $uid = $user->getId();
3738 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3739 return $this->mNotificationTimestamp
[$uid];
3741 if( !$uid ||
!$wgShowUpdatedMarker ) {
3742 return $this->mNotificationTimestamp
[$uid] = false;
3744 // Don't cache too much!
3745 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3746 $this->mNotificationTimestamp
= array();
3748 $dbr = wfGetDB( DB_SLAVE
);
3749 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3750 'wl_notificationtimestamp',
3751 array( 'wl_namespace' => $this->getNamespace(),
3752 'wl_title' => $this->getDBkey(),
3753 'wl_user' => $user->getId()
3757 return $this->mNotificationTimestamp
[$uid];
3761 * Get the trackback URL for this page
3763 * @return \type{\string} Trackback URL
3765 public function trackbackURL() {
3766 global $wgScriptPath, $wgServer, $wgScriptExtension;
3768 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3769 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3773 * Get the trackback RDF for this page
3775 * @return \type{\string} Trackback RDF
3777 public function trackbackRDF() {
3778 $url = htmlspecialchars($this->getFullURL());
3779 $title = htmlspecialchars($this->getText());
3780 $tburl = $this->trackbackURL();
3782 // Autodiscovery RDF is placed in comments so HTML validator
3783 // won't barf. This is a rather icky workaround, but seems
3784 // frequently used by this kind of RDF thingy.
3786 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3788 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3789 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3790 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3793 dc:identifier=\"$url\"
3795 trackback:ping=\"$tburl\" />
3801 * Generate strings used for xml 'id' names in monobook tabs
3803 * @param $prepend string defaults to 'nstab-'
3804 * @return \type{\string} XML 'id' name
3806 public function getNamespaceKey( $prepend = 'nstab-' ) {
3808 // Gets the subject namespace if this title
3809 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3810 // Checks if cononical namespace name exists for namespace
3811 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3812 // Uses canonical namespace name
3813 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3815 // Uses text of namespace
3816 $namespaceKey = $this->getSubjectNsText();
3818 // Makes namespace key lowercase
3819 $namespaceKey = $wgContLang->lc( $namespaceKey );
3821 if ( $namespaceKey == '' ) {
3822 $namespaceKey = 'main';
3824 // Changes file to image for backwards compatibility
3825 if ( $namespaceKey == 'file' ) {
3826 $namespaceKey = 'image';
3828 return $prepend . $namespaceKey;
3832 * Returns true if this is a special page.
3836 public function isSpecialPage( ) {
3837 return $this->getNamespace() == NS_SPECIAL
;
3841 * Returns true if this title resolves to the named special page
3843 * @param $name \type{\string} The special page name
3846 public function isSpecial( $name ) {
3847 if ( $this->getNamespace() == NS_SPECIAL
) {
3848 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3849 if ( $name == $thisName ) {
3857 * If the Title refers to a special page alias which is not the local default,
3859 * @return \type{Title} A new Title which points to the local default.
3860 * Otherwise, returns $this.
3862 public function fixSpecialName() {
3863 if ( $this->getNamespace() == NS_SPECIAL
) {
3864 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3865 if ( $canonicalName ) {
3866 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3867 if ( $localName != $this->mDbkeyform
) {
3868 return Title
::makeTitle( NS_SPECIAL
, $localName );
3876 * Is this Title in a namespace which contains content?
3877 * In other words, is this a content page, for the purposes of calculating
3880 * @return \type{\bool}
3882 public function isContentPage() {
3883 return MWNamespace
::isContent( $this->getNamespace() );
3887 * Get all extant redirects to this Title
3889 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3890 * NULL to consider all namespaces
3891 * @return \type{\arrayof{Title}} Redirects to this title
3893 public function getRedirectsHere( $ns = null ) {
3896 $dbr = wfGetDB( DB_SLAVE
);
3898 'rd_namespace' => $this->getNamespace(),
3899 'rd_title' => $this->getDBkey(),
3902 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3904 $res = $dbr->select(
3905 array( 'redirect', 'page' ),
3906 array( 'page_namespace', 'page_title' ),
3912 foreach( $res as $row ) {
3913 $redirs[] = self
::newFromRow( $row );
3919 * Check if this Title is a valid redirect target
3921 * @return \type{\bool}
3923 public function isValidRedirectTarget() {
3924 global $wgInvalidRedirectTargets;
3926 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3927 if( $this->isSpecial( 'Userlogout' ) ) {
3931 foreach( $wgInvalidRedirectTargets as $target ) {
3932 if( $this->isSpecial( $target ) ) {
3941 * Get a backlink cache object
3943 * @return object BacklinkCache
3945 function getBacklinkCache() {
3946 if ( is_null( $this->mBacklinkCache
) ) {
3947 $this->mBacklinkCache
= new BacklinkCache( $this );
3949 return $this->mBacklinkCache
;
3953 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3958 public function canUseNoindex(){
3959 global $wgArticleRobotPolicies, $wgContentNamespaces,
3960 $wgExemptFromUserRobotsControl;
3962 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3963 ?
$wgContentNamespaces
3964 : $wgExemptFromUserRobotsControl;
3966 return !in_array( $this->mNamespace
, $bannedNamespaces );
3971 * Returns restriction types for the current Title
3973 * @return array applicable restriction types
3975 public function getRestrictionTypes() {
3976 global $wgRestrictionTypes;
3977 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3979 if ( $this->getNamespace() == NS_FILE
) {
3980 $types[] = 'upload';
3983 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );