8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
16 define ( 'GAID_FOR_UPDATE', 1 );
19 * Represents a title within MediaWiki.
20 * Optionally may contain an interwiki designation or namespace.
21 * @note This class can fetch various kinds of data from the database;
22 * however, it does so inefficiently.
24 * @internal documentation reviewed 15 Mar 2010
27 /** @name Static cache variables */
29 static private $titleCache=array();
30 static private $interwikiCache=array();
34 * Title::newFromText maintains a cache to avoid expensive re-normalization of
35 * commonly used titles. On a batch operation this can become a memory leak
36 * if not bounded. After hitting this many titles reset the cache.
38 const CACHE_MAX
= 1000;
42 * @name Private member variables
43 * Please use the accessor functions instead.
48 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; ///< URL-encoded form of the main part
50 var $mDbkeyform = ''; ///< Main part with underscores
51 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
54 var $mFragment; ///< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; ///< ID of most recent revision
57 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
61 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
62 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
63 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
64 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
65 # Don't change the following default, NS_MAIN is hardcoded in several
66 # places. See bug 696.
67 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
68 # Zero except in {{transclusion}} tags
69 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
70 var $mLength = -1; ///< The page length, 0 for special pages
71 var $mRedirect = null; ///< Is the article at this title a redirect?
72 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
73 var $mBacklinkCache = null; ///< Cache of links to this title
81 /* private */ function __construct() {}
84 * Create a new Title from a prefixed DB key
86 * @param $key \type{\string} The database key, which has underscores
87 * instead of spaces, possibly including namespace and
89 * @return \type{Title} the new object, or NULL on an error
91 public static function newFromDBkey( $key ) {
93 $t->mDbkeyform
= $key;
94 if( $t->secureAndSplit() )
101 * Create a new Title from text, such as what one would find in a link. De-
102 * codes any HTML entities in the text.
104 * @param $text string The link text; spaces, prefixes, and an
105 * initial ':' indicating the main namespace are accepted.
106 * @param $defaultNamespace int The namespace to use if none is speci-
107 * fied by a prefix. If you want to force a specific namespace even if
108 * $text might begin with a namespace prefix, use makeTitle() or
110 * @return Title The new object, or null on an error.
112 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
113 if( is_object( $text ) ) {
114 throw new MWException( 'Title::newFromText given an object' );
118 * Wiki pages often contain multiple links to the same page.
119 * Title normalization and parsing can become expensive on
120 * pages with many links, so we can save a little time by
123 * In theory these are value objects and won't get changed...
125 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
126 return Title
::$titleCache[$text];
130 * Convert things like é ā or 〗 into normalized(bug 14952) text
132 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
135 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace
= $defaultNamespace;
138 static $cachedcount = 0 ;
139 if( $t->secureAndSplit() ) {
140 if( $defaultNamespace == NS_MAIN
) {
141 if( $cachedcount >= self
::CACHE_MAX
) {
142 # Avoid memory leaks on mass operations...
143 Title
::$titleCache = array();
147 Title
::$titleCache[$text] =& $t;
157 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
159 * Example of wrong and broken code:
160 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
162 * Example of right code:
163 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
165 * Create a new Title from URL-encoded text. Ensures that
166 * the given title's length does not exceed the maximum.
168 * @param $url \type{\string} the title, as might be taken from a URL
169 * @return \type{Title} the new object, or NULL on an error
171 public static function newFromURL( $url ) {
172 global $wgLegalTitleChars;
175 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
176 # but some URLs used it as a space replacement and they still come
177 # from some external search tools.
178 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
179 $url = str_replace( '+', ' ', $url );
182 $t->mDbkeyform
= str_replace( ' ', '_', $url );
183 if( $t->secureAndSplit() ) {
191 * Create a new Title from an article ID
193 * @param $id \type{\int} the page_id corresponding to the Title to create
194 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
195 * @return \type{Title} the new object, or NULL on an error
197 public static function newFromID( $id, $flags = 0 ) {
198 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
199 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
200 if( $row !== false ) {
201 $title = Title
::newFromRow( $row );
209 * Make an array of titles from an array of IDs
211 * @param $ids \type{\arrayof{\int}} Array of IDs
212 * @return \type{\arrayof{Title}} Array of Titles
214 public static function newFromIDs( $ids ) {
215 if ( !count( $ids ) ) {
218 $dbr = wfGetDB( DB_SLAVE
);
219 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
220 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
223 foreach( $res as $row ) {
224 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
230 * Make a Title object from a DB row
232 * @param $row \type{Row} (needs at least page_title,page_namespace)
233 * @return \type{Title} corresponding Title
235 public static function newFromRow( $row ) {
236 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
238 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
239 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
240 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
241 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
247 * Create a new Title from a namespace index and a DB key.
248 * It's assumed that $ns and $title are *valid*, for instance when
249 * they came directly from the database or a special page name.
250 * For convenience, spaces are converted to underscores so that
251 * eg user_text fields can be used directly.
253 * @param $ns \type{\int} the namespace of the article
254 * @param $title \type{\string} the unprefixed database key form
255 * @param $fragment \type{\string} The link fragment (after the "#")
256 * @return \type{Title} the new object
258 public static function &makeTitle( $ns, $title, $fragment = '' ) {
261 $t->mFragment
= $fragment;
262 $t->mNamespace
= $ns = intval( $ns );
263 $t->mDbkeyform
= str_replace( ' ', '_', $title );
264 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
265 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
266 $t->mTextform
= str_replace( '_', ' ', $title );
271 * Create a new Title from a namespace index and a DB key.
272 * The parameters will be checked for validity, which is a bit slower
273 * than makeTitle() but safer for user-provided data.
275 * @param $ns \type{\int} the namespace of the article
276 * @param $title \type{\string} the database key form
277 * @param $fragment \type{\string} The link fragment (after the "#")
278 * @return \type{Title} the new object, or NULL on an error
280 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
282 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
283 if( $t->secureAndSplit() ) {
291 * Create a new Title for the Main Page
293 * @return \type{Title} the new object
295 public static function newMainPage() {
296 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
297 // Don't give fatal errors if the message is broken
299 $title = Title
::newFromText( 'Main Page' );
305 * Extract a redirect destination from a string and return the
306 * Title, or null if the text doesn't contain a valid redirect
307 * This will only return the very next target, useful for
308 * the redirect table and other checks that don't need full recursion
310 * @param $text \type{\string} Text with possible redirect
311 * @return \type{Title} The corresponding Title
313 public static function newFromRedirect( $text ) {
314 return self
::newFromRedirectInternal( $text );
318 * Extract a redirect destination from a string and return the
319 * Title, or null if the text doesn't contain a valid redirect
320 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
321 * in order to provide (hopefully) the Title of the final destination instead of another redirect
323 * @param $text \type{\string} Text with possible redirect
324 * @return \type{Title} The corresponding Title
326 public static function newFromRedirectRecurse( $text ) {
327 $titles = self
::newFromRedirectArray( $text );
328 return $titles ?
array_pop( $titles ) : null;
332 * Extract a redirect destination from a string and return an
333 * array of Titles, or null if the text doesn't contain a valid redirect
334 * The last element in the array is the final destination after all redirects
335 * have been resolved (up to $wgMaxRedirects times)
337 * @param $text \type{\string} Text with possible redirect
338 * @return \type{\array} Array of Titles, with the destination last
340 public static function newFromRedirectArray( $text ) {
341 global $wgMaxRedirects;
342 // are redirects disabled?
343 if( $wgMaxRedirects < 1 )
345 $title = self
::newFromRedirectInternal( $text );
346 if( is_null( $title ) )
348 // recursive check to follow double redirects
349 $recurse = $wgMaxRedirects;
350 $titles = array( $title );
351 while( --$recurse > 0 ) {
352 if( $title->isRedirect() ) {
353 $article = new Article( $title, 0 );
354 $newtitle = $article->getRedirectTarget();
358 // Redirects to some special pages are not permitted
359 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
360 // the new title passes the checks, so make that our current title so that further recursion can be checked
362 $titles[] = $newtitle;
371 * Really extract the redirect destination
372 * Do not call this function directly, use one of the newFromRedirect* functions above
374 * @param $text \type{\string} Text with possible redirect
375 * @return \type{Title} The corresponding Title
377 protected static function newFromRedirectInternal( $text ) {
378 $redir = MagicWord
::get( 'redirect' );
380 if( $redir->matchStartAndRemove( $text ) ) {
381 // Extract the first link and see if it's usable
382 // Ensure that it really does come directly after #REDIRECT
383 // Some older redirects included a colon, so don't freak about that!
385 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
386 // Strip preceding colon used to "escape" categories, etc.
387 // and URL-decode links
388 if( strpos( $m[1], '%' ) !== false ) {
389 // Match behavior of inline link parsing here;
390 // don't interpret + as " " most of the time!
391 // It might be safe to just use rawurldecode instead, though.
392 $m[1] = urldecode( ltrim( $m[1], ':' ) );
394 $title = Title
::newFromText( $m[1] );
395 // If the title is a redirect to bad special pages or is invalid, return null
396 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
405 #----------------------------------------------------------------------------
407 #----------------------------------------------------------------------------
410 * Get the prefixed DB key associated with an ID
412 * @param $id \type{\int} the page_id of the article
413 * @return \type{Title} an object representing the article, or NULL
414 * if no such article was found
416 public static function nameOf( $id ) {
417 $dbr = wfGetDB( DB_SLAVE
);
419 $s = $dbr->selectRow( 'page',
420 array( 'page_namespace','page_title' ),
421 array( 'page_id' => $id ),
423 if ( $s === false ) { return null; }
425 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
430 * Get a regex character class describing the legal characters in a link
432 * @return \type{\string} the list of characters, not delimited
434 public static function legalChars() {
435 global $wgLegalTitleChars;
436 return $wgLegalTitleChars;
440 * Get a string representation of a title suitable for
441 * including in a search index
443 * @param $ns \type{\int} a namespace index
444 * @param $title \type{\string} text-form main part
445 * @return \type{\string} a stripped-down title string ready for the
448 public static function indexTitle( $ns, $title ) {
451 $lc = SearchEngine
::legalSearchChars() . '&#;';
452 $t = $wgContLang->normalizeForSearch( $title );
453 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
454 $t = $wgContLang->lc( $t );
457 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
458 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
460 $t = preg_replace( "/\\s+/", ' ', $t );
462 if ( $ns == NS_FILE
) {
463 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
469 * Make a prefixed DB key from a DB key and a namespace index
471 * @param $ns \type{\int} numerical representation of the namespace
472 * @param $title \type{\string} the DB key form the title
473 * @param $fragment \type{\string} The link fragment (after the "#")
474 * @return \type{\string} the prefixed form of the title
476 public static function makeName( $ns, $title, $fragment = '' ) {
479 $namespace = $wgContLang->getNsText( $ns );
480 $name = $namespace == '' ?
$title : "$namespace:$title";
481 if ( strval( $fragment ) != '' ) {
482 $name .= '#' . $fragment;
488 * Determine whether the object refers to a page within
491 * @return \type{\bool} TRUE if this is an in-project interwiki link
492 * or a wikilink, FALSE otherwise
494 public function isLocal() {
495 if ( $this->mInterwiki
!= '' ) {
496 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
503 * Determine whether the object refers to a page within
504 * this project and is transcludable.
506 * @return \type{\bool} TRUE if this is transcludable
508 public function isTrans() {
509 if ($this->mInterwiki
== '')
512 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
516 * Escape a text fragment, say from a link, for a URL
518 * @param $fragment string containing a URL or link fragment (after the "#")
519 * @return String: escaped string
521 static function escapeFragmentForURL( $fragment ) {
522 # Note that we don't urlencode the fragment. urlencoded Unicode
523 # fragments appear not to work in IE (at least up to 7) or in at least
524 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
525 # to care if they aren't encoded.
526 return Sanitizer
::escapeId( $fragment, 'noninitial' );
529 #----------------------------------------------------------------------------
531 #----------------------------------------------------------------------------
533 /** Simple accessors */
535 * Get the text form (spaces not underscores) of the main part
537 * @return \type{\string} Main part of the title
539 public function getText() { return $this->mTextform
; }
542 * Get the URL-encoded form of the main part
544 * @return \type{\string} Main part of the title, URL-encoded
546 public function getPartialURL() { return $this->mUrlform
; }
549 * Get the main part with underscores
551 * @return \type{\string} Main part of the title, with underscores
553 public function getDBkey() { return $this->mDbkeyform
; }
556 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
558 * @return \type{\int} Namespace index
560 public function getNamespace() { return $this->mNamespace
; }
563 * Get the namespace text
565 * @return \type{\string} Namespace text
567 public function getNsText() {
570 if ( $this->mInterwiki
!= '' ) {
571 // This probably shouldn't even happen. ohh man, oh yuck.
572 // But for interwiki transclusion it sometimes does.
573 // Shit. Shit shit shit.
575 // Use the canonical namespaces if possible to try to
576 // resolve a foreign namespace.
577 if( MWNamespace
::exists( $this->mNamespace
) ) {
578 return MWNamespace
::getCanonicalName( $this->mNamespace
);
581 return $wgContLang->getNsText( $this->mNamespace
);
585 * Get the DB key with the initial letter case as specified by the user
587 * @return \type{\string} DB key
589 function getUserCaseDBKey() {
590 return $this->mUserCaseDBKey
;
594 * Get the namespace text of the subject (rather than talk) page
596 * @return \type{\string} Namespace text
598 public function getSubjectNsText() {
600 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
604 * Get the namespace text of the talk page
606 * @return \type{\string} Namespace text
608 public function getTalkNsText() {
610 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
614 * Could this title have a corresponding talk page?
616 * @return \type{\bool} TRUE or FALSE
618 public function canTalk() {
619 return( MWNamespace
::canTalk( $this->mNamespace
) );
623 * Get the interwiki prefix (or null string)
625 * @return \type{\string} Interwiki prefix
627 public function getInterwiki() { return $this->mInterwiki
; }
630 * Get the Title fragment (i.e.\ the bit after the #) in text form
632 * @return \type{\string} Title fragment
634 public function getFragment() { return $this->mFragment
; }
637 * Get the fragment in URL form, including the "#" character if there is one
638 * @return \type{\string} Fragment in URL form
640 public function getFragmentForURL() {
641 if ( $this->mFragment
== '' ) {
644 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
649 * Get the default namespace index, for when there is no namespace
651 * @return \type{\int} Default namespace index
653 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
656 * Get title for search index
658 * @return \type{\string} a stripped-down title string ready for the
661 public function getIndexTitle() {
662 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
666 * Get the prefixed database key form
668 * @return \type{\string} the prefixed title, with underscores and
669 * any interwiki and namespace prefixes
671 public function getPrefixedDBkey() {
672 $s = $this->prefix( $this->mDbkeyform
);
673 $s = str_replace( ' ', '_', $s );
678 * Get the prefixed title with spaces.
679 * This is the form usually used for display
681 * @return \type{\string} the prefixed title, with spaces
683 public function getPrefixedText() {
684 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
685 $s = $this->prefix( $this->mTextform
);
686 $s = str_replace( '_', ' ', $s );
687 $this->mPrefixedText
= $s;
689 return $this->mPrefixedText
;
693 * Get the prefixed title with spaces, plus any fragment
694 * (part beginning with '#')
696 * @return \type{\string} the prefixed title, with spaces and
697 * the fragment, including '#'
699 public function getFullText() {
700 $text = $this->getPrefixedText();
701 if( $this->mFragment
!= '' ) {
702 $text .= '#' . $this->mFragment
;
708 * Get the base name, i.e. the leftmost parts before the /
710 * @return \type{\string} Base name
712 public function getBaseText() {
713 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
714 return $this->getText();
717 $parts = explode( '/', $this->getText() );
718 # Don't discard the real title if there's no subpage involved
719 if( count( $parts ) > 1 )
720 unset( $parts[ count( $parts ) - 1 ] );
721 return implode( '/', $parts );
725 * Get the lowest-level subpage name, i.e. the rightmost part after /
727 * @return \type{\string} Subpage name
729 public function getSubpageText() {
730 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
731 return( $this->mTextform
);
733 $parts = explode( '/', $this->mTextform
);
734 return( $parts[ count( $parts ) - 1 ] );
738 * Get a URL-encoded form of the subpage text
740 * @return \type{\string} URL-encoded subpage name
742 public function getSubpageUrlForm() {
743 $text = $this->getSubpageText();
744 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
749 * Get a URL-encoded title (not an actual URL) including interwiki
751 * @return \type{\string} the URL-encoded form
753 public function getPrefixedURL() {
754 $s = $this->prefix( $this->mDbkeyform
);
755 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
760 * Get a real URL referring to this title, with interwiki link and
763 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
764 * links. Can be specified as an associative array as well, e.g.,
765 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
766 * @param $variant \type{\string} language variant of url (for sr, zh..)
767 * @return \type{\string} the URL
769 public function getFullURL( $query = '', $variant = false ) {
770 global $wgContLang, $wgServer, $wgRequest;
772 if( is_array( $query ) ) {
773 $query = wfArrayToCGI( $query );
776 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
778 $url = $this->getLocalURL( $query, $variant );
780 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
781 // Correct fix would be to move the prepending elsewhere.
782 if ($wgRequest->getVal('action') != 'render') {
783 $url = $wgServer . $url;
786 $baseUrl = $interwiki->getURL( );
788 $namespace = wfUrlencode( $this->getNsText() );
789 if ( $namespace != '' ) {
790 # Can this actually happen? Interwikis shouldn't be parsed.
791 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
794 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
795 $url = wfAppendQuery( $url, $query );
798 # Finally, add the fragment.
799 $url .= $this->getFragmentForURL();
801 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
806 * Get a URL with no fragment or server name. If this page is generated
807 * with action=render, $wgServer is prepended.
809 * @param $query Mixed: an optional query string; if not specified,
810 * $wgArticlePath will be used. Can be specified as an associative array
811 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
813 * @param $variant \type{\string} language variant of url (for sr, zh..)
814 * @return \type{\string} the URL
816 public function getLocalURL( $query = '', $variant = false ) {
817 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
818 global $wgVariantArticlePath, $wgContLang, $wgUser;
820 if( is_array( $query ) ) {
821 $query = wfArrayToCGI( $query );
824 // internal links should point to same variant as current page (only anonymous users)
825 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
826 $pref = $wgContLang->getPreferredVariant(false);
827 if($pref != $wgContLang->getCode())
829 } elseif ( $variant == $wgContLang->getCode() ) {
830 // Don't use $wgVariantArticlePath for the main code
834 if ( $this->isExternal() ) {
835 $url = $this->getFullURL();
837 // This is currently only used for edit section links in the
838 // context of interwiki transclusion. In theory we should
839 // append the query to the end of any existing query string,
840 // but interwiki transclusion is already broken in that case.
844 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
845 if ( $query == '' ) {
846 if( $variant != false && $wgContLang->hasVariants() ) {
847 if( $wgVariantArticlePath == false ) {
848 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
850 $variantArticlePath = $wgVariantArticlePath;
852 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
853 $url = str_replace( '$1', $dbkey, $url );
855 $url = str_replace( '$1', $dbkey, $wgArticlePath );
858 global $wgActionPaths;
861 if( !empty( $wgActionPaths ) &&
862 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
864 $action = urldecode( $matches[2] );
865 if( isset( $wgActionPaths[$action] ) ) {
866 $query = $matches[1];
867 if( isset( $matches[4] ) ) $query .= $matches[4];
868 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
870 $url = wfAppendQuery( $url, $query );
874 if ( $url === false ) {
875 if ( $query == '-' ) {
878 $url = "{$wgScript}?title={$dbkey}&{$query}";
882 // FIXME: this causes breakage in various places when we
883 // actually expected a local URL and end up with dupe prefixes.
884 if ($wgRequest->getVal('action') == 'render') {
885 $url = $wgServer . $url;
888 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
893 * Get a URL that's the simplest URL that will be valid to link, locally,
894 * to the current Title. It includes the fragment, but does not include
895 * the server unless action=render is used (or the link is external). If
896 * there's a fragment but the prefixed text is empty, we just return a link
899 * The result obviously should not be URL-escaped, but does need to be
900 * HTML-escaped if it's being output in HTML.
902 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
903 * query string. Keys and values will be escaped.
904 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
905 * for external links. Default is "false" (same variant as current page,
906 * for anonymous users).
907 * @return \type{\string} the URL
909 public function getLinkUrl( $query = array(), $variant = false ) {
910 wfProfileIn( __METHOD__
);
911 if( $this->isExternal() ) {
912 $ret = $this->getFullURL( $query );
913 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
914 $ret = $this->getFragmentForURL();
916 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
918 wfProfileOut( __METHOD__
);
923 * Get an HTML-escaped version of the URL form, suitable for
924 * using in a link, without a server name or fragment
926 * @param $query \type{\string} an optional query string
927 * @return \type{\string} the URL
929 public function escapeLocalURL( $query = '' ) {
930 return htmlspecialchars( $this->getLocalURL( $query ) );
934 * Get an HTML-escaped version of the URL form, suitable for
935 * using in a link, including the server name and fragment
937 * @param $query \type{\string} an optional query string
938 * @return \type{\string} the URL
940 public function escapeFullURL( $query = '' ) {
941 return htmlspecialchars( $this->getFullURL( $query ) );
945 * Get the URL form for an internal link.
946 * - Used in various Squid-related code, in case we have a different
947 * internal hostname for the server from the exposed one.
949 * @param $query \type{\string} an optional query string
950 * @param $variant \type{\string} language variant of url (for sr, zh..)
951 * @return \type{\string} the URL
953 public function getInternalURL( $query = '', $variant = false ) {
954 global $wgInternalServer;
955 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
956 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
961 * Get the edit URL for this Title
963 * @return \type{\string} the URL, or a null string if this is an
966 public function getEditURL() {
967 if ( $this->mInterwiki
!= '' ) { return ''; }
968 $s = $this->getLocalURL( 'action=edit' );
974 * Get the HTML-escaped displayable text form.
975 * Used for the title field in <a> tags.
977 * @return \type{\string} the text, including any prefixes
979 public function getEscapedText() {
980 return htmlspecialchars( $this->getPrefixedText() );
984 * Is this Title interwiki?
986 * @return \type{\bool}
988 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
991 * Is this page "semi-protected" - the *only* protection is autoconfirm?
993 * @param $action \type{\string} Action to check (default: edit)
994 * @return \type{\bool}
996 public function isSemiProtected( $action = 'edit' ) {
997 if( $this->exists() ) {
998 $restrictions = $this->getRestrictions( $action );
999 if( count( $restrictions ) > 0 ) {
1000 foreach( $restrictions as $restriction ) {
1001 if( strtolower( $restriction ) != 'autoconfirmed' )
1010 # If it doesn't exist, it can't be protected
1016 * Does the title correspond to a protected article?
1018 * @param $action \type{\string} the action the page is protected from,
1019 * by default checks all actions.
1020 * @return \type{\bool}
1022 public function isProtected( $action = '' ) {
1023 global $wgRestrictionLevels;
1025 $restrictionTypes = $this->getRestrictionTypes();
1027 # Special pages have inherent protection
1028 if( $this->getNamespace() == NS_SPECIAL
)
1031 # Check regular protection levels
1032 foreach( $restrictionTypes as $type ){
1033 if( $action == $type ||
$action == '' ) {
1034 $r = $this->getRestrictions( $type );
1035 foreach( $wgRestrictionLevels as $level ) {
1036 if( in_array( $level, $r ) && $level != '' ) {
1047 * Is this a conversion table for the LanguageConverter?
1049 * @return \type{\bool}
1051 public function isConversionTable() {
1052 if($this->getNamespace() == NS_MEDIAWIKI
1053 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1061 * Is $wgUser watching this page?
1063 * @return \type{\bool}
1065 public function userIsWatching() {
1068 if ( is_null( $this->mWatched
) ) {
1069 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1070 $this->mWatched
= false;
1072 $this->mWatched
= $wgUser->isWatched( $this );
1075 return $this->mWatched
;
1079 * Can $wgUser perform $action on this page?
1080 * This skips potentially expensive cascading permission checks
1081 * as well as avoids expensive error formatting
1083 * Suitable for use for nonessential UI controls in common cases, but
1084 * _not_ for functional access control.
1086 * May provide false positives, but should never provide a false negative.
1088 * @param $action \type{\string} action that permission needs to be checked for
1089 * @return \type{\bool}
1091 public function quickUserCan( $action ) {
1092 return $this->userCan( $action, false );
1096 * Determines if $wgUser is unable to edit this page because it has been protected
1097 * by $wgNamespaceProtection.
1099 * @return \type{\bool}
1101 public function isNamespaceProtected() {
1102 global $wgNamespaceProtection, $wgUser;
1103 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1104 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1105 if( $right != '' && !$wgUser->isAllowed( $right ) )
1113 * Can $wgUser perform $action on this page?
1115 * @param $action \type{\string} action that permission needs to be checked for
1116 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1117 * @return \type{\bool}
1119 public function userCan( $action, $doExpensiveQueries = true ) {
1121 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1125 * Can $user perform $action on this page?
1127 * FIXME: This *does not* check throttles (User::pingLimiter()).
1129 * @param $action \type{\string}action that permission needs to be checked for
1130 * @param $user \type{User} user to check
1131 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1132 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1133 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1135 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1136 if( !StubObject
::isRealObject( $user ) ) {
1137 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1139 $wgUser->_unstub( '', 5 );
1142 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1146 global $wgEmailConfirmToEdit;
1148 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1149 $errors[] = array( 'confirmedittext' );
1152 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1153 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1154 $block = $user->mBlock
;
1156 // This is from OutputPage::blockedPage
1157 // Copied at r23888 by werdna
1159 $id = $user->blockedBy();
1160 $reason = $user->blockedFor();
1161 if( $reason == '' ) {
1162 $reason = wfMsg( 'blockednoreason' );
1166 if ( is_numeric( $id ) ) {
1167 $name = User
::whoIs( $id );
1172 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1173 $blockid = $block->mId
;
1174 $blockExpiry = $user->mBlock
->mExpiry
;
1175 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1177 if ( $blockExpiry == 'infinity' ) {
1178 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1179 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1181 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1182 if ( strpos( $option, ':' ) == false )
1185 list ($show, $value) = explode( ":", $option );
1187 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1188 $blockExpiry = $show;
1193 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1196 $intended = $user->mBlock
->mAddress
;
1198 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1199 $blockid, $blockExpiry, $intended, $blockTimestamp );
1202 // Remove the errors being ignored.
1204 foreach( $errors as $index => $error ) {
1205 $error_key = is_array($error) ?
$error[0] : $error;
1207 if (in_array( $error_key, $ignoreErrors )) {
1208 unset($errors[$index]);
1216 * Can $user perform $action on this page? This is an internal function,
1217 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1218 * checks on wfReadOnly() and blocks)
1220 * @param $action \type{\string} action that permission needs to be checked for
1221 * @param $user \type{User} user to check
1222 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1223 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1224 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1226 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1227 wfProfileIn( __METHOD__
);
1231 // First stop is permissions checks, which fail most often, and which are easiest to test.
1232 if ( $action == 'move' ) {
1233 if( !$user->isAllowed( 'move-rootuserpages' )
1234 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1236 // Show user page-specific message only if the user can move other pages
1237 $errors[] = array( 'cant-move-user-page' );
1240 // Check if user is allowed to move files if it's a file
1241 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1242 $errors[] = array( 'movenotallowedfile' );
1245 if( !$user->isAllowed( 'move' ) ) {
1246 // User can't move anything
1247 global $wgGroupPermissions;
1248 $userCanMove = false;
1249 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1250 $userCanMove = $wgGroupPermissions['user']['move'];
1252 $autoconfirmedCanMove = false;
1253 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1254 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1256 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1257 // custom message if logged-in users without any special rights can move
1258 $errors[] = array ( 'movenologintext' );
1260 $errors[] = array ('movenotallowed');
1263 } elseif ( $action == 'create' ) {
1264 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1265 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1267 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1269 } elseif( $action == 'move-target' ) {
1270 if( !$user->isAllowed( 'move' ) ) {
1271 // User can't move anything
1272 $errors[] = array ('movenotallowed');
1273 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1274 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1276 // Show user page-specific message only if the user can move other pages
1277 $errors[] = array( 'cant-move-to-user-page' );
1279 } elseif( !$user->isAllowed( $action ) ) {
1282 // We avoid expensive display logic for quickUserCan's and such
1285 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1286 User
::getGroupsWithPermission( $action ) );
1293 $wgLang->commaList( $groups ),
1297 $return = array( "badaccess-group0" );
1299 $errors[] = $return;
1302 # Short-circuit point
1303 if( $short && count($errors) > 0 ) {
1304 wfProfileOut( __METHOD__
);
1308 // Use getUserPermissionsErrors instead
1309 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1310 wfProfileOut( __METHOD__
);
1311 return $result ?
array() : array( array( 'badaccess-group0' ) );
1313 // Check getUserPermissionsErrors hook
1314 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1315 if( is_array($result) && count($result) && !is_array($result[0]) )
1316 $errors[] = $result; # A single array representing an error
1317 else if( is_array($result) && is_array($result[0]) )
1318 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1319 else if( $result !== '' && is_string($result) )
1320 $errors[] = array($result); # A string representing a message-id
1321 else if( $result === false )
1322 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1324 # Short-circuit point
1325 if( $short && count($errors) > 0 ) {
1326 wfProfileOut( __METHOD__
);
1329 // Check getUserPermissionsErrorsExpensive hook
1330 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1331 if( is_array($result) && count($result) && !is_array($result[0]) )
1332 $errors[] = $result; # A single array representing an error
1333 else if( is_array($result) && is_array($result[0]) )
1334 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1335 else if( $result !== '' && is_string($result) )
1336 $errors[] = array($result); # A string representing a message-id
1337 else if( $result === false )
1338 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1340 # Short-circuit point
1341 if( $short && count($errors) > 0 ) {
1342 wfProfileOut( __METHOD__
);
1346 # Only 'createaccount' and 'execute' can be performed on
1347 # special pages, which don't actually exist in the DB.
1348 $specialOKActions = array( 'createaccount', 'execute' );
1349 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1350 $errors[] = array('ns-specialprotected');
1353 # Check $wgNamespaceProtection for restricted namespaces
1354 if( $this->isNamespaceProtected() ) {
1355 $ns = $this->getNamespace() == NS_MAIN ?
1356 wfMsg( 'nstab-main' ) : $this->getNsText();
1357 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1358 array('protectedinterface') : array( 'namespaceprotected', $ns );
1361 # Protect css/js subpages of user pages
1362 # XXX: this might be better using restrictions
1363 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1364 # and $this->userCanEditJsSubpage() from working
1365 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1366 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1367 && $action != 'patrol'
1368 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1370 $errors[] = array('customcssjsprotected');
1371 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1372 && $action != 'patrol'
1373 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1375 $errors[] = array('customcssjsprotected');
1378 # Check against page_restrictions table requirements on this
1379 # page. The user must possess all required rights for this action.
1380 foreach( $this->getRestrictions($action) as $right ) {
1381 // Backwards compatibility, rewrite sysop -> protect
1382 if( $right == 'sysop' ) {
1385 if( $right != '' && !$user->isAllowed( $right ) ) {
1386 // Users with 'editprotected' permission can edit protected pages
1387 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1388 // Users with 'editprotected' permission cannot edit protected pages
1389 // with cascading option turned on.
1390 if( $this->mCascadeRestriction
) {
1391 $errors[] = array( 'protectedpagetext', $right );
1394 $errors[] = array( 'protectedpagetext', $right );
1398 # Short-circuit point
1399 if( $short && count($errors) > 0 ) {
1400 wfProfileOut( __METHOD__
);
1404 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1405 # We /could/ use the protection level on the source page, but it's fairly ugly
1406 # as we have to establish a precedence hierarchy for pages included by multiple
1407 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1408 # as they could remove the protection anyway.
1409 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1410 # Cascading protection depends on more than this page...
1411 # Several cascading protected pages may include this page...
1412 # Check each cascading level
1413 # This is only for protection restrictions, not for all actions
1414 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1415 foreach( $restrictions[$action] as $right ) {
1416 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1417 if( $right != '' && !$user->isAllowed( $right ) ) {
1419 foreach( $cascadingSources as $page )
1420 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1421 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1426 # Short-circuit point
1427 if( $short && count($errors) > 0 ) {
1428 wfProfileOut( __METHOD__
);
1432 if( $action == 'protect' ) {
1433 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1434 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1438 if( $action == 'create' ) {
1439 $title_protection = $this->getTitleProtection();
1440 if( is_array($title_protection) ) {
1441 extract($title_protection); // is this extract() really needed?
1443 if( $pt_create_perm == 'sysop' ) {
1444 $pt_create_perm = 'protect'; // B/C
1446 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1447 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1450 } elseif( $action == 'move' ) {
1451 // Check for immobile pages
1452 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1453 // Specific message for this case
1454 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1455 } elseif( !$this->isMovable() ) {
1456 // Less specific message for rarer cases
1457 $errors[] = array( 'immobile-page' );
1459 } elseif( $action == 'move-target' ) {
1460 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1461 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1462 } elseif( !$this->isMovable() ) {
1463 $errors[] = array( 'immobile-target-page' );
1467 wfProfileOut( __METHOD__
);
1472 * Is this title subject to title protection?
1474 * @return \type{\mixed} An associative array representing any existent title
1475 * protection, or false if there's none.
1477 private function getTitleProtection() {
1478 // Can't protect pages in special namespaces
1479 if ( $this->getNamespace() < 0 ) {
1483 // Can't protect pages that exist.
1484 if ($this->exists()) {
1488 $dbr = wfGetDB( DB_SLAVE
);
1489 $res = $dbr->select( 'protected_titles', '*',
1490 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1493 if ($row = $dbr->fetchRow( $res )) {
1501 * Update the title protection status
1503 * @param $create_perm \type{\string} Permission required for creation
1504 * @param $reason \type{\string} Reason for protection
1505 * @param $expiry \type{\string} Expiry timestamp
1506 * @return boolean true
1508 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1509 global $wgUser,$wgContLang;
1511 if ($create_perm == implode(',',$this->getRestrictions('create'))
1512 && $expiry == $this->mRestrictionsExpiry
['create']) {
1517 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1519 $dbw = wfGetDB( DB_MASTER
);
1521 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1523 $expiry_description = '';
1524 if ( $encodedExpiry != 'infinity' ) {
1525 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1526 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1529 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1532 # Update protection table
1533 if ($create_perm != '' ) {
1534 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1536 'pt_namespace' => $namespace,
1537 'pt_title' => $title,
1538 'pt_create_perm' => $create_perm,
1539 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1540 'pt_expiry' => $encodedExpiry,
1541 'pt_user' => $wgUser->getId(),
1542 'pt_reason' => $reason,
1546 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1547 'pt_title' => $title ), __METHOD__
);
1549 # Update the protection log
1550 if( $dbw->affectedRows() ) {
1551 $log = new LogPage( 'protect' );
1553 if( $create_perm ) {
1554 $params = array("[create=$create_perm] $expiry_description",'');
1555 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1557 $log->addEntry( 'unprotect', $this, $reason );
1565 * Remove any title protection due to page existing
1567 public function deleteTitleProtection() {
1568 $dbw = wfGetDB( DB_MASTER
);
1570 $dbw->delete( 'protected_titles',
1571 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1576 * Would anybody with sufficient privileges be able to move this page?
1577 * Some pages just aren't movable.
1579 * @return \type{\bool} TRUE or FALSE
1581 public function isMovable() {
1582 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1586 * Can $wgUser read this page?
1588 * @return \type{\bool}
1589 * @todo fold these checks into userCan()
1591 public function userCanRead() {
1592 global $wgUser, $wgGroupPermissions;
1594 static $useShortcut = null;
1596 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1597 if( is_null( $useShortcut ) ) {
1598 global $wgRevokePermissions;
1599 $useShortcut = true;
1600 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1601 # Not a public wiki, so no shortcut
1602 $useShortcut = false;
1603 } elseif( !empty( $wgRevokePermissions ) ) {
1605 * Iterate through each group with permissions being revoked (key not included since we don't care
1606 * what the group name is), then check if the read permission is being revoked. If it is, then
1607 * we don't use the shortcut below since the user might not be able to read, even though anon
1608 * reading is allowed.
1610 foreach( $wgRevokePermissions as $perms ) {
1611 if( !empty( $perms['read'] ) ) {
1612 # We might be removing the read right from the user, so no shortcut
1613 $useShortcut = false;
1621 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1622 if ( $result !== null ) {
1626 # Shortcut for public wikis, allows skipping quite a bit of code
1630 if( $wgUser->isAllowed( 'read' ) ) {
1633 global $wgWhitelistRead;
1636 * Always grant access to the login page.
1637 * Even anons need to be able to log in.
1639 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1644 * Bail out if there isn't whitelist
1646 if( !is_array($wgWhitelistRead) ) {
1651 * Check for explicit whitelisting
1653 $name = $this->getPrefixedText();
1654 $dbName = $this->getPrefixedDBKey();
1655 // Check with and without underscores
1656 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1660 * Old settings might have the title prefixed with
1661 * a colon for main-namespace pages
1663 if( $this->getNamespace() == NS_MAIN
) {
1664 if( in_array( ':' . $name, $wgWhitelistRead ) )
1669 * If it's a special page, ditch the subpage bit
1672 if( $this->getNamespace() == NS_SPECIAL
) {
1673 $name = $this->getDBkey();
1674 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1675 if ( $name === false ) {
1676 # Invalid special page, but we show standard login required message
1680 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1681 if( in_array( $pure, $wgWhitelistRead, true ) )
1690 * Is this a talk page of some sort?
1692 * @return \type{\bool}
1694 public function isTalkPage() {
1695 return MWNamespace
::isTalk( $this->getNamespace() );
1699 * Is this a subpage?
1701 * @return \type{\bool}
1703 public function isSubpage() {
1704 return MWNamespace
::hasSubpages( $this->mNamespace
)
1705 ?
strpos( $this->getText(), '/' ) !== false
1710 * Does this have subpages? (Warning, usually requires an extra DB query.)
1712 * @return \type{\bool}
1714 public function hasSubpages() {
1715 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1720 # We dynamically add a member variable for the purpose of this method
1721 # alone to cache the result. There's no point in having it hanging
1722 # around uninitialized in every Title object; therefore we only add it
1723 # if needed and don't declare it statically.
1724 if( isset( $this->mHasSubpages
) ) {
1725 return $this->mHasSubpages
;
1728 $subpages = $this->getSubpages( 1 );
1729 if( $subpages instanceof TitleArray
)
1730 return $this->mHasSubpages
= (bool)$subpages->count();
1731 return $this->mHasSubpages
= false;
1735 * Get all subpages of this page.
1737 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1738 * @return mixed TitleArray, or empty array if this page's namespace
1739 * doesn't allow subpages
1741 public function getSubpages( $limit = -1 ) {
1742 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1745 $dbr = wfGetDB( DB_SLAVE
);
1746 $conds['page_namespace'] = $this->getNamespace();
1747 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1750 $options['LIMIT'] = $limit;
1751 return $this->mSubpages
= TitleArray
::newFromResult(
1752 $dbr->select( 'page',
1753 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1762 * Could this page contain custom CSS or JavaScript, based
1765 * @return \type{\bool}
1767 public function isCssOrJsPage() {
1768 return $this->mNamespace
== NS_MEDIAWIKI
1769 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1773 * Is this a .css or .js subpage of a user page?
1774 * @return \type{\bool}
1776 public function isCssJsSubpage() {
1777 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1781 * Is this a *valid* .css or .js subpage of a user page?
1782 * Check that the corresponding skin exists
1784 * @return \type{\bool}
1786 public function isValidCssJsSubpage() {
1787 if ( $this->isCssJsSubpage() ) {
1788 $name = $this->getSkinFromCssJsSubpage();
1789 if ( $name == 'common' ) return true;
1790 $skinNames = Skin
::getSkinNames();
1791 return array_key_exists( $name, $skinNames );
1798 * Trim down a .css or .js subpage title to get the corresponding skin name
1800 * @return string containing skin name from .css or .js subpage title
1802 public function getSkinFromCssJsSubpage() {
1803 $subpage = explode( '/', $this->mTextform
);
1804 $subpage = $subpage[ count( $subpage ) - 1 ];
1805 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1809 * Is this a .css subpage of a user page?
1811 * @return \type{\bool}
1813 public function isCssSubpage() {
1814 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1818 * Is this a .js subpage of a user page?
1820 * @return \type{\bool}
1822 public function isJsSubpage() {
1823 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1827 * Protect css subpages of user pages: can $wgUser edit
1830 * @return \type{\bool}
1831 * @todo XXX: this might be better using restrictions
1833 public function userCanEditCssSubpage() {
1835 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1836 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1839 * Protect js subpages of user pages: can $wgUser edit
1842 * @return \type{\bool}
1843 * @todo XXX: this might be better using restrictions
1845 public function userCanEditJsSubpage() {
1847 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1848 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1852 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1854 * @return \type{\bool} If the page is subject to cascading restrictions.
1856 public function isCascadeProtected() {
1857 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1858 return ( $sources > 0 );
1862 * Cascading protection: Get the source of any cascading restrictions on this page.
1864 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages
1865 * that the restrictions have come from.
1866 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1867 * objects of the pages from which cascading restrictions have come,
1868 * false for none, or true if such restrictions exist, but $get_pages was not set.
1869 * The restriction array is an array of each type, each of which contains a
1870 * array of unique groups.
1872 public function getCascadeProtectionSources( $get_pages = true ) {
1873 $pagerestrictions = array();
1875 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1876 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1877 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1878 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1881 wfProfileIn( __METHOD__
);
1883 $dbr = wfGetDB( DB_SLAVE
);
1885 if ( $this->getNamespace() == NS_FILE
) {
1886 $tables = array ('imagelinks', 'page_restrictions');
1887 $where_clauses = array(
1888 'il_to' => $this->getDBkey(),
1890 'pr_cascade' => 1 );
1892 $tables = array ('templatelinks', 'page_restrictions');
1893 $where_clauses = array(
1894 'tl_namespace' => $this->getNamespace(),
1895 'tl_title' => $this->getDBkey(),
1897 'pr_cascade' => 1 );
1901 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1902 $where_clauses[] = 'page_id=pr_page';
1905 $cols = array( 'pr_expiry' );
1908 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1910 $sources = $get_pages ?
array() : false;
1911 $now = wfTimestampNow();
1912 $purgeExpired = false;
1914 foreach( $res as $row ) {
1915 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1916 if( $expiry > $now ) {
1918 $page_id = $row->pr_page
;
1919 $page_ns = $row->page_namespace
;
1920 $page_title = $row->page_title
;
1921 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1922 # Add groups needed for each restriction type if its not already there
1923 # Make sure this restriction type still exists
1925 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1926 $pagerestrictions[$row->pr_type
] = array();
1929 if ( isset($pagerestrictions[$row->pr_type
]) &&
1930 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1931 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1937 // Trigger lazy purge of expired restrictions from the db
1938 $purgeExpired = true;
1941 if( $purgeExpired ) {
1942 Title
::purgeExpiredRestrictions();
1945 wfProfileOut( __METHOD__
);
1948 $this->mCascadeSources
= $sources;
1949 $this->mCascadingRestrictions
= $pagerestrictions;
1951 $this->mHasCascadingRestrictions
= $sources;
1953 return array( $sources, $pagerestrictions );
1957 * Returns cascading restrictions for the current article
1961 function areRestrictionsCascading() {
1962 if (!$this->mRestrictionsLoaded
) {
1963 $this->loadRestrictions();
1966 return $this->mCascadeRestriction
;
1970 * Loads a string into mRestrictions array
1972 * @param $res \type{Resource} restrictions as an SQL result.
1973 * @param $oldFashionedRestrictions string comma-separated list of page
1974 * restrictions from page table (pre 1.10)
1976 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1978 $dbr = wfGetDB( DB_SLAVE
);
1980 while( $row = $dbr->fetchObject( $res ) ) {
1984 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1988 * Compiles list of active page restrictions from both page table (pre 1.10)
1989 * and page_restrictions table
1991 * @param $rows array of db result objects
1992 * @param $oldFashionedRestrictions string comma-separated list of page
1993 * restrictions from page table (pre 1.10)
1995 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1996 $dbr = wfGetDB( DB_SLAVE
);
1998 $restrictionTypes = $this->getRestrictionTypes();
2000 foreach( $restrictionTypes as $type ){
2001 $this->mRestrictions
[$type] = array();
2002 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
2005 $this->mCascadeRestriction
= false;
2007 # Backwards-compatibility: also load the restrictions from the page record (old format).
2009 if ( $oldFashionedRestrictions === null ) {
2010 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2011 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2014 if ($oldFashionedRestrictions != '') {
2016 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2017 $temp = explode( '=', trim( $restrict ) );
2018 if(count($temp) == 1) {
2019 // old old format should be treated as edit/move restriction
2020 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2021 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2023 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2027 $this->mOldRestrictions
= true;
2031 if( count($rows) ) {
2032 # Current system - load second to make them override.
2033 $now = wfTimestampNow();
2034 $purgeExpired = false;
2036 foreach( $rows as $row ) {
2037 # Cycle through all the restrictions.
2039 // Don't take care of restrictions types that aren't allowed
2041 if( !in_array( $row->pr_type
, $restrictionTypes ) )
2044 // This code should be refactored, now that it's being used more generally,
2045 // But I don't really see any harm in leaving it in Block for now -werdna
2046 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2048 // Only apply the restrictions if they haven't expired!
2049 if ( !$expiry ||
$expiry > $now ) {
2050 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2051 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2053 $this->mCascadeRestriction |
= $row->pr_cascade
;
2055 // Trigger a lazy purge of expired restrictions
2056 $purgeExpired = true;
2060 if( $purgeExpired ) {
2061 Title
::purgeExpiredRestrictions();
2065 $this->mRestrictionsLoaded
= true;
2069 * Load restrictions from the page_restrictions table
2071 * @param $oldFashionedRestrictions string comma-separated list of page
2072 * restrictions from page table (pre 1.10)
2074 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2075 if( !$this->mRestrictionsLoaded
) {
2076 if ($this->exists()) {
2077 $dbr = wfGetDB( DB_SLAVE
);
2079 $res = $dbr->select( 'page_restrictions', '*',
2080 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2082 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2084 $title_protection = $this->getTitleProtection();
2086 if (is_array($title_protection)) {
2087 extract($title_protection);
2089 $now = wfTimestampNow();
2090 $expiry = Block
::decodeExpiry($pt_expiry);
2092 if (!$expiry ||
$expiry > $now) {
2093 // Apply the restrictions
2094 $this->mRestrictionsExpiry
['create'] = $expiry;
2095 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
2096 } else { // Get rid of the old restrictions
2097 Title
::purgeExpiredRestrictions();
2100 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
2102 $this->mRestrictionsLoaded
= true;
2108 * Purge expired restrictions from the page_restrictions table
2110 static function purgeExpiredRestrictions() {
2111 $dbw = wfGetDB( DB_MASTER
);
2112 $dbw->delete( 'page_restrictions',
2113 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2116 $dbw->delete( 'protected_titles',
2117 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2122 * Accessor/initialisation for mRestrictions
2124 * @param $action \type{\string} action that permission needs to be checked for
2125 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2127 public function getRestrictions( $action ) {
2128 if( !$this->mRestrictionsLoaded
) {
2129 $this->loadRestrictions();
2131 return isset( $this->mRestrictions
[$action] )
2132 ?
$this->mRestrictions
[$action]
2137 * Get the expiry time for the restriction against a given action
2139 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2140 * or not protected at all, or false if the action is not recognised.
2142 public function getRestrictionExpiry( $action ) {
2143 if( !$this->mRestrictionsLoaded
) {
2144 $this->loadRestrictions();
2146 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2150 * Is there a version of this page in the deletion archive?
2152 * @return \type{\int} the number of archived revisions
2154 public function isDeleted() {
2155 if( $this->getNamespace() < 0 ) {
2158 $dbr = wfGetDB( DB_SLAVE
);
2159 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2160 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2163 if( $this->getNamespace() == NS_FILE
) {
2164 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2165 array( 'fa_name' => $this->getDBkey() ),
2174 * Is there a version of this page in the deletion archive?
2178 public function isDeletedQuick() {
2179 if( $this->getNamespace() < 0 ) {
2182 $dbr = wfGetDB( DB_SLAVE
);
2183 $deleted = (bool)$dbr->selectField( 'archive', '1',
2184 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2187 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2188 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2189 array( 'fa_name' => $this->getDBkey() ),
2197 * Get the article ID for this Title from the link cache,
2198 * adding it if necessary
2200 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2202 * @return \type{\int} the ID
2204 public function getArticleID( $flags = 0 ) {
2205 if( $this->getNamespace() < 0 ) {
2206 return $this->mArticleID
= 0;
2208 $linkCache = LinkCache
::singleton();
2209 if( $flags & GAID_FOR_UPDATE
) {
2210 $oldUpdate = $linkCache->forUpdate( true );
2211 $linkCache->clearLink( $this );
2212 $this->mArticleID
= $linkCache->addLinkObj( $this );
2213 $linkCache->forUpdate( $oldUpdate );
2215 if( -1 == $this->mArticleID
) {
2216 $this->mArticleID
= $linkCache->addLinkObj( $this );
2219 return $this->mArticleID
;
2223 * Is this an article that is a redirect page?
2224 * Uses link cache, adding it if necessary
2226 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2227 * @return \type{\bool}
2229 public function isRedirect( $flags = 0 ) {
2230 if( !is_null($this->mRedirect
) )
2231 return $this->mRedirect
;
2232 # Calling getArticleID() loads the field from cache as needed
2233 if( !$this->getArticleID($flags) ) {
2234 return $this->mRedirect
= false;
2236 $linkCache = LinkCache
::singleton();
2237 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2239 return $this->mRedirect
;
2243 * What is the length of this page?
2244 * Uses link cache, adding it if necessary
2246 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2247 * @return \type{\bool}
2249 public function getLength( $flags = 0 ) {
2250 if( $this->mLength
!= -1 )
2251 return $this->mLength
;
2252 # Calling getArticleID() loads the field from cache as needed
2253 if( !$this->getArticleID($flags) ) {
2254 return $this->mLength
= 0;
2256 $linkCache = LinkCache
::singleton();
2257 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2259 return $this->mLength
;
2263 * What is the page_latest field for this page?
2265 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2266 * @return \type{\int} or false if the page doesn't exist
2268 public function getLatestRevID( $flags = 0 ) {
2269 if( $this->mLatestID
!== false )
2270 return $this->mLatestID
;
2272 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2273 $this->mLatestID
= (int)$db->selectField(
2274 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2275 return $this->mLatestID
;
2279 * This clears some fields in this object, and clears any associated
2280 * keys in the "bad links" section of the link cache.
2282 * - This is called from Article::insertNewArticle() to allow
2283 * loading of the new page_id. It's also called from
2284 * Article::doDeleteArticle()
2286 * @param $newid \type{\int} the new Article ID
2288 public function resetArticleID( $newid ) {
2289 $linkCache = LinkCache
::singleton();
2290 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2292 if ( $newid === false ) {
2293 $this->mArticleID
= -1;
2295 $this->mArticleID
= intval( $newid );
2297 $this->mRestrictionsLoaded
= false;
2298 $this->mRestrictions
= array();
2299 $this->mRedirect
= null;
2300 $this->mLength
= -1;
2301 $this->mLatestID
= false;
2305 * Updates page_touched for this page; called from LinksUpdate.php
2307 * @return \type{\bool} true if the update succeded
2309 public function invalidateCache() {
2310 if( wfReadOnly() ) {
2313 $dbw = wfGetDB( DB_MASTER
);
2314 $success = $dbw->update( 'page',
2315 array( 'page_touched' => $dbw->timestamp() ),
2319 HTMLFileCache
::clearFileCache( $this );
2324 * Prefix some arbitrary text with the namespace or interwiki prefix
2327 * @param $name \type{\string} the text
2328 * @return \type{\string} the prefixed text
2331 /* private */ function prefix( $name ) {
2333 if ( $this->mInterwiki
!= '' ) {
2334 $p = $this->mInterwiki
. ':';
2336 if ( 0 != $this->mNamespace
) {
2337 $p .= $this->getNsText() . ':';
2343 * Returns a simple regex that will match on characters and sequences invalid in titles.
2344 * Note that this doesn't pick up many things that could be wrong with titles, but that
2345 * replacing this regex with something valid will make many titles valid.
2347 * @return string regex string
2349 static function getTitleInvalidRegex() {
2350 static $rxTc = false;
2352 # Matching titles will be held as illegal.
2354 # Any character not allowed is forbidden...
2355 '[^' . Title
::legalChars() . ']' .
2356 # URL percent encoding sequences interfere with the ability
2357 # to round-trip titles -- you can't link to them consistently.
2358 '|%[0-9A-Fa-f]{2}' .
2359 # XML/HTML character references produce similar issues.
2360 '|&[A-Za-z0-9\x80-\xff]+;' .
2362 '|&#x[0-9A-Fa-f]+;' .
2370 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2372 * @param $text string containing title to capitalize
2373 * @param $ns int namespace index, defaults to NS_MAIN
2374 * @return String containing capitalized title
2376 public static function capitalize( $text, $ns = NS_MAIN
) {
2379 if ( MWNamespace
::isCapitalized( $ns ) )
2380 return $wgContLang->ucfirst( $text );
2386 * Secure and split - main initialisation function for this object
2388 * Assumes that mDbkeyform has been set, and is urldecoded
2389 * and uses underscores, but not otherwise munged. This function
2390 * removes illegal characters, splits off the interwiki and
2391 * namespace prefixes, sets the other forms, and canonicalizes
2394 * @return \type{\bool} true on success
2396 private function secureAndSplit() {
2397 global $wgContLang, $wgLocalInterwiki;
2400 $rxTc = self
::getTitleInvalidRegex();
2402 $this->mInterwiki
= $this->mFragment
= '';
2403 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2405 $dbkey = $this->mDbkeyform
;
2407 # Strip Unicode bidi override characters.
2408 # Sometimes they slip into cut-n-pasted page titles, where the
2409 # override chars get included in list displays.
2410 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2412 # Clean up whitespace
2413 # Note: use of the /u option on preg_replace here will cause
2414 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2415 # conveniently disabling them.
2417 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2418 $dbkey = trim( $dbkey, '_' );
2420 if ( $dbkey == '' ) {
2424 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2425 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2429 $this->mDbkeyform
= $dbkey;
2431 # Initial colon indicates main namespace rather than specified default
2432 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2433 if ( ':' == $dbkey{0} ) {
2434 $this->mNamespace
= NS_MAIN
;
2435 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2436 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2439 # Namespace or interwiki prefix
2441 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2444 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2446 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2447 # Ordinary namespace
2449 $this->mNamespace
= $ns;
2450 # For Talk:X pages, check if X has a "namespace" prefix
2451 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2452 if( $wgContLang->getNsIndex( $x[1] ) )
2453 return false; # Disallow Talk:File:x type titles...
2454 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2455 return false; # Disallow Talk:Interwiki:x type titles...
2457 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2459 # Can't make a local interwiki link to an interwiki link.
2460 # That's just crazy!
2466 $this->mInterwiki
= $wgContLang->lc( $p );
2468 # Redundant interwiki prefix to the local wiki
2469 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2470 if( $dbkey == '' ) {
2471 # Can't have an empty self-link
2474 $this->mInterwiki
= '';
2476 # Do another namespace split...
2480 # If there's an initial colon after the interwiki, that also
2481 # resets the default namespace
2482 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2483 $this->mNamespace
= NS_MAIN
;
2484 $dbkey = substr( $dbkey, 1 );
2487 # If there's no recognized interwiki or namespace,
2488 # then let the colon expression be part of the title.
2493 # We already know that some pages won't be in the database!
2495 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2496 $this->mArticleID
= 0;
2498 $fragment = strstr( $dbkey, '#' );
2499 if ( false !== $fragment ) {
2500 $this->setFragment( $fragment );
2501 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2502 # remove whitespace again: prevents "Foo_bar_#"
2503 # becoming "Foo_bar_"
2504 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2507 # Reject illegal characters.
2509 if( preg_match( $rxTc, $dbkey ) ) {
2514 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2515 * reachable due to the way web browsers deal with 'relative' URLs.
2516 * Also, they conflict with subpage syntax. Forbid them explicitly.
2518 if ( strpos( $dbkey, '.' ) !== false &&
2519 ( $dbkey === '.' ||
$dbkey === '..' ||
2520 strpos( $dbkey, './' ) === 0 ||
2521 strpos( $dbkey, '../' ) === 0 ||
2522 strpos( $dbkey, '/./' ) !== false ||
2523 strpos( $dbkey, '/../' ) !== false ||
2524 substr( $dbkey, -2 ) == '/.' ||
2525 substr( $dbkey, -3 ) == '/..' ) )
2531 * Magic tilde sequences? Nu-uh!
2533 if( strpos( $dbkey, '~~~' ) !== false ) {
2538 * Limit the size of titles to 255 bytes.
2539 * This is typically the size of the underlying database field.
2540 * We make an exception for special pages, which don't need to be stored
2541 * in the database, and may edge over 255 bytes due to subpage syntax
2542 * for long titles, e.g. [[Special:Block/Long name]]
2544 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2545 strlen( $dbkey ) > 512 )
2551 * Normally, all wiki links are forced to have
2552 * an initial capital letter so [[foo]] and [[Foo]]
2553 * point to the same place.
2555 * Don't force it for interwikis, since the other
2556 * site might be case-sensitive.
2558 $this->mUserCaseDBKey
= $dbkey;
2559 if( $this->mInterwiki
== '') {
2560 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2564 * Can't make a link to a namespace alone...
2565 * "empty" local links can only be self-links
2566 * with a fragment identifier.
2569 $this->mInterwiki
== '' &&
2570 $this->mNamespace
!= NS_MAIN
) {
2573 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2574 // IP names are not allowed for accounts, and can only be referring to
2575 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2576 // there are numerous ways to present the same IP. Having sp:contribs scan
2577 // them all is silly and having some show the edits and others not is
2578 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2579 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2580 IP
::sanitizeIP( $dbkey ) : $dbkey;
2581 // Any remaining initial :s are illegal.
2582 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2587 $this->mDbkeyform
= $dbkey;
2588 $this->mUrlform
= wfUrlencode( $dbkey );
2590 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2596 * Set the fragment for this title. Removes the first character from the
2597 * specified fragment before setting, so it assumes you're passing it with
2600 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2601 * Still in active use privately.
2603 * @param $fragment \type{\string} text
2605 public function setFragment( $fragment ) {
2606 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2610 * Get a Title object associated with the talk page of this article
2612 * @return \type{Title} the object for the talk page
2614 public function getTalkPage() {
2615 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2619 * Get a title object associated with the subject page of this
2622 * @return \type{Title} the object for the subject page
2624 public function getSubjectPage() {
2625 // Is this the same title?
2626 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2627 if( $this->getNamespace() == $subjectNS ) {
2630 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2634 * Get an array of Title objects linking to this Title
2635 * Also stores the IDs in the link cache.
2637 * WARNING: do not use this function on arbitrary user-supplied titles!
2638 * On heavily-used templates it will max out the memory.
2640 * @param $options Array: may be FOR UPDATE
2641 * @param $table String: table name
2642 * @param $prefix String: fields prefix
2643 * @return \type{\arrayof{Title}} the Title objects linking here
2645 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2646 $linkCache = LinkCache
::singleton();
2648 if ( count( $options ) > 0 ) {
2649 $db = wfGetDB( DB_MASTER
);
2651 $db = wfGetDB( DB_SLAVE
);
2654 $res = $db->select( array( 'page', $table ),
2655 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2657 "{$prefix}_from=page_id",
2658 "{$prefix}_namespace" => $this->getNamespace(),
2659 "{$prefix}_title" => $this->getDBkey() ),
2664 if ( $db->numRows( $res ) ) {
2665 foreach( $res as $row ) {
2666 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2667 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2668 $retVal[] = $titleObj;
2672 $db->freeResult( $res );
2677 * Get an array of Title objects using this Title as a template
2678 * Also stores the IDs in the link cache.
2680 * WARNING: do not use this function on arbitrary user-supplied titles!
2681 * On heavily-used templates it will max out the memory.
2683 * @param $options Array: may be FOR UPDATE
2684 * @return \type{\arrayof{Title}} the Title objects linking here
2686 public function getTemplateLinksTo( $options = array() ) {
2687 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2691 * Get an array of Title objects referring to non-existent articles linked from this page
2693 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2694 * @return \type{\arrayof{Title}} the Title objects
2696 public function getBrokenLinksFrom() {
2697 if ( $this->getArticleId() == 0 ) {
2698 # All links from article ID 0 are false positives
2702 $dbr = wfGetDB( DB_SLAVE
);
2703 $res = $dbr->select(
2704 array( 'page', 'pagelinks' ),
2705 array( 'pl_namespace', 'pl_title' ),
2707 'pl_from' => $this->getArticleId(),
2708 'page_namespace IS NULL'
2710 __METHOD__
, array(),
2714 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2720 foreach( $res as $row ) {
2721 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2728 * Get a list of URLs to purge from the Squid cache when this
2731 * @return \type{\arrayof{\string}} the URLs
2733 public function getSquidURLs() {
2737 $this->getInternalURL(),
2738 $this->getInternalURL( 'action=history' )
2741 // purge variant urls as well
2742 if($wgContLang->hasVariants()){
2743 $variants = $wgContLang->getVariants();
2744 foreach($variants as $vCode){
2745 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2746 $urls[] = $this->getInternalURL('',$vCode);
2754 * Purge all applicable Squid URLs
2756 public function purgeSquid() {
2758 if ( $wgUseSquid ) {
2759 $urls = $this->getSquidURLs();
2760 $u = new SquidUpdate( $urls );
2766 * Move this page without authentication
2768 * @param $nt \type{Title} the new page Title
2769 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2771 public function moveNoAuth( &$nt ) {
2772 return $this->moveTo( $nt, false );
2776 * Check whether a given move operation would be valid.
2777 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2779 * @param $nt \type{Title} the new title
2780 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2782 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2783 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2785 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2790 // Normally we'd add this to $errors, but we'll get
2791 // lots of syntax errors if $nt is not an object
2792 return array(array('badtitletext'));
2794 if( $this->equals( $nt ) ) {
2795 $errors[] = array('selfmove');
2797 if( !$this->isMovable() ) {
2798 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2800 if ( $nt->getInterwiki() != '' ) {
2801 $errors[] = array( 'immobile-target-namespace-iw' );
2803 if ( !$nt->isMovable() ) {
2804 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2807 $oldid = $this->getArticleID();
2808 $newid = $nt->getArticleID();
2810 if ( strlen( $nt->getDBkey() ) < 1 ) {
2811 $errors[] = array('articleexists');
2813 if ( ( $this->getDBkey() == '' ) ||
2815 ( $nt->getDBkey() == '' ) ) {
2816 $errors[] = array('badarticleerror');
2819 // Image-specific checks
2820 if( $this->getNamespace() == NS_FILE
) {
2821 $file = wfLocalFile( $this );
2822 if( $file->exists() ) {
2823 if( $nt->getNamespace() != NS_FILE
) {
2824 $errors[] = array('imagenocrossnamespace');
2826 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2827 $errors[] = array('imageinvalidfilename');
2829 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2830 $errors[] = array('imagetypemismatch');
2833 $destfile = wfLocalFile( $nt );
2834 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2835 $errors[] = array( 'file-exists-sharedrepo' );
2841 $errors = wfMergeErrorArrays( $errors,
2842 $this->getUserPermissionsErrors('move', $wgUser),
2843 $this->getUserPermissionsErrors('edit', $wgUser),
2844 $nt->getUserPermissionsErrors('move-target', $wgUser),
2845 $nt->getUserPermissionsErrors('edit', $wgUser) );
2848 $match = EditPage
::matchSummarySpamRegex( $reason );
2849 if( $match !== false ) {
2850 // This is kind of lame, won't display nice
2851 $errors[] = array('spamprotectiontext');
2855 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2856 $errors[] = array('hookaborted', $err);
2859 # The move is allowed only if (1) the target doesn't exist, or
2860 # (2) the target is a redirect to the source, and has no history
2861 # (so we can undo bad moves right after they're done).
2863 if ( 0 != $newid ) { # Target exists; check for validity
2864 if ( ! $this->isValidMoveTarget( $nt ) ) {
2865 $errors[] = array('articleexists');
2868 $tp = $nt->getTitleProtection();
2869 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2870 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2871 $errors[] = array('cantmove-titleprotected');
2880 * Move a title to a new location
2882 * @param $nt \type{Title} the new title
2883 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2885 * @param $reason \type{\string} The reason for the move
2886 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2887 * Ignored if the user doesn't have the suppressredirect right.
2888 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2890 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2891 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2892 if( is_array( $err ) ) {
2896 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2897 $dbw = wfGetDB( DB_MASTER
);
2898 if( $this->getNamespace() == NS_FILE
) {
2899 $file = wfLocalFile( $this );
2900 if( $file->exists() ) {
2901 $status = $file->move( $nt );
2902 if( !$status->isOk() ) {
2903 return $status->getErrorsArray();
2908 $pageid = $this->getArticleID();
2909 $protected = $this->isProtected();
2910 if( $nt->exists() ) {
2911 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2912 $pageCountChange = ($createRedirect ?
0 : -1);
2913 } else { # Target didn't exist, do normal move.
2914 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2915 $pageCountChange = ($createRedirect ?
1 : 0);
2918 if( is_array( $err ) ) {
2921 $redirid = $this->getArticleID();
2923 // Category memberships include a sort key which may be customized.
2924 // If it's left as the default (the page title), we need to update
2925 // the sort key to match the new title.
2927 // Be careful to avoid resetting cl_timestamp, which may disturb
2928 // time-based lists on some sites.
2930 // Warning -- if the sort key is *explicitly* set to the old title,
2931 // we can't actually distinguish it from a default here, and it'll
2932 // be set to the new title even though it really shouldn't.
2933 // It'll get corrected on the next edit, but resetting cl_timestamp.
2934 $dbw->update( 'categorylinks',
2936 'cl_sortkey' => $nt->getPrefixedText(),
2937 'cl_timestamp=cl_timestamp' ),
2939 'cl_from' => $pageid,
2940 'cl_sortkey' => $this->getPrefixedText() ),
2944 # Protect the redirect title as the title used to be...
2945 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2947 'pr_page' => $redirid,
2948 'pr_type' => 'pr_type',
2949 'pr_level' => 'pr_level',
2950 'pr_cascade' => 'pr_cascade',
2951 'pr_user' => 'pr_user',
2952 'pr_expiry' => 'pr_expiry'
2954 array( 'pr_page' => $pageid ),
2958 # Update the protection log
2959 $log = new LogPage( 'protect' );
2960 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2961 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2962 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2966 $oldnamespace = $this->getNamespace() & ~
1;
2967 $newnamespace = $nt->getNamespace() & ~
1;
2968 $oldtitle = $this->getDBkey();
2969 $newtitle = $nt->getDBkey();
2971 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2972 WatchedItem
::duplicateEntries( $this, $nt );
2975 # Update search engine
2976 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2978 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2982 if( $this->isContentPage() && !$nt->isContentPage() ) {
2983 # No longer a content page
2984 # Not viewed, edited, removing
2985 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2986 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2987 # Now a content page
2988 # Not viewed, edited, adding
2989 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2990 } elseif( $pageCountChange ) {
2992 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2999 # Update message cache for interface messages
3000 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
3001 global $wgMessageCache;
3003 # @bug 17860: old article can be deleted, if this the case,
3004 # delete it from message cache
3005 if ( $this->getArticleID() === 0 ) {
3006 $wgMessageCache->replace( $this->getDBkey(), false );
3008 $oldarticle = new Article( $this );
3009 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3012 $newarticle = new Article( $nt );
3013 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3017 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3022 * Move page to a title which is at present a redirect to the
3025 * @param $nt \type{Title} the page to move to, which should currently
3027 * @param $reason \type{\string} The reason for the move
3028 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3029 * Ignored if the user doesn't have the suppressredirect right
3031 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3032 global $wgUseSquid, $wgUser, $wgContLang;
3034 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3037 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3039 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3040 $comment = $wgContLang->truncate( $comment, 250 );
3042 $now = wfTimestampNow();
3043 $newid = $nt->getArticleID();
3044 $oldid = $this->getArticleID();
3045 $latest = $this->getLatestRevID();
3047 $dbw = wfGetDB( DB_MASTER
);
3049 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3050 $newns = $nt->getNamespace();
3051 $newdbk = $nt->getDBkey();
3053 # Delete the old redirect. We don't save it to history since
3054 # by definition if we've got here it's rather uninteresting.
3055 # We have to remove it so that the next step doesn't trigger
3056 # a conflict on the unique namespace+title index...
3057 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3058 if ( !$dbw->cascadingDeletes() ) {
3059 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3060 global $wgUseTrackbacks;
3061 if ($wgUseTrackbacks)
3062 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3063 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3064 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3065 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3066 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3067 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3068 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3069 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3071 // If the redirect was recently created, it may have an entry in recentchanges still
3072 $dbw->delete( 'recentchanges',
3073 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3077 # Save a null revision in the page's history notifying of the move
3078 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3079 $nullRevId = $nullRevision->insertOn( $dbw );
3081 $article = new Article( $this );
3082 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3084 # Change the name of the target page:
3085 $dbw->update( 'page',
3087 'page_touched' => $dbw->timestamp($now),
3088 'page_namespace' => $nt->getNamespace(),
3089 'page_title' => $nt->getDBkey(),
3090 'page_latest' => $nullRevId,
3092 /* WHERE */ array( 'page_id' => $oldid ),
3095 $nt->resetArticleID( $oldid );
3097 # Recreate the redirect, this time in the other direction.
3098 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3099 $mwRedir = MagicWord
::get( 'redirect' );
3100 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3101 $redirectArticle = new Article( $this );
3102 $newid = $redirectArticle->insertOn( $dbw );
3103 $redirectRevision = new Revision( array(
3105 'comment' => $comment,
3106 'text' => $redirectText ) );
3107 $redirectRevision->insertOn( $dbw );
3108 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3110 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3112 # Now, we record the link from the redirect to the new title.
3113 # It should have no other outgoing links...
3114 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3115 $dbw->insert( 'pagelinks',
3117 'pl_from' => $newid,
3118 'pl_namespace' => $nt->getNamespace(),
3119 'pl_title' => $nt->getDBkey() ),
3121 $redirectSuppressed = false;
3123 $this->resetArticleID( 0 );
3124 $redirectSuppressed = true;
3128 $log = new LogPage( 'move' );
3129 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3132 if ( $wgUseSquid ) {
3133 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3134 $u = new SquidUpdate( $urls );
3141 * Move page to non-existing title.
3143 * @param $nt \type{Title} the new Title
3144 * @param $reason \type{\string} The reason for the move
3145 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3146 * Ignored if the user doesn't have the suppressredirect right
3148 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3149 global $wgUseSquid, $wgUser, $wgContLang;
3151 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3153 $comment .= wfMsgExt( 'colon-separator',
3154 array( 'escapenoentities', 'content' ) );
3155 $comment .= $reason;
3157 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3158 $comment = $wgContLang->truncate( $comment, 250 );
3160 $newid = $nt->getArticleID();
3161 $oldid = $this->getArticleID();
3162 $latest = $this->getLatestRevId();
3164 $dbw = wfGetDB( DB_MASTER
);
3165 $now = $dbw->timestamp();
3167 # Save a null revision in the page's history notifying of the move
3168 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3169 if ( !is_object( $nullRevision ) ) {
3170 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3172 $nullRevId = $nullRevision->insertOn( $dbw );
3174 $article = new Article( $this );
3175 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3178 $dbw->update( 'page',
3180 'page_touched' => $now,
3181 'page_namespace' => $nt->getNamespace(),
3182 'page_title' => $nt->getDBkey(),
3183 'page_latest' => $nullRevId,
3185 /* WHERE */ array( 'page_id' => $oldid ),
3188 $nt->resetArticleID( $oldid );
3190 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3192 $mwRedir = MagicWord
::get( 'redirect' );
3193 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3194 $redirectArticle = new Article( $this );
3195 $newid = $redirectArticle->insertOn( $dbw );
3196 $redirectRevision = new Revision( array(
3198 'comment' => $comment,
3199 'text' => $redirectText ) );
3200 $redirectRevision->insertOn( $dbw );
3201 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3203 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3205 # Record the just-created redirect's linking to the page
3206 $dbw->insert( 'pagelinks',
3208 'pl_from' => $newid,
3209 'pl_namespace' => $nt->getNamespace(),
3210 'pl_title' => $nt->getDBkey() ),
3212 $redirectSuppressed = false;
3214 $this->resetArticleID( 0 );
3215 $redirectSuppressed = true;
3219 $log = new LogPage( 'move' );
3220 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3222 # Purge caches as per article creation
3223 Article
::onArticleCreate( $nt );
3225 # Purge old title from squid
3226 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3227 $this->purgeSquid();
3232 * Move this page's subpages to be subpages of $nt
3234 * @param $nt Title Move target
3235 * @param $auth bool Whether $wgUser's permissions should be checked
3236 * @param $reason string The reason for the move
3237 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3238 * Ignored if the user doesn't have the 'suppressredirect' right
3239 * @return mixed array with old page titles as keys, and strings (new page titles) or
3240 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3242 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3243 global $wgMaximumMovedPages;
3244 // Check permissions
3245 if( !$this->userCan( 'move-subpages' ) )
3246 return array( 'cant-move-subpages' );
3247 // Do the source and target namespaces support subpages?
3248 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3249 return array( 'namespace-nosubpages',
3250 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3251 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3252 return array( 'namespace-nosubpages',
3253 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3255 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3258 foreach( $subpages as $oldSubpage ) {
3260 if( $count > $wgMaximumMovedPages ) {
3261 $retval[$oldSubpage->getPrefixedTitle()] =
3262 array( 'movepage-max-pages',
3263 $wgMaximumMovedPages );
3267 // We don't know whether this function was called before
3268 // or after moving the root page, so check both
3270 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3271 $oldSubpage->getArticleID() == $nt->getArticleId() )
3272 // When moving a page to a subpage of itself,
3273 // don't move it twice
3275 $newPageName = preg_replace(
3276 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3277 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3278 $oldSubpage->getDBkey() );
3279 if( $oldSubpage->isTalkPage() ) {
3280 $newNs = $nt->getTalkPage()->getNamespace();
3282 $newNs = $nt->getSubjectPage()->getNamespace();
3284 # Bug 14385: we need makeTitleSafe because the new page names may
3285 # be longer than 255 characters.
3286 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3288 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3289 if( $success === true ) {
3290 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3292 $retval[$oldSubpage->getPrefixedText()] = $success;
3299 * Checks if this page is just a one-rev redirect.
3300 * Adds lock, so don't use just for light purposes.
3302 * @return \type{\bool}
3304 public function isSingleRevRedirect() {
3305 $dbw = wfGetDB( DB_MASTER
);
3307 $row = $dbw->selectRow( 'page',
3308 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3311 array( 'FOR UPDATE' )
3313 # Cache some fields we may want
3314 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3315 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3316 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3317 if( !$this->mRedirect
) {
3320 # Does the article have a history?
3321 $row = $dbw->selectField( array( 'page', 'revision'),
3323 array( 'page_namespace' => $this->getNamespace(),
3324 'page_title' => $this->getDBkey(),
3326 'page_latest != rev_id'
3329 array( 'FOR UPDATE' )
3331 # Return true if there was no history
3332 return ($row === false);
3336 * Checks if $this can be moved to a given Title
3337 * - Selects for update, so don't call it unless you mean business
3339 * @param $nt \type{Title} the new title to check
3340 * @return \type{\bool} TRUE or FALSE
3342 public function isValidMoveTarget( $nt ) {
3343 $dbw = wfGetDB( DB_MASTER
);
3344 # Is it an existsing file?
3345 if( $nt->getNamespace() == NS_FILE
) {
3346 $file = wfLocalFile( $nt );
3347 if( $file->exists() ) {
3348 wfDebug( __METHOD__
. ": file exists\n" );
3352 # Is it a redirect with no history?
3353 if( !$nt->isSingleRevRedirect() ) {
3354 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3357 # Get the article text
3358 $rev = Revision
::newFromTitle( $nt );
3359 $text = $rev->getText();
3360 # Does the redirect point to the source?
3361 # Or is it a broken self-redirect, usually caused by namespace collisions?
3363 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3364 $redirTitle = Title
::newFromText( $m[1] );
3365 if( !is_object( $redirTitle ) ||
3366 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3367 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3368 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3373 wfDebug( __METHOD__
. ": failsafe\n" );
3380 * Can this title be added to a user's watchlist?
3382 * @return \type{\bool} TRUE or FALSE
3384 public function isWatchable() {
3385 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3389 * Get categories to which this Title belongs and return an array of
3390 * categories' names.
3392 * @return \type{\array} array an array of parents in the form:
3393 * $parent => $currentarticle
3395 public function getParentCategories() {
3398 $titlekey = $this->getArticleId();
3399 $dbr = wfGetDB( DB_SLAVE
);
3400 $categorylinks = $dbr->tableName( 'categorylinks' );
3403 $sql = "SELECT * FROM $categorylinks"
3404 ." WHERE cl_from='$titlekey'"
3405 ." AND cl_from <> '0'"
3406 ." ORDER BY cl_sortkey";
3408 $res = $dbr->query( $sql );
3410 if( $dbr->numRows( $res ) > 0 ) {
3411 foreach( $res as $row )
3412 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3413 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3414 $dbr->freeResult( $res );
3422 * Get a tree of parent categories
3424 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3425 * @return \type{\array} Tree of parent categories
3427 public function getParentCategoryTree( $children = array() ) {
3429 $parents = $this->getParentCategories();
3432 foreach( $parents as $parent => $current ) {
3433 if ( array_key_exists( $parent, $children ) ) {
3434 # Circular reference
3435 $stack[$parent] = array();
3437 $nt = Title
::newFromText($parent);
3439 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3451 * Get an associative array for selecting this title from
3454 * @return \type{\array} Selection array
3456 public function pageCond() {
3457 if( $this->mArticleID
> 0 ) {
3458 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3459 return array( 'page_id' => $this->mArticleID
);
3461 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3466 * Get the revision ID of the previous revision
3468 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3469 * @param $flags \type{\int} GAID_FOR_UPDATE
3470 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3472 public function getPreviousRevisionID( $revId, $flags=0 ) {
3473 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3474 return $db->selectField( 'revision', 'rev_id',
3476 'rev_page' => $this->getArticleId($flags),
3477 'rev_id < ' . intval( $revId )
3480 array( 'ORDER BY' => 'rev_id DESC' )
3485 * Get the revision ID of the next revision
3487 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3488 * @param $flags \type{\int} GAID_FOR_UPDATE
3489 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3491 public function getNextRevisionID( $revId, $flags=0 ) {
3492 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3493 return $db->selectField( 'revision', 'rev_id',
3495 'rev_page' => $this->getArticleId($flags),
3496 'rev_id > ' . intval( $revId )
3499 array( 'ORDER BY' => 'rev_id' )
3504 * Get the first revision of the page
3506 * @param $flags \type{\int} GAID_FOR_UPDATE
3507 * @return Revision (or NULL if page doesn't exist)
3509 public function getFirstRevision( $flags=0 ) {
3510 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3511 $pageId = $this->getArticleId($flags);
3512 if( !$pageId ) return null;
3513 $row = $db->selectRow( 'revision', '*',
3514 array( 'rev_page' => $pageId ),
3516 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3521 return new Revision( $row );
3526 * Check if this is a new page
3530 public function isNewPage() {
3531 $dbr = wfGetDB( DB_SLAVE
);
3532 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3536 * Get the oldest revision timestamp of this page
3538 * @return String: MW timestamp
3540 public function getEarliestRevTime() {
3541 $dbr = wfGetDB( DB_SLAVE
);
3542 if( $this->exists() ) {
3543 $min = $dbr->selectField( 'revision',
3544 'MIN(rev_timestamp)',
3545 array( 'rev_page' => $this->getArticleId() ),
3547 return wfTimestampOrNull( TS_MW
, $min );
3553 * Get the number of revisions between the given revision IDs.
3554 * Used for diffs and other things that really need it.
3556 * @param $old \type{\int} Revision ID.
3557 * @param $new \type{\int} Revision ID.
3558 * @return \type{\int} Number of revisions between these IDs.
3560 public function countRevisionsBetween( $old, $new ) {
3561 $dbr = wfGetDB( DB_SLAVE
);
3562 return (int)$dbr->selectField( 'revision', 'count(*)',
3563 'rev_page = ' . intval( $this->getArticleId() ) .
3564 ' AND rev_id > ' . intval( $old ) .
3565 ' AND rev_id < ' . intval( $new ),
3571 * Compare with another title.
3573 * @param $title \type{Title}
3574 * @return \type{\bool} TRUE or FALSE
3576 public function equals( Title
$title ) {
3577 // Note: === is necessary for proper matching of number-like titles.
3578 return $this->getInterwiki() === $title->getInterwiki()
3579 && $this->getNamespace() == $title->getNamespace()
3580 && $this->getDBkey() === $title->getDBkey();
3584 * Callback for usort() to do title sorts by (namespace, title)
3586 * @return Integer: result of string comparison, or namespace comparison
3588 public static function compare( $a, $b ) {
3589 if( $a->getNamespace() == $b->getNamespace() ) {
3590 return strcmp( $a->getText(), $b->getText() );
3592 return $a->getNamespace() - $b->getNamespace();
3597 * Return a string representation of this title
3599 * @return \type{\string} String representation of this title
3601 public function __toString() {
3602 return $this->getPrefixedText();
3606 * Check if page exists. For historical reasons, this function simply
3607 * checks for the existence of the title in the page table, and will
3608 * thus return false for interwiki links, special pages and the like.
3609 * If you want to know if a title can be meaningfully viewed, you should
3610 * probably call the isKnown() method instead.
3612 * @return \type{\bool}
3614 public function exists() {
3615 return $this->getArticleId() != 0;
3619 * Should links to this title be shown as potentially viewable (i.e. as
3620 * "bluelinks"), even if there's no record by this title in the page
3623 * This function is semi-deprecated for public use, as well as somewhat
3624 * misleadingly named. You probably just want to call isKnown(), which
3625 * calls this function internally.
3627 * (ISSUE: Most of these checks are cheap, but the file existence check
3628 * can potentially be quite expensive. Including it here fixes a lot of
3629 * existing code, but we might want to add an optional parameter to skip
3630 * it and any other expensive checks.)
3632 * @return \type{\bool}
3634 public function isAlwaysKnown() {
3635 if( $this->mInterwiki
!= '' ) {
3636 return true; // any interwiki link might be viewable, for all we know
3638 switch( $this->mNamespace
) {
3641 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3643 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3645 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3647 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3648 // the full l10n of that language to be loaded. That takes much memory and
3649 // isn't needed. So we strip the language part away.
3650 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3651 return (bool)wfMsgWeirdKey( $basename ); // known system message
3658 * Does this title refer to a page that can (or might) be meaningfully
3659 * viewed? In particular, this function may be used to determine if
3660 * links to the title should be rendered as "bluelinks" (as opposed to
3661 * "redlinks" to non-existent pages).
3663 * @return \type{\bool}
3665 public function isKnown() {
3666 return $this->exists() ||
$this->isAlwaysKnown();
3670 * Does this page have source text?
3674 public function hasSourceText() {
3675 if ( $this->exists() )
3678 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3679 // If the page doesn't exist but is a known system message, default
3680 // message content will be displayed, same for language subpages
3681 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3682 // causes the full l10n of that language to be loaded. That takes much
3683 // memory and isn't needed. So we strip the language part away.
3684 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3685 return (bool)wfMsgWeirdKey( $basename );
3692 * Is this in a namespace that allows actual pages?
3694 * @return \type{\bool}
3695 * @internal note -- uses hardcoded namespace index instead of constants
3697 public function canExist() {
3698 return $this->mNamespace
>=0 && $this->mNamespace
!= NS_MEDIA
;
3702 * Update page_touched timestamps and send squid purge messages for
3703 * pages linking to this title. May be sent to the job queue depending
3704 * on the number of links. Typically called on create and delete.
3706 public function touchLinks() {
3707 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3710 if ( $this->getNamespace() == NS_CATEGORY
) {
3711 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3717 * Get the last touched timestamp
3719 * @param $db DatabaseBase: optional db
3720 * @return \type{\string} Last touched timestamp
3722 public function getTouched( $db = null ) {
3723 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3724 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3729 * Get the timestamp when this page was updated since the user last saw it.
3732 * @return Mixed: string/null
3734 public function getNotificationTimestamp( $user = null ) {
3735 global $wgUser, $wgShowUpdatedMarker;
3736 // Assume current user if none given
3737 if( !$user ) $user = $wgUser;
3738 // Check cache first
3739 $uid = $user->getId();
3740 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3741 return $this->mNotificationTimestamp
[$uid];
3743 if( !$uid ||
!$wgShowUpdatedMarker ) {
3744 return $this->mNotificationTimestamp
[$uid] = false;
3746 // Don't cache too much!
3747 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3748 $this->mNotificationTimestamp
= array();
3750 $dbr = wfGetDB( DB_SLAVE
);
3751 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3752 'wl_notificationtimestamp',
3753 array( 'wl_namespace' => $this->getNamespace(),
3754 'wl_title' => $this->getDBkey(),
3755 'wl_user' => $user->getId()
3759 return $this->mNotificationTimestamp
[$uid];
3763 * Get the trackback URL for this page
3765 * @return \type{\string} Trackback URL
3767 public function trackbackURL() {
3768 global $wgScriptPath, $wgServer, $wgScriptExtension;
3770 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3771 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3775 * Get the trackback RDF for this page
3777 * @return \type{\string} Trackback RDF
3779 public function trackbackRDF() {
3780 $url = htmlspecialchars($this->getFullURL());
3781 $title = htmlspecialchars($this->getText());
3782 $tburl = $this->trackbackURL();
3784 // Autodiscovery RDF is placed in comments so HTML validator
3785 // won't barf. This is a rather icky workaround, but seems
3786 // frequently used by this kind of RDF thingy.
3788 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3790 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3791 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3792 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3795 dc:identifier=\"$url\"
3797 trackback:ping=\"$tburl\" />
3803 * Generate strings used for xml 'id' names in monobook tabs
3805 * @param $prepend string defaults to 'nstab-'
3806 * @return \type{\string} XML 'id' name
3808 public function getNamespaceKey( $prepend = 'nstab-' ) {
3810 // Gets the subject namespace if this title
3811 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3812 // Checks if cononical namespace name exists for namespace
3813 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3814 // Uses canonical namespace name
3815 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3817 // Uses text of namespace
3818 $namespaceKey = $this->getSubjectNsText();
3820 // Makes namespace key lowercase
3821 $namespaceKey = $wgContLang->lc( $namespaceKey );
3823 if ( $namespaceKey == '' ) {
3824 $namespaceKey = 'main';
3826 // Changes file to image for backwards compatibility
3827 if ( $namespaceKey == 'file' ) {
3828 $namespaceKey = 'image';
3830 return $prepend . $namespaceKey;
3834 * Returns true if this is a special page.
3838 public function isSpecialPage( ) {
3839 return $this->getNamespace() == NS_SPECIAL
;
3843 * Returns true if this title resolves to the named special page
3845 * @param $name \type{\string} The special page name
3848 public function isSpecial( $name ) {
3849 if ( $this->getNamespace() == NS_SPECIAL
) {
3850 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3851 if ( $name == $thisName ) {
3859 * If the Title refers to a special page alias which is not the local default,
3861 * @return \type{Title} A new Title which points to the local default.
3862 * Otherwise, returns $this.
3864 public function fixSpecialName() {
3865 if ( $this->getNamespace() == NS_SPECIAL
) {
3866 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3867 if ( $canonicalName ) {
3868 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3869 if ( $localName != $this->mDbkeyform
) {
3870 return Title
::makeTitle( NS_SPECIAL
, $localName );
3878 * Is this Title in a namespace which contains content?
3879 * In other words, is this a content page, for the purposes of calculating
3882 * @return \type{\bool}
3884 public function isContentPage() {
3885 return MWNamespace
::isContent( $this->getNamespace() );
3889 * Get all extant redirects to this Title
3891 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3892 * NULL to consider all namespaces
3893 * @return \type{\arrayof{Title}} Redirects to this title
3895 public function getRedirectsHere( $ns = null ) {
3898 $dbr = wfGetDB( DB_SLAVE
);
3900 'rd_namespace' => $this->getNamespace(),
3901 'rd_title' => $this->getDBkey(),
3904 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3906 $res = $dbr->select(
3907 array( 'redirect', 'page' ),
3908 array( 'page_namespace', 'page_title' ),
3914 foreach( $res as $row ) {
3915 $redirs[] = self
::newFromRow( $row );
3921 * Check if this Title is a valid redirect target
3923 * @return \type{\bool}
3925 public function isValidRedirectTarget() {
3926 global $wgInvalidRedirectTargets;
3928 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3929 if( $this->isSpecial( 'Userlogout' ) ) {
3933 foreach( $wgInvalidRedirectTargets as $target ) {
3934 if( $this->isSpecial( $target ) ) {
3943 * Get a backlink cache object
3945 * @return object BacklinkCache
3947 function getBacklinkCache() {
3948 if ( is_null( $this->mBacklinkCache
) ) {
3949 $this->mBacklinkCache
= new BacklinkCache( $this );
3951 return $this->mBacklinkCache
;
3955 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3960 public function canUseNoindex(){
3961 global $wgArticleRobotPolicies, $wgContentNamespaces,
3962 $wgExemptFromUserRobotsControl;
3964 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3965 ?
$wgContentNamespaces
3966 : $wgExemptFromUserRobotsControl;
3968 return !in_array( $this->mNamespace
, $bannedNamespaces );
3973 * Returns restriction types for the current Title
3975 * @return array applicable restriction types
3977 public function getRestrictionTypes() {
3978 global $wgRestrictionTypes;
3979 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3981 if ( $this->getNamespace() == NS_FILE
) {
3982 $types[] = 'upload';
3985 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );