7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
14 * Represents a title within MediaWiki.
15 * Optionally may contain an interwiki designation or namespace.
16 * @note This class can fetch various kinds of data from the database;
17 * however, it does so inefficiently.
20 /** @name Static cache variables */
22 static private $titleCache=array();
23 static private $interwikiCache=array();
27 * Title::newFromText maintains a cache to avoid expensive re-normalization of
28 * commonly used titles. On a batch operation this can become a memory leak
29 * if not bounded. After hitting this many titles reset the cache.
31 const CACHE_MAX
= 1000;
35 * @name Private member variables
36 * Please use the accessor functions instead.
41 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
42 var $mUrlform = ''; ///< URL-encoded form of the main part
43 var $mDbkeyform = ''; ///< Main part with underscores
44 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
45 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
46 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
47 var $mFragment; ///< Title fragment (i.e. the bit after the #)
48 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
49 var $mLatestID = false; ///< ID of most recent revision
50 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
51 var $mOldRestrictions = false;
52 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
53 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
54 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
55 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
56 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
57 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
58 # Don't change the following default, NS_MAIN is hardcoded in several
59 # places. See bug 696.
60 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
61 # Zero except in {{transclusion}} tags
62 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
63 var $mLength = -1; ///< The page length, 0 for special pages
64 var $mRedirect = null; ///< Is the article at this title a redirect?
65 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
66 var $mBacklinkCache = null; ///< Cache of links to this title
74 /* private */ function __construct() {}
77 * Create a new Title from a prefixed DB key
78 * @param $key \type{\string} The database key, which has underscores
79 * instead of spaces, possibly including namespace and
81 * @return \type{Title} the new object, or NULL on an error
83 public static function newFromDBkey( $key ) {
85 $t->mDbkeyform
= $key;
86 if( $t->secureAndSplit() )
93 * Create a new Title from text, such as what one would find in a link. De-
94 * codes any HTML entities in the text.
96 * @param $text string The link text; spaces, prefixes, and an
97 * initial ':' indicating the main namespace are accepted.
98 * @param $defaultNamespace int The namespace to use if none is speci-
99 * fied by a prefix. If you want to force a specific namespace even if
100 * $text might begin with a namespace prefix, use makeTitle() or
102 * @return Title The new object, or null on an error.
104 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
105 if( is_object( $text ) ) {
106 throw new MWException( 'Title::newFromText given an object' );
110 * Wiki pages often contain multiple links to the same page.
111 * Title normalization and parsing can become expensive on
112 * pages with many links, so we can save a little time by
115 * In theory these are value objects and won't get changed...
117 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
118 return Title
::$titleCache[$text];
122 * Convert things like é ā or 〗 into real text...
124 $filteredText = Sanitizer
::decodeCharReferences( $text );
127 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
128 $t->mDefaultNamespace
= $defaultNamespace;
130 static $cachedcount = 0 ;
131 if( $t->secureAndSplit() ) {
132 if( $defaultNamespace == NS_MAIN
) {
133 if( $cachedcount >= self
::CACHE_MAX
) {
134 # Avoid memory leaks on mass operations...
135 Title
::$titleCache = array();
139 Title
::$titleCache[$text] =& $t;
149 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
151 * Example of wrong and broken code:
152 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
154 * Example of right code:
155 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
157 * Create a new Title from URL-encoded text. Ensures that
158 * the given title's length does not exceed the maximum.
159 * @param $url \type{\string} the title, as might be taken from a URL
160 * @return \type{Title} the new object, or NULL on an error
162 public static function newFromURL( $url ) {
163 global $wgLegalTitleChars;
166 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
167 # but some URLs used it as a space replacement and they still come
168 # from some external search tools.
169 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
170 $url = str_replace( '+', ' ', $url );
173 $t->mDbkeyform
= str_replace( ' ', '_', $url );
174 if( $t->secureAndSplit() ) {
182 * Create a new Title from an article ID
184 * @param $id \type{\int} the page_id corresponding to the Title to create
185 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
186 * @return \type{Title} the new object, or NULL on an error
188 public static function newFromID( $id, $flags = 0 ) {
189 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
190 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
191 if( $row !== false ) {
192 $title = Title
::newFromRow( $row );
200 * Make an array of titles from an array of IDs
201 * @param $ids \type{\arrayof{\int}} Array of IDs
202 * @return \type{\arrayof{Title}} Array of Titles
204 public static function newFromIDs( $ids ) {
205 if ( !count( $ids ) ) {
208 $dbr = wfGetDB( DB_SLAVE
);
209 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
210 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
213 foreach( $res as $row ) {
214 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
220 * Make a Title object from a DB row
221 * @param $row \type{Row} (needs at least page_title,page_namespace)
222 * @return \type{Title} corresponding Title
224 public static function newFromRow( $row ) {
225 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
227 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
228 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
229 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
230 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
236 * Create a new Title from a namespace index and a DB key.
237 * It's assumed that $ns and $title are *valid*, for instance when
238 * they came directly from the database or a special page name.
239 * For convenience, spaces are converted to underscores so that
240 * eg user_text fields can be used directly.
242 * @param $ns \type{\int} the namespace of the article
243 * @param $title \type{\string} the unprefixed database key form
244 * @param $fragment \type{\string} The link fragment (after the "#")
245 * @return \type{Title} the new object
247 public static function &makeTitle( $ns, $title, $fragment = '' ) {
250 $t->mFragment
= $fragment;
251 $t->mNamespace
= $ns = intval( $ns );
252 $t->mDbkeyform
= str_replace( ' ', '_', $title );
253 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
254 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
255 $t->mTextform
= str_replace( '_', ' ', $title );
260 * Create a new Title from a namespace index and a DB key.
261 * The parameters will be checked for validity, which is a bit slower
262 * than makeTitle() but safer for user-provided data.
264 * @param $ns \type{\int} the namespace of the article
265 * @param $title \type{\string} the database key form
266 * @param $fragment \type{\string} The link fragment (after the "#")
267 * @return \type{Title} the new object, or NULL on an error
269 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
271 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
272 if( $t->secureAndSplit() ) {
280 * Create a new Title for the Main Page
281 * @return \type{Title} the new object
283 public static function newMainPage() {
284 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
285 // Don't give fatal errors if the message is broken
287 $title = Title
::newFromText( 'Main Page' );
293 * Extract a redirect destination from a string and return the
294 * Title, or null if the text doesn't contain a valid redirect
295 * This will only return the very next target, useful for
296 * the redirect table and other checks that don't need full recursion
298 * @param $text \type{\string} Text with possible redirect
299 * @return \type{Title} The corresponding Title
301 public static function newFromRedirect( $text ) {
302 return self
::newFromRedirectInternal( $text );
306 * Extract a redirect destination from a string and return the
307 * Title, or null if the text doesn't contain a valid redirect
308 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
309 * in order to provide (hopefully) the Title of the final destination instead of another redirect
311 * @param $text \type{\string} Text with possible redirect
312 * @return \type{Title} The corresponding Title
314 public static function newFromRedirectRecurse( $text ) {
315 $titles = self
::newFromRedirectArray( $text );
316 return $titles ?
array_pop( $titles ) : null;
320 * Extract a redirect destination from a string and return an
321 * array of Titles, or null if the text doesn't contain a valid redirect
322 * The last element in the array is the final destination after all redirects
323 * have been resolved (up to $wgMaxRedirects times)
325 * @param $text \type{\string} Text with possible redirect
326 * @return \type{\array} Array of Titles, with the destination last
328 public static function newFromRedirectArray( $text ) {
329 global $wgMaxRedirects;
330 // are redirects disabled?
331 if( $wgMaxRedirects < 1 )
333 $title = self
::newFromRedirectInternal( $text );
334 if( is_null( $title ) )
336 // recursive check to follow double redirects
337 $recurse = $wgMaxRedirects;
338 $titles = array( $title );
339 while( --$recurse > 0 ) {
340 if( $title->isRedirect() ) {
341 $article = new Article( $title, 0 );
342 $newtitle = $article->getRedirectTarget();
346 // Redirects to some special pages are not permitted
347 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
348 // the new title passes the checks, so make that our current title so that further recursion can be checked
350 $titles[] = $newtitle;
359 * Really extract the redirect destination
360 * Do not call this function directly, use one of the newFromRedirect* functions above
362 * @param $text \type{\string} Text with possible redirect
363 * @return \type{Title} The corresponding Title
365 protected static function newFromRedirectInternal( $text ) {
366 $redir = MagicWord
::get( 'redirect' );
368 if( $redir->matchStartAndRemove( $text ) ) {
369 // Extract the first link and see if it's usable
370 // Ensure that it really does come directly after #REDIRECT
371 // Some older redirects included a colon, so don't freak about that!
373 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
374 // Strip preceding colon used to "escape" categories, etc.
375 // and URL-decode links
376 if( strpos( $m[1], '%' ) !== false ) {
377 // Match behavior of inline link parsing here;
378 // don't interpret + as " " most of the time!
379 // It might be safe to just use rawurldecode instead, though.
380 $m[1] = urldecode( ltrim( $m[1], ':' ) );
382 $title = Title
::newFromText( $m[1] );
383 // If the title is a redirect to bad special pages or is invalid, return null
384 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
393 #----------------------------------------------------------------------------
395 #----------------------------------------------------------------------------
398 * Get the prefixed DB key associated with an ID
399 * @param $id \type{\int} the page_id of the article
400 * @return \type{Title} an object representing the article, or NULL
401 * if no such article was found
403 public static function nameOf( $id ) {
404 $dbr = wfGetDB( DB_SLAVE
);
406 $s = $dbr->selectRow( 'page',
407 array( 'page_namespace','page_title' ),
408 array( 'page_id' => $id ),
410 if ( $s === false ) { return null; }
412 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
417 * Get a regex character class describing the legal characters in a link
418 * @return \type{\string} the list of characters, not delimited
420 public static function legalChars() {
421 global $wgLegalTitleChars;
422 return $wgLegalTitleChars;
426 * Get a string representation of a title suitable for
427 * including in a search index
429 * @param $ns \type{\int} a namespace index
430 * @param $title \type{\string} text-form main part
431 * @return \type{\string} a stripped-down title string ready for the
434 public static function indexTitle( $ns, $title ) {
437 $lc = SearchEngine
::legalSearchChars() . '&#;';
438 $t = $wgContLang->stripForSearch( $title );
439 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
440 $t = $wgContLang->lc( $t );
443 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
444 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
446 $t = preg_replace( "/\\s+/", ' ', $t );
448 if ( $ns == NS_FILE
) {
449 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
455 * Make a prefixed DB key from a DB key and a namespace index
456 * @param $ns \type{\int} numerical representation of the namespace
457 * @param $title \type{\string} the DB key form the title
458 * @param $fragment \type{\string} The link fragment (after the "#")
459 * @return \type{\string} the prefixed form of the title
461 public static function makeName( $ns, $title, $fragment = '' ) {
464 $namespace = $wgContLang->getNsText( $ns );
465 $name = $namespace == '' ?
$title : "$namespace:$title";
466 if ( strval( $fragment ) != '' ) {
467 $name .= '#' . $fragment;
473 * Determine whether the object refers to a page within
476 * @return \type{\bool} TRUE if this is an in-project interwiki link
477 * or a wikilink, FALSE otherwise
479 public function isLocal() {
480 if ( $this->mInterwiki
!= '' ) {
481 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return \type{\bool} TRUE if this is transcludable
493 public function isTrans() {
494 if ($this->mInterwiki
== '')
497 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
501 * Escape a text fragment, say from a link, for a URL
503 static function escapeFragmentForURL( $fragment ) {
504 global $wgEnforceHtmlIds;
505 # Note that we don't urlencode the fragment. urlencoded Unicode
506 # fragments appear not to work in IE (at least up to 7) or in at least
507 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
508 # to care if they aren't encoded.
509 return Sanitizer
::escapeId( $fragment,
510 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
513 #----------------------------------------------------------------------------
515 #----------------------------------------------------------------------------
517 /** Simple accessors */
519 * Get the text form (spaces not underscores) of the main part
520 * @return \type{\string} Main part of the title
522 public function getText() { return $this->mTextform
; }
524 * Get the URL-encoded form of the main part
525 * @return \type{\string} Main part of the title, URL-encoded
527 public function getPartialURL() { return $this->mUrlform
; }
529 * Get the main part with underscores
530 * @return \type{\string} Main part of the title, with underscores
532 public function getDBkey() { return $this->mDbkeyform
; }
534 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
535 * @return \type{\int} Namespace index
537 public function getNamespace() { return $this->mNamespace
; }
539 * Get the namespace text
540 * @return \type{\string} Namespace text
542 public function getNsText() {
545 if ( '' != $this->mInterwiki
) {
546 // This probably shouldn't even happen. ohh man, oh yuck.
547 // But for interwiki transclusion it sometimes does.
548 // Shit. Shit shit shit.
550 // Use the canonical namespaces if possible to try to
551 // resolve a foreign namespace.
552 if( MWNamespace
::exists( $this->mNamespace
) ) {
553 return MWNamespace
::getCanonicalName( $this->mNamespace
);
556 return $wgContLang->getNsText( $this->mNamespace
);
559 * Get the DB key with the initial letter case as specified by the user
560 * @return \type{\string} DB key
562 function getUserCaseDBKey() {
563 return $this->mUserCaseDBKey
;
566 * Get the namespace text of the subject (rather than talk) page
567 * @return \type{\string} Namespace text
569 public function getSubjectNsText() {
571 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
574 * Get the namespace text of the talk page
575 * @return \type{\string} Namespace text
577 public function getTalkNsText() {
579 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
582 * Could this title have a corresponding talk page?
583 * @return \type{\bool} TRUE or FALSE
585 public function canTalk() {
586 return( MWNamespace
::canTalk( $this->mNamespace
) );
589 * Get the interwiki prefix (or null string)
590 * @return \type{\string} Interwiki prefix
592 public function getInterwiki() { return $this->mInterwiki
; }
594 * Get the Title fragment (i.e.\ the bit after the #) in text form
595 * @return \type{\string} Title fragment
597 public function getFragment() { return $this->mFragment
; }
599 * Get the fragment in URL form, including the "#" character if there is one
600 * @return \type{\string} Fragment in URL form
602 public function getFragmentForURL() {
603 if ( $this->mFragment
== '' ) {
606 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
610 * Get the default namespace index, for when there is no namespace
611 * @return \type{\int} Default namespace index
613 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
616 * Get title for search index
617 * @return \type{\string} a stripped-down title string ready for the
620 public function getIndexTitle() {
621 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
625 * Get the prefixed database key form
626 * @return \type{\string} the prefixed title, with underscores and
627 * any interwiki and namespace prefixes
629 public function getPrefixedDBkey() {
630 $s = $this->prefix( $this->mDbkeyform
);
631 $s = str_replace( ' ', '_', $s );
636 * Get the prefixed title with spaces.
637 * This is the form usually used for display
638 * @return \type{\string} the prefixed title, with spaces
640 public function getPrefixedText() {
641 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
642 $s = $this->prefix( $this->mTextform
);
643 $s = str_replace( '_', ' ', $s );
644 $this->mPrefixedText
= $s;
646 return $this->mPrefixedText
;
650 * Get the prefixed title with spaces, plus any fragment
651 * (part beginning with '#')
652 * @return \type{\string} the prefixed title, with spaces and
653 * the fragment, including '#'
655 public function getFullText() {
656 $text = $this->getPrefixedText();
657 if( '' != $this->mFragment
) {
658 $text .= '#' . $this->mFragment
;
664 * Get the base name, i.e. the leftmost parts before the /
665 * @return \type{\string} Base name
667 public function getBaseText() {
668 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
669 return $this->getText();
672 $parts = explode( '/', $this->getText() );
673 # Don't discard the real title if there's no subpage involved
674 if( count( $parts ) > 1 )
675 unset( $parts[ count( $parts ) - 1 ] );
676 return implode( '/', $parts );
680 * Get the lowest-level subpage name, i.e. the rightmost part after /
681 * @return \type{\string} Subpage name
683 public function getSubpageText() {
684 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
685 return( $this->mTextform
);
687 $parts = explode( '/', $this->mTextform
);
688 return( $parts[ count( $parts ) - 1 ] );
692 * Get a URL-encoded form of the subpage text
693 * @return \type{\string} URL-encoded subpage name
695 public function getSubpageUrlForm() {
696 $text = $this->getSubpageText();
697 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
702 * Get a URL-encoded title (not an actual URL) including interwiki
703 * @return \type{\string} the URL-encoded form
705 public function getPrefixedURL() {
706 $s = $this->prefix( $this->mDbkeyform
);
707 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
712 * Get a real URL referring to this title, with interwiki link and
715 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
716 * links. Can be specified as an associative array as well, e.g.,
717 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
718 * @param $variant \type{\string} language variant of url (for sr, zh..)
719 * @return \type{\string} the URL
721 public function getFullURL( $query = '', $variant = false ) {
722 global $wgContLang, $wgServer, $wgRequest;
724 if( is_array( $query ) ) {
725 $query = wfArrayToCGI( $query );
728 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
730 $url = $this->getLocalURL( $query, $variant );
732 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
733 // Correct fix would be to move the prepending elsewhere.
734 if ($wgRequest->getVal('action') != 'render') {
735 $url = $wgServer . $url;
738 $baseUrl = $interwiki->getURL( );
740 $namespace = wfUrlencode( $this->getNsText() );
741 if ( '' != $namespace ) {
742 # Can this actually happen? Interwikis shouldn't be parsed.
743 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
746 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
747 $url = wfAppendQuery( $url, $query );
750 # Finally, add the fragment.
751 $url .= $this->getFragmentForURL();
753 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
758 * Get a URL with no fragment or server name. If this page is generated
759 * with action=render, $wgServer is prepended.
760 * @param mixed $query an optional query string; if not specified,
761 * $wgArticlePath will be used. Can be specified as an associative array
762 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
764 * @param $variant \type{\string} language variant of url (for sr, zh..)
765 * @return \type{\string} the URL
767 public function getLocalURL( $query = '', $variant = false ) {
768 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
769 global $wgVariantArticlePath, $wgContLang, $wgUser;
771 if( is_array( $query ) ) {
772 $query = wfArrayToCGI( $query );
775 // internal links should point to same variant as current page (only anonymous users)
776 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
777 $pref = $wgContLang->getPreferredVariant(false);
778 if($pref != $wgContLang->getCode())
782 if ( $this->isExternal() ) {
783 $url = $this->getFullURL();
785 // This is currently only used for edit section links in the
786 // context of interwiki transclusion. In theory we should
787 // append the query to the end of any existing query string,
788 // but interwiki transclusion is already broken in that case.
792 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
793 if ( $query == '' ) {
794 if( $variant != false && $wgContLang->hasVariants() ) {
795 if( $wgVariantArticlePath == false ) {
796 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
798 $variantArticlePath = $wgVariantArticlePath;
800 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
801 $url = str_replace( '$1', $dbkey, $url );
803 $url = str_replace( '$1', $dbkey, $wgArticlePath );
806 global $wgActionPaths;
809 if( !empty( $wgActionPaths ) &&
810 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
812 $action = urldecode( $matches[2] );
813 if( isset( $wgActionPaths[$action] ) ) {
814 $query = $matches[1];
815 if( isset( $matches[4] ) ) $query .= $matches[4];
816 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
818 $url = wfAppendQuery( $url, $query );
822 if ( $url === false ) {
823 if ( $query == '-' ) {
826 $url = "{$wgScript}?title={$dbkey}&{$query}";
830 // FIXME: this causes breakage in various places when we
831 // actually expected a local URL and end up with dupe prefixes.
832 if ($wgRequest->getVal('action') == 'render') {
833 $url = $wgServer . $url;
836 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
841 * Get a URL that's the simplest URL that will be valid to link, locally,
842 * to the current Title. It includes the fragment, but does not include
843 * the server unless action=render is used (or the link is external). If
844 * there's a fragment but the prefixed text is empty, we just return a link
847 * The result obviously should not be URL-escaped, but does need to be
848 * HTML-escaped if it's being output in HTML.
850 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
851 * query string. Keys and values will be escaped.
852 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
853 * for external links. Default is "false" (same variant as current page,
854 * for anonymous users).
855 * @return \type{\string} the URL
857 public function getLinkUrl( $query = array(), $variant = false ) {
858 wfProfileIn( __METHOD__
);
859 if( $this->isExternal() ) {
860 $ret = $this->getFullURL( $query );
861 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
862 $ret = $this->getFragmentForURL();
864 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
866 wfProfileOut( __METHOD__
);
871 * Get an HTML-escaped version of the URL form, suitable for
872 * using in a link, without a server name or fragment
873 * @param $query \type{\string} an optional query string
874 * @return \type{\string} the URL
876 public function escapeLocalURL( $query = '' ) {
877 return htmlspecialchars( $this->getLocalURL( $query ) );
881 * Get an HTML-escaped version of the URL form, suitable for
882 * using in a link, including the server name and fragment
884 * @param $query \type{\string} an optional query string
885 * @return \type{\string} the URL
887 public function escapeFullURL( $query = '' ) {
888 return htmlspecialchars( $this->getFullURL( $query ) );
892 * Get the URL form for an internal link.
893 * - Used in various Squid-related code, in case we have a different
894 * internal hostname for the server from the exposed one.
896 * @param $query \type{\string} an optional query string
897 * @param $variant \type{\string} language variant of url (for sr, zh..)
898 * @return \type{\string} the URL
900 public function getInternalURL( $query = '', $variant = false ) {
901 global $wgInternalServer;
902 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
903 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
908 * Get the edit URL for this Title
909 * @return \type{\string} the URL, or a null string if this is an
912 public function getEditURL() {
913 if ( '' != $this->mInterwiki
) { return ''; }
914 $s = $this->getLocalURL( 'action=edit' );
920 * Get the HTML-escaped displayable text form.
921 * Used for the title field in <a> tags.
922 * @return \type{\string} the text, including any prefixes
924 public function getEscapedText() {
925 return htmlspecialchars( $this->getPrefixedText() );
929 * Is this Title interwiki?
930 * @return \type{\bool}
932 public function isExternal() { return ( '' != $this->mInterwiki
); }
935 * Is this page "semi-protected" - the *only* protection is autoconfirm?
937 * @param @action \type{\string} Action to check (default: edit)
938 * @return \type{\bool}
940 public function isSemiProtected( $action = 'edit' ) {
941 if( $this->exists() ) {
942 $restrictions = $this->getRestrictions( $action );
943 if( count( $restrictions ) > 0 ) {
944 foreach( $restrictions as $restriction ) {
945 if( strtolower( $restriction ) != 'autoconfirmed' )
954 # If it doesn't exist, it can't be protected
960 * Does the title correspond to a protected article?
961 * @param $what \type{\string} the action the page is protected from,
962 * by default checks all actions.
963 * @return \type{\bool}
965 public function isProtected( $action = '' ) {
966 global $wgRestrictionLevels;
968 $restrictionTypes = $this->getRestrictionTypes();
970 # Special pages have inherent protection
971 if( $this->getNamespace() == NS_SPECIAL
)
974 # Check regular protection levels
975 foreach( $restrictionTypes as $type ){
976 if( $action == $type ||
$action == '' ) {
977 $r = $this->getRestrictions( $type );
978 foreach( $wgRestrictionLevels as $level ) {
979 if( in_array( $level, $r ) && $level != '' ) {
990 * Is $wgUser watching this page?
991 * @return \type{\bool}
993 public function userIsWatching() {
996 if ( is_null( $this->mWatched
) ) {
997 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
998 $this->mWatched
= false;
1000 $this->mWatched
= $wgUser->isWatched( $this );
1003 return $this->mWatched
;
1007 * Can $wgUser perform $action on this page?
1008 * This skips potentially expensive cascading permission checks
1009 * as well as avoids expensive error formatting
1011 * Suitable for use for nonessential UI controls in common cases, but
1012 * _not_ for functional access control.
1014 * May provide false positives, but should never provide a false negative.
1016 * @param $action \type{\string} action that permission needs to be checked for
1017 * @return \type{\bool}
1019 public function quickUserCan( $action ) {
1020 return $this->userCan( $action, false );
1024 * Determines if $wgUser is unable to edit this page because it has been protected
1025 * by $wgNamespaceProtection.
1027 * @return \type{\bool}
1029 public function isNamespaceProtected() {
1030 global $wgNamespaceProtection, $wgUser;
1031 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1032 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1033 if( $right != '' && !$wgUser->isAllowed( $right ) )
1041 * Can $wgUser perform $action on this page?
1042 * @param $action \type{\string} action that permission needs to be checked for
1043 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1044 * @return \type{\bool}
1046 public function userCan( $action, $doExpensiveQueries = true ) {
1048 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1052 * Can $user perform $action on this page?
1054 * FIXME: This *does not* check throttles (User::pingLimiter()).
1056 * @param $action \type{\string}action that permission needs to be checked for
1057 * @param $user \type{User} user to check
1058 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1059 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1060 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1062 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1063 if( !StubObject
::isRealObject( $user ) ) {
1064 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1066 $wgUser->_unstub( '', 5 );
1069 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1073 global $wgEmailConfirmToEdit;
1075 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1076 $errors[] = array( 'confirmedittext' );
1079 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1080 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1081 $block = $user->mBlock
;
1083 // This is from OutputPage::blockedPage
1084 // Copied at r23888 by werdna
1086 $id = $user->blockedBy();
1087 $reason = $user->blockedFor();
1088 if( $reason == '' ) {
1089 $reason = wfMsg( 'blockednoreason' );
1093 if ( is_numeric( $id ) ) {
1094 $name = User
::whoIs( $id );
1099 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1100 $blockid = $block->mId
;
1101 $blockExpiry = $user->mBlock
->mExpiry
;
1102 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1104 if ( $blockExpiry == 'infinity' ) {
1105 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1106 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1108 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1109 if ( strpos( $option, ':' ) == false )
1112 list ($show, $value) = explode( ":", $option );
1114 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1115 $blockExpiry = $show;
1120 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1123 $intended = $user->mBlock
->mAddress
;
1125 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1126 $blockid, $blockExpiry, $intended, $blockTimestamp );
1129 // Remove the errors being ignored.
1131 foreach( $errors as $index => $error ) {
1132 $error_key = is_array($error) ?
$error[0] : $error;
1134 if (in_array( $error_key, $ignoreErrors )) {
1135 unset($errors[$index]);
1143 * Can $user perform $action on this page? This is an internal function,
1144 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1145 * checks on wfReadOnly() and blocks)
1147 * @param $action \type{\string} action that permission needs to be checked for
1148 * @param $user \type{User} user to check
1149 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1150 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1151 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1153 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1154 wfProfileIn( __METHOD__
);
1158 // First stop is permissions checks, which fail most often, and which are easiest to test.
1159 if ( $action == 'move' ) {
1160 if( !$user->isAllowed( 'move-rootuserpages' )
1161 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1163 // Show user page-specific message only if the user can move other pages
1164 $errors[] = array( 'cant-move-user-page' );
1167 // Check if user is allowed to move files if it's a file
1168 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1169 $errors[] = array( 'movenotallowedfile' );
1172 if( !$user->isAllowed( 'move' ) ) {
1173 // User can't move anything
1174 global $wgGroupPermissions;
1175 $userCanMove = false;
1176 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1177 $userCanMove = $wgGroupPermissions['user']['move'];
1179 $autoconfirmedCanMove = false;
1180 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1181 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1183 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1184 // custom message if logged-in users without any special rights can move
1185 $errors[] = array ( 'movenologintext' );
1187 $errors[] = array ('movenotallowed');
1190 } elseif ( $action == 'create' ) {
1191 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1192 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1194 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1196 } elseif( $action == 'move-target' ) {
1197 if( !$user->isAllowed( 'move' ) ) {
1198 // User can't move anything
1199 $errors[] = array ('movenotallowed');
1200 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1201 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1203 // Show user page-specific message only if the user can move other pages
1204 $errors[] = array( 'cant-move-to-user-page' );
1206 } elseif( !$user->isAllowed( $action ) ) {
1209 // We avoid expensive display logic for quickUserCan's and such
1212 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1213 User
::getGroupsWithPermission( $action ) );
1217 $return = array( 'badaccess-groups',
1218 array( implode( ', ', $groups ), count( $groups ) ) );
1220 $return = array( "badaccess-group0" );
1222 $errors[] = $return;
1225 # Short-circuit point
1226 if( $short && count($errors) > 0 ) {
1227 wfProfileOut( __METHOD__
);
1231 // Use getUserPermissionsErrors instead
1232 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1233 wfProfileOut( __METHOD__
);
1234 return $result ?
array() : array( array( 'badaccess-group0' ) );
1236 // Check getUserPermissionsErrors hook
1237 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1238 if( is_array($result) && count($result) && !is_array($result[0]) )
1239 $errors[] = $result; # A single array representing an error
1240 else if( is_array($result) && is_array($result[0]) )
1241 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1242 else if( $result !== '' && is_string($result) )
1243 $errors[] = array($result); # A string representing a message-id
1244 else if( $result === false )
1245 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1247 # Short-circuit point
1248 if( $short && count($errors) > 0 ) {
1249 wfProfileOut( __METHOD__
);
1252 // Check getUserPermissionsErrorsExpensive hook
1253 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1254 if( is_array($result) && count($result) && !is_array($result[0]) )
1255 $errors[] = $result; # A single array representing an error
1256 else if( is_array($result) && is_array($result[0]) )
1257 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1258 else if( $result !== '' && is_string($result) )
1259 $errors[] = array($result); # A string representing a message-id
1260 else if( $result === false )
1261 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1263 # Short-circuit point
1264 if( $short && count($errors) > 0 ) {
1265 wfProfileOut( __METHOD__
);
1269 # Only 'createaccount' and 'execute' can be performed on
1270 # special pages, which don't actually exist in the DB.
1271 $specialOKActions = array( 'createaccount', 'execute' );
1272 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1273 $errors[] = array('ns-specialprotected');
1276 # Check $wgNamespaceProtection for restricted namespaces
1277 if( $this->isNamespaceProtected() ) {
1278 $ns = $this->getNamespace() == NS_MAIN ?
1279 wfMsg( 'nstab-main' ) : $this->getNsText();
1280 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1281 array('protectedinterface') : array( 'namespaceprotected', $ns );
1284 # Protect css/js subpages of user pages
1285 # XXX: this might be better using restrictions
1286 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1287 # and $this->userCanEditJsSubpage() from working
1288 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1289 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1290 && $action != 'patrol'
1291 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1293 $errors[] = array('customcssjsprotected');
1294 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1295 && $action != 'patrol'
1296 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1298 $errors[] = array('customcssjsprotected');
1301 # Check against page_restrictions table requirements on this
1302 # page. The user must possess all required rights for this action.
1303 foreach( $this->getRestrictions($action) as $right ) {
1304 // Backwards compatibility, rewrite sysop -> protect
1305 if( $right == 'sysop' ) {
1308 if( '' != $right && !$user->isAllowed( $right ) ) {
1309 // Users with 'editprotected' permission can edit protected pages
1310 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1311 // Users with 'editprotected' permission cannot edit protected pages
1312 // with cascading option turned on.
1313 if( $this->mCascadeRestriction
) {
1314 $errors[] = array( 'protectedpagetext', $right );
1317 $errors[] = array( 'protectedpagetext', $right );
1321 # Short-circuit point
1322 if( $short && count($errors) > 0 ) {
1323 wfProfileOut( __METHOD__
);
1327 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1328 # We /could/ use the protection level on the source page, but it's fairly ugly
1329 # as we have to establish a precedence hierarchy for pages included by multiple
1330 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1331 # as they could remove the protection anyway.
1332 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1333 # Cascading protection depends on more than this page...
1334 # Several cascading protected pages may include this page...
1335 # Check each cascading level
1336 # This is only for protection restrictions, not for all actions
1337 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1338 foreach( $restrictions[$action] as $right ) {
1339 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1340 if( '' != $right && !$user->isAllowed( $right ) ) {
1342 foreach( $cascadingSources as $page )
1343 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1344 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1349 # Short-circuit point
1350 if( $short && count($errors) > 0 ) {
1351 wfProfileOut( __METHOD__
);
1355 if( $action == 'protect' ) {
1356 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1357 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1361 if( $action == 'create' ) {
1362 $title_protection = $this->getTitleProtection();
1363 if( is_array($title_protection) ) {
1364 extract($title_protection); // is this extract() really needed?
1366 if( $pt_create_perm == 'sysop' ) {
1367 $pt_create_perm = 'protect'; // B/C
1369 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1370 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1373 } elseif( $action == 'move' ) {
1374 // Check for immobile pages
1375 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1376 // Specific message for this case
1377 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1378 } elseif( !$this->isMovable() ) {
1379 // Less specific message for rarer cases
1380 $errors[] = array( 'immobile-page' );
1382 } elseif( $action == 'move-target' ) {
1383 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1384 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1385 } elseif( !$this->isMovable() ) {
1386 $errors[] = array( 'immobile-target-page' );
1390 wfProfileOut( __METHOD__
);
1395 * Is this title subject to title protection?
1396 * @return \type{\mixed} An associative array representing any existent title
1397 * protection, or false if there's none.
1399 private function getTitleProtection() {
1400 // Can't protect pages in special namespaces
1401 if ( $this->getNamespace() < 0 ) {
1405 // Can't protect pages that exist.
1406 if ($this->exists()) {
1410 $dbr = wfGetDB( DB_SLAVE
);
1411 $res = $dbr->select( 'protected_titles', '*',
1412 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1415 if ($row = $dbr->fetchRow( $res )) {
1423 * Update the title protection status
1424 * @param $create_perm \type{\string} Permission required for creation
1425 * @param $reason \type{\string} Reason for protection
1426 * @param $expiry \type{\string} Expiry timestamp
1428 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1429 global $wgUser,$wgContLang;
1431 if ($create_perm == implode(',',$this->getRestrictions('create'))
1432 && $expiry == $this->mRestrictionsExpiry
['create']) {
1437 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1439 $dbw = wfGetDB( DB_MASTER
);
1441 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1443 $expiry_description = '';
1444 if ( $encodedExpiry != 'infinity' ) {
1445 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1446 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1449 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1452 # Update protection table
1453 if ($create_perm != '' ) {
1454 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1456 'pt_namespace' => $namespace,
1457 'pt_title' => $title,
1458 'pt_create_perm' => $create_perm,
1459 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1460 'pt_expiry' => $encodedExpiry,
1461 'pt_user' => $wgUser->getId(),
1462 'pt_reason' => $reason,
1466 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1467 'pt_title' => $title ), __METHOD__
);
1469 # Update the protection log
1470 if( $dbw->affectedRows() ) {
1471 $log = new LogPage( 'protect' );
1473 if( $create_perm ) {
1474 $params = array("[create=$create_perm] $expiry_description",'');
1475 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1477 $log->addEntry( 'unprotect', $this, $reason );
1485 * Remove any title protection due to page existing
1487 public function deleteTitleProtection() {
1488 $dbw = wfGetDB( DB_MASTER
);
1490 $dbw->delete( 'protected_titles',
1491 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1496 * Would anybody with sufficient privileges be able to move this page?
1497 * Some pages just aren't movable.
1499 * @return \type{\bool} TRUE or FALSE
1501 public function isMovable() {
1502 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1506 * Can $wgUser read this page?
1507 * @return \type{\bool} TRUE or FALSE
1508 * @todo fold these checks into userCan()
1510 public function userCanRead() {
1511 global $wgUser, $wgGroupPermissions;
1513 static $useShortcut = null;
1515 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1516 if( is_null( $useShortcut ) ) {
1517 global $wgRevokePermissions;
1518 $useShortcut = true;
1519 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1520 # Not a public wiki, so no shortcut
1521 $useShortcut = false;
1522 } elseif( !empty( $wgRevokePermissions ) ) {
1524 * Iterate through each group with permissions being revoked (key not included since we don't care
1525 * what the group name is), then check if the read permission is being revoked. If it is, then
1526 * we don't use the shortcut below since the user might not be able to read, even though anon
1527 * reading is allowed.
1529 foreach( $wgRevokePermissions as $perms ) {
1530 if( !empty( $perms['read'] ) ) {
1531 # We might be removing the read right from the user, so no shortcut
1532 $useShortcut = false;
1540 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1541 if ( $result !== null ) {
1545 # Shortcut for public wikis, allows skipping quite a bit of code
1549 if( $wgUser->isAllowed( 'read' ) ) {
1552 global $wgWhitelistRead;
1555 * Always grant access to the login page.
1556 * Even anons need to be able to log in.
1558 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1563 * Bail out if there isn't whitelist
1565 if( !is_array($wgWhitelistRead) ) {
1570 * Check for explicit whitelisting
1572 $name = $this->getPrefixedText();
1573 $dbName = $this->getPrefixedDBKey();
1574 // Check with and without underscores
1575 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1579 * Old settings might have the title prefixed with
1580 * a colon for main-namespace pages
1582 if( $this->getNamespace() == NS_MAIN
) {
1583 if( in_array( ':' . $name, $wgWhitelistRead ) )
1588 * If it's a special page, ditch the subpage bit
1591 if( $this->getNamespace() == NS_SPECIAL
) {
1592 $name = $this->getDBkey();
1593 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1594 if ( $name === false ) {
1595 # Invalid special page, but we show standard login required message
1599 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1600 if( in_array( $pure, $wgWhitelistRead, true ) )
1609 * Is this a talk page of some sort?
1610 * @return \type{\bool} TRUE or FALSE
1612 public function isTalkPage() {
1613 return MWNamespace
::isTalk( $this->getNamespace() );
1617 * Is this a subpage?
1618 * @return \type{\bool} TRUE or FALSE
1620 public function isSubpage() {
1621 return MWNamespace
::hasSubpages( $this->mNamespace
)
1622 ?
strpos( $this->getText(), '/' ) !== false
1627 * Does this have subpages? (Warning, usually requires an extra DB query.)
1628 * @return \type{\bool} TRUE or FALSE
1630 public function hasSubpages() {
1631 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1636 # We dynamically add a member variable for the purpose of this method
1637 # alone to cache the result. There's no point in having it hanging
1638 # around uninitialized in every Title object; therefore we only add it
1639 # if needed and don't declare it statically.
1640 if( isset( $this->mHasSubpages
) ) {
1641 return $this->mHasSubpages
;
1644 $subpages = $this->getSubpages( 1 );
1645 if( $subpages instanceof TitleArray
)
1646 return $this->mHasSubpages
= (bool)$subpages->count();
1647 return $this->mHasSubpages
= false;
1651 * Get all subpages of this page.
1652 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1653 * @return mixed TitleArray, or empty array if this page's namespace
1654 * doesn't allow subpages
1656 public function getSubpages( $limit = -1 ) {
1657 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1660 $dbr = wfGetDB( DB_SLAVE
);
1661 $conds['page_namespace'] = $this->getNamespace();
1662 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1665 $options['LIMIT'] = $limit;
1666 return $this->mSubpages
= TitleArray
::newFromResult(
1667 $dbr->select( 'page',
1668 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1677 * Could this page contain custom CSS or JavaScript, based
1680 * @return \type{\bool} TRUE or FALSE
1682 public function isCssOrJsPage() {
1683 return $this->mNamespace
== NS_MEDIAWIKI
1684 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1688 * Is this a .css or .js subpage of a user page?
1689 * @return \type{\bool} TRUE or FALSE
1691 public function isCssJsSubpage() {
1692 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1695 * Is this a *valid* .css or .js subpage of a user page?
1696 * Check that the corresponding skin exists
1697 * @return \type{\bool} TRUE or FALSE
1699 public function isValidCssJsSubpage() {
1700 if ( $this->isCssJsSubpage() ) {
1701 $skinNames = Skin
::getSkinNames();
1702 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1708 * Trim down a .css or .js subpage title to get the corresponding skin name
1710 public function getSkinFromCssJsSubpage() {
1711 $subpage = explode( '/', $this->mTextform
);
1712 $subpage = $subpage[ count( $subpage ) - 1 ];
1713 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1716 * Is this a .css subpage of a user page?
1717 * @return \type{\bool} TRUE or FALSE
1719 public function isCssSubpage() {
1720 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1723 * Is this a .js subpage of a user page?
1724 * @return \type{\bool} TRUE or FALSE
1726 public function isJsSubpage() {
1727 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1730 * Protect css subpages of user pages: can $wgUser edit
1733 * @return \type{\bool} TRUE or FALSE
1734 * @todo XXX: this might be better using restrictions
1736 public function userCanEditCssSubpage() {
1738 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1739 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1742 * Protect js subpages of user pages: can $wgUser edit
1745 * @return \type{\bool} TRUE or FALSE
1746 * @todo XXX: this might be better using restrictions
1748 public function userCanEditJsSubpage() {
1750 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1751 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1755 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1757 * @return \type{\bool} If the page is subject to cascading restrictions.
1759 public function isCascadeProtected() {
1760 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1761 return ( $sources > 0 );
1765 * Cascading protection: Get the source of any cascading restrictions on this page.
1767 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1768 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1769 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1770 * The restriction array is an array of each type, each of which contains an array of unique groups.
1772 public function getCascadeProtectionSources( $get_pages = true ) {
1773 $pagerestrictions = array();
1775 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1776 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1777 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1778 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1781 wfProfileIn( __METHOD__
);
1783 $dbr = wfGetDB( DB_SLAVE
);
1785 if ( $this->getNamespace() == NS_FILE
) {
1786 $tables = array ('imagelinks', 'page_restrictions');
1787 $where_clauses = array(
1788 'il_to' => $this->getDBkey(),
1790 'pr_cascade' => 1 );
1792 $tables = array ('templatelinks', 'page_restrictions');
1793 $where_clauses = array(
1794 'tl_namespace' => $this->getNamespace(),
1795 'tl_title' => $this->getDBkey(),
1797 'pr_cascade' => 1 );
1801 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1802 $where_clauses[] = 'page_id=pr_page';
1805 $cols = array( 'pr_expiry' );
1808 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1810 $sources = $get_pages ?
array() : false;
1811 $now = wfTimestampNow();
1812 $purgeExpired = false;
1814 foreach( $res as $row ) {
1815 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1816 if( $expiry > $now ) {
1818 $page_id = $row->pr_page
;
1819 $page_ns = $row->page_namespace
;
1820 $page_title = $row->page_title
;
1821 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1822 # Add groups needed for each restriction type if its not already there
1823 # Make sure this restriction type still exists
1825 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1826 $pagerestrictions[$row->pr_type
] = array();
1829 if ( isset($pagerestrictions[$row->pr_type
]) &&
1830 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1831 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1837 // Trigger lazy purge of expired restrictions from the db
1838 $purgeExpired = true;
1841 if( $purgeExpired ) {
1842 Title
::purgeExpiredRestrictions();
1845 wfProfileOut( __METHOD__
);
1848 $this->mCascadeSources
= $sources;
1849 $this->mCascadingRestrictions
= $pagerestrictions;
1851 $this->mHasCascadingRestrictions
= $sources;
1853 return array( $sources, $pagerestrictions );
1856 function areRestrictionsCascading() {
1857 if (!$this->mRestrictionsLoaded
) {
1858 $this->loadRestrictions();
1861 return $this->mCascadeRestriction
;
1865 * Loads a string into mRestrictions array
1866 * @param $res \type{Resource} restrictions as an SQL result.
1868 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1870 $dbr = wfGetDB( DB_SLAVE
);
1872 while( $row = $dbr->fetchObject( $res ) ) {
1876 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1879 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1880 $dbr = wfGetDB( DB_SLAVE
);
1882 $restrictionTypes = $this->getRestrictionTypes();
1884 foreach( $restrictionTypes as $type ){
1885 $this->mRestrictions
[$type] = array();
1886 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1889 $this->mCascadeRestriction
= false;
1891 # Backwards-compatibility: also load the restrictions from the page record (old format).
1893 if ( $oldFashionedRestrictions === null ) {
1894 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1895 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1898 if ($oldFashionedRestrictions != '') {
1900 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1901 $temp = explode( '=', trim( $restrict ) );
1902 if(count($temp) == 1) {
1903 // old old format should be treated as edit/move restriction
1904 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1905 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1907 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1911 $this->mOldRestrictions
= true;
1915 if( count($rows) ) {
1916 # Current system - load second to make them override.
1917 $now = wfTimestampNow();
1918 $purgeExpired = false;
1920 foreach( $rows as $row ) {
1921 # Cycle through all the restrictions.
1923 // Don't take care of restrictions types that aren't allowed
1925 if( !in_array( $row->pr_type
, $restrictionTypes ) )
1928 // This code should be refactored, now that it's being used more generally,
1929 // But I don't really see any harm in leaving it in Block for now -werdna
1930 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1932 // Only apply the restrictions if they haven't expired!
1933 if ( !$expiry ||
$expiry > $now ) {
1934 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1935 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1937 $this->mCascadeRestriction |
= $row->pr_cascade
;
1939 // Trigger a lazy purge of expired restrictions
1940 $purgeExpired = true;
1944 if( $purgeExpired ) {
1945 Title
::purgeExpiredRestrictions();
1949 $this->mRestrictionsLoaded
= true;
1953 * Load restrictions from the page_restrictions table
1955 public function loadRestrictions( $oldFashionedRestrictions = null ) {
1956 if( !$this->mRestrictionsLoaded
) {
1957 if ($this->exists()) {
1958 $dbr = wfGetDB( DB_SLAVE
);
1960 $res = $dbr->select( 'page_restrictions', '*',
1961 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1963 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
1965 $title_protection = $this->getTitleProtection();
1967 if (is_array($title_protection)) {
1968 extract($title_protection);
1970 $now = wfTimestampNow();
1971 $expiry = Block
::decodeExpiry($pt_expiry);
1973 if (!$expiry ||
$expiry > $now) {
1974 // Apply the restrictions
1975 $this->mRestrictionsExpiry
['create'] = $expiry;
1976 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1977 } else { // Get rid of the old restrictions
1978 Title
::purgeExpiredRestrictions();
1981 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1983 $this->mRestrictionsLoaded
= true;
1989 * Purge expired restrictions from the page_restrictions table
1991 static function purgeExpiredRestrictions() {
1992 $dbw = wfGetDB( DB_MASTER
);
1993 $dbw->delete( 'page_restrictions',
1994 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1997 $dbw->delete( 'protected_titles',
1998 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2003 * Accessor/initialisation for mRestrictions
2005 * @param $action \type{\string} action that permission needs to be checked for
2006 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2008 public function getRestrictions( $action ) {
2009 if( !$this->mRestrictionsLoaded
) {
2010 $this->loadRestrictions();
2012 return isset( $this->mRestrictions
[$action] )
2013 ?
$this->mRestrictions
[$action]
2018 * Get the expiry time for the restriction against a given action
2019 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2020 * or not protected at all, or false if the action is not recognised.
2022 public function getRestrictionExpiry( $action ) {
2023 if( !$this->mRestrictionsLoaded
) {
2024 $this->loadRestrictions();
2026 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2030 * Is there a version of this page in the deletion archive?
2031 * @return \type{\int} the number of archived revisions
2033 public function isDeleted() {
2034 if( $this->getNamespace() < 0 ) {
2037 $dbr = wfGetDB( DB_SLAVE
);
2038 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2039 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2042 if( $this->getNamespace() == NS_FILE
) {
2043 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2044 array( 'fa_name' => $this->getDBkey() ),
2053 * Is there a version of this page in the deletion archive?
2056 public function isDeletedQuick() {
2057 if( $this->getNamespace() < 0 ) {
2060 $dbr = wfGetDB( DB_SLAVE
);
2061 $deleted = (bool)$dbr->selectField( 'archive', '1',
2062 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2065 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2066 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2067 array( 'fa_name' => $this->getDBkey() ),
2075 * Get the article ID for this Title from the link cache,
2076 * adding it if necessary
2077 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2079 * @return \type{\int} the ID
2081 public function getArticleID( $flags = 0 ) {
2082 if( $this->getNamespace() < 0 ) {
2083 return $this->mArticleID
= 0;
2085 $linkCache = LinkCache
::singleton();
2086 if( $flags & GAID_FOR_UPDATE
) {
2087 $oldUpdate = $linkCache->forUpdate( true );
2088 $linkCache->clearLink( $this );
2089 $this->mArticleID
= $linkCache->addLinkObj( $this );
2090 $linkCache->forUpdate( $oldUpdate );
2092 if( -1 == $this->mArticleID
) {
2093 $this->mArticleID
= $linkCache->addLinkObj( $this );
2096 return $this->mArticleID
;
2100 * Is this an article that is a redirect page?
2101 * Uses link cache, adding it if necessary
2102 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2103 * @return \type{\bool}
2105 public function isRedirect( $flags = 0 ) {
2106 if( !is_null($this->mRedirect
) )
2107 return $this->mRedirect
;
2108 # Calling getArticleID() loads the field from cache as needed
2109 if( !$this->getArticleID($flags) ) {
2110 return $this->mRedirect
= false;
2112 $linkCache = LinkCache
::singleton();
2113 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2115 return $this->mRedirect
;
2119 * What is the length of this page?
2120 * Uses link cache, adding it if necessary
2121 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2122 * @return \type{\bool}
2124 public function getLength( $flags = 0 ) {
2125 if( $this->mLength
!= -1 )
2126 return $this->mLength
;
2127 # Calling getArticleID() loads the field from cache as needed
2128 if( !$this->getArticleID($flags) ) {
2129 return $this->mLength
= 0;
2131 $linkCache = LinkCache
::singleton();
2132 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2134 return $this->mLength
;
2138 * What is the page_latest field for this page?
2139 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2140 * @return \type{\int} or false if the page doesn't exist
2142 public function getLatestRevID( $flags = 0 ) {
2143 if( $this->mLatestID
!== false )
2144 return $this->mLatestID
;
2146 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2147 $this->mLatestID
= $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2148 return $this->mLatestID
;
2152 * This clears some fields in this object, and clears any associated
2153 * keys in the "bad links" section of the link cache.
2155 * - This is called from Article::insertNewArticle() to allow
2156 * loading of the new page_id. It's also called from
2157 * Article::doDeleteArticle()
2159 * @param $newid \type{\int} the new Article ID
2161 public function resetArticleID( $newid ) {
2162 $linkCache = LinkCache
::singleton();
2163 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2165 if ( $newid === false ) { $this->mArticleID
= -1; }
2166 else { $this->mArticleID
= intval( $newid ); }
2167 $this->mRestrictionsLoaded
= false;
2168 $this->mRestrictions
= array();
2172 * Updates page_touched for this page; called from LinksUpdate.php
2173 * @return \type{\bool} true if the update succeded
2175 public function invalidateCache() {
2176 if( wfReadOnly() ) {
2179 $dbw = wfGetDB( DB_MASTER
);
2180 $success = $dbw->update( 'page',
2181 array( 'page_touched' => $dbw->timestamp() ),
2185 HTMLFileCache
::clearFileCache( $this );
2190 * Prefix some arbitrary text with the namespace or interwiki prefix
2193 * @param $name \type{\string} the text
2194 * @return \type{\string} the prefixed text
2197 /* private */ function prefix( $name ) {
2199 if ( '' != $this->mInterwiki
) {
2200 $p = $this->mInterwiki
. ':';
2202 if ( 0 != $this->mNamespace
) {
2203 $p .= $this->getNsText() . ':';
2208 // Returns a simple regex that will match on characters and sequences invalid in titles.
2209 // Note that this doesn't pick up many things that could be wrong with titles, but that
2210 // replacing this regex with something valid will make many titles valid.
2211 static function getTitleInvalidRegex() {
2212 static $rxTc = false;
2214 # Matching titles will be held as illegal.
2216 # Any character not allowed is forbidden...
2217 '[^' . Title
::legalChars() . ']' .
2218 # URL percent encoding sequences interfere with the ability
2219 # to round-trip titles -- you can't link to them consistently.
2220 '|%[0-9A-Fa-f]{2}' .
2221 # XML/HTML character references produce similar issues.
2222 '|&[A-Za-z0-9\x80-\xff]+;' .
2224 '|&#x[0-9A-Fa-f]+;' .
2232 * Capitalize a text if it belongs to a namespace that capitalizes
2234 public static function capitalize( $text, $ns = NS_MAIN
) {
2237 if ( MWNamespace
::isCapitalized( $ns ) )
2238 return $wgContLang->ucfirst( $text );
2244 * Secure and split - main initialisation function for this object
2246 * Assumes that mDbkeyform has been set, and is urldecoded
2247 * and uses underscores, but not otherwise munged. This function
2248 * removes illegal characters, splits off the interwiki and
2249 * namespace prefixes, sets the other forms, and canonicalizes
2251 * @return \type{\bool} true on success
2253 private function secureAndSplit() {
2254 global $wgContLang, $wgLocalInterwiki;
2257 $rxTc = self
::getTitleInvalidRegex();
2259 $this->mInterwiki
= $this->mFragment
= '';
2260 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2262 $dbkey = $this->mDbkeyform
;
2264 # Strip Unicode bidi override characters.
2265 # Sometimes they slip into cut-n-pasted page titles, where the
2266 # override chars get included in list displays.
2267 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2269 # Clean up whitespace
2270 # Note: use of the /u option on preg_replace here will cause
2271 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2272 # conveniently disabling them.
2274 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2275 $dbkey = trim( $dbkey, '_' );
2277 if ( '' == $dbkey ) {
2281 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2282 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2286 $this->mDbkeyform
= $dbkey;
2288 # Initial colon indicates main namespace rather than specified default
2289 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2290 if ( ':' == $dbkey{0} ) {
2291 $this->mNamespace
= NS_MAIN
;
2292 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2293 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2296 # Namespace or interwiki prefix
2298 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2301 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2303 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2304 # Ordinary namespace
2306 $this->mNamespace
= $ns;
2307 # For Talk:X pages, check if X has a "namespace" prefix
2308 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2309 if( $wgContLang->getNsIndex( $x[1] ) )
2310 return false; # Disallow Talk:File:x type titles...
2311 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2312 return false; # Disallow Talk:Interwiki:x type titles...
2314 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2316 # Can't make a local interwiki link to an interwiki link.
2317 # That's just crazy!
2323 $this->mInterwiki
= $wgContLang->lc( $p );
2325 # Redundant interwiki prefix to the local wiki
2326 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2327 if( $dbkey == '' ) {
2328 # Can't have an empty self-link
2331 $this->mInterwiki
= '';
2333 # Do another namespace split...
2337 # If there's an initial colon after the interwiki, that also
2338 # resets the default namespace
2339 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2340 $this->mNamespace
= NS_MAIN
;
2341 $dbkey = substr( $dbkey, 1 );
2344 # If there's no recognized interwiki or namespace,
2345 # then let the colon expression be part of the title.
2350 # We already know that some pages won't be in the database!
2352 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2353 $this->mArticleID
= 0;
2355 $fragment = strstr( $dbkey, '#' );
2356 if ( false !== $fragment ) {
2357 $this->setFragment( $fragment );
2358 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2359 # remove whitespace again: prevents "Foo_bar_#"
2360 # becoming "Foo_bar_"
2361 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2364 # Reject illegal characters.
2366 if( preg_match( $rxTc, $dbkey ) ) {
2371 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2372 * reachable due to the way web browsers deal with 'relative' URLs.
2373 * Also, they conflict with subpage syntax. Forbid them explicitly.
2375 if ( strpos( $dbkey, '.' ) !== false &&
2376 ( $dbkey === '.' ||
$dbkey === '..' ||
2377 strpos( $dbkey, './' ) === 0 ||
2378 strpos( $dbkey, '../' ) === 0 ||
2379 strpos( $dbkey, '/./' ) !== false ||
2380 strpos( $dbkey, '/../' ) !== false ||
2381 substr( $dbkey, -2 ) == '/.' ||
2382 substr( $dbkey, -3 ) == '/..' ) )
2388 * Magic tilde sequences? Nu-uh!
2390 if( strpos( $dbkey, '~~~' ) !== false ) {
2395 * Limit the size of titles to 255 bytes.
2396 * This is typically the size of the underlying database field.
2397 * We make an exception for special pages, which don't need to be stored
2398 * in the database, and may edge over 255 bytes due to subpage syntax
2399 * for long titles, e.g. [[Special:Block/Long name]]
2401 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2402 strlen( $dbkey ) > 512 )
2408 * Normally, all wiki links are forced to have
2409 * an initial capital letter so [[foo]] and [[Foo]]
2410 * point to the same place.
2412 * Don't force it for interwikis, since the other
2413 * site might be case-sensitive.
2415 $this->mUserCaseDBKey
= $dbkey;
2416 if( $this->mInterwiki
== '') {
2417 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2421 * Can't make a link to a namespace alone...
2422 * "empty" local links can only be self-links
2423 * with a fragment identifier.
2426 $this->mInterwiki
== '' &&
2427 $this->mNamespace
!= NS_MAIN
) {
2430 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2431 // IP names are not allowed for accounts, and can only be referring to
2432 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2433 // there are numerous ways to present the same IP. Having sp:contribs scan
2434 // them all is silly and having some show the edits and others not is
2435 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2436 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2437 IP
::sanitizeIP( $dbkey ) : $dbkey;
2438 // Any remaining initial :s are illegal.
2439 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2444 $this->mDbkeyform
= $dbkey;
2445 $this->mUrlform
= wfUrlencode( $dbkey );
2447 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2453 * Set the fragment for this title. Removes the first character from the
2454 * specified fragment before setting, so it assumes you're passing it with
2457 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2458 * Still in active use privately.
2460 * @param $fragment \type{\string} text
2462 public function setFragment( $fragment ) {
2463 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2467 * Get a Title object associated with the talk page of this article
2468 * @return \type{Title} the object for the talk page
2470 public function getTalkPage() {
2471 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2475 * Get a title object associated with the subject page of this
2478 * @return \type{Title} the object for the subject page
2480 public function getSubjectPage() {
2481 // Is this the same title?
2482 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2483 if( $this->getNamespace() == $subjectNS ) {
2486 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2490 * Get an array of Title objects linking to this Title
2491 * Also stores the IDs in the link cache.
2493 * WARNING: do not use this function on arbitrary user-supplied titles!
2494 * On heavily-used templates it will max out the memory.
2496 * @param array $options may be FOR UPDATE
2497 * @return \type{\arrayof{Title}} the Title objects linking here
2499 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2500 $linkCache = LinkCache
::singleton();
2502 if ( count( $options ) > 0 ) {
2503 $db = wfGetDB( DB_MASTER
);
2505 $db = wfGetDB( DB_SLAVE
);
2508 $res = $db->select( array( 'page', $table ),
2509 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2511 "{$prefix}_from=page_id",
2512 "{$prefix}_namespace" => $this->getNamespace(),
2513 "{$prefix}_title" => $this->getDBkey() ),
2518 if ( $db->numRows( $res ) ) {
2519 foreach( $res as $row ) {
2520 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2521 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2522 $retVal[] = $titleObj;
2526 $db->freeResult( $res );
2531 * Get an array of Title objects using this Title as a template
2532 * Also stores the IDs in the link cache.
2534 * WARNING: do not use this function on arbitrary user-supplied titles!
2535 * On heavily-used templates it will max out the memory.
2537 * @param array $options may be FOR UPDATE
2538 * @return \type{\arrayof{Title}} the Title objects linking here
2540 public function getTemplateLinksTo( $options = array() ) {
2541 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2545 * Get an array of Title objects referring to non-existent articles linked from this page
2547 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2548 * @return \type{\arrayof{Title}} the Title objects
2550 public function getBrokenLinksFrom() {
2551 if ( $this->getArticleId() == 0 ) {
2552 # All links from article ID 0 are false positives
2556 $dbr = wfGetDB( DB_SLAVE
);
2557 $res = $dbr->select(
2558 array( 'page', 'pagelinks' ),
2559 array( 'pl_namespace', 'pl_title' ),
2561 'pl_from' => $this->getArticleId(),
2562 'page_namespace IS NULL'
2564 __METHOD__
, array(),
2568 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2574 foreach( $res as $row ) {
2575 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2582 * Get a list of URLs to purge from the Squid cache when this
2585 * @return \type{\arrayof{\string}} the URLs
2587 public function getSquidURLs() {
2591 $this->getInternalURL(),
2592 $this->getInternalURL( 'action=history' )
2595 // purge variant urls as well
2596 if($wgContLang->hasVariants()){
2597 $variants = $wgContLang->getVariants();
2598 foreach($variants as $vCode){
2599 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2600 $urls[] = $this->getInternalURL('',$vCode);
2608 * Purge all applicable Squid URLs
2610 public function purgeSquid() {
2612 if ( $wgUseSquid ) {
2613 $urls = $this->getSquidURLs();
2614 $u = new SquidUpdate( $urls );
2620 * Move this page without authentication
2621 * @param &$nt \type{Title} the new page Title
2623 public function moveNoAuth( &$nt ) {
2624 return $this->moveTo( $nt, false );
2628 * Check whether a given move operation would be valid.
2629 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2630 * @param &$nt \type{Title} the new title
2631 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2633 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2634 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2636 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2641 // Normally we'd add this to $errors, but we'll get
2642 // lots of syntax errors if $nt is not an object
2643 return array(array('badtitletext'));
2645 if( $this->equals( $nt ) ) {
2646 $errors[] = array('selfmove');
2648 if( !$this->isMovable() ) {
2649 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2651 if ( $nt->getInterwiki() != '' ) {
2652 $errors[] = array( 'immobile-target-namespace-iw' );
2654 if ( !$nt->isMovable() ) {
2655 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2658 $oldid = $this->getArticleID();
2659 $newid = $nt->getArticleID();
2661 if ( strlen( $nt->getDBkey() ) < 1 ) {
2662 $errors[] = array('articleexists');
2664 if ( ( '' == $this->getDBkey() ) ||
2666 ( '' == $nt->getDBkey() ) ) {
2667 $errors[] = array('badarticleerror');
2670 // Image-specific checks
2671 if( $this->getNamespace() == NS_FILE
) {
2672 $file = wfLocalFile( $this );
2673 if( $file->exists() ) {
2674 if( $nt->getNamespace() != NS_FILE
) {
2675 $errors[] = array('imagenocrossnamespace');
2677 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2678 $errors[] = array('imageinvalidfilename');
2680 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2681 $errors[] = array('imagetypemismatch');
2684 $destfile = wfLocalFile( $nt );
2685 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2686 $errors[] = array( 'file-exists-sharedrepo' );
2692 $errors = wfMergeErrorArrays( $errors,
2693 $this->getUserPermissionsErrors('move', $wgUser),
2694 $this->getUserPermissionsErrors('edit', $wgUser),
2695 $nt->getUserPermissionsErrors('move-target', $wgUser),
2696 $nt->getUserPermissionsErrors('edit', $wgUser) );
2699 $match = EditPage
::matchSummarySpamRegex( $reason );
2700 if( $match !== false ) {
2701 // This is kind of lame, won't display nice
2702 $errors[] = array('spamprotectiontext');
2706 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2707 $errors[] = array('hookaborted', $err);
2710 # The move is allowed only if (1) the target doesn't exist, or
2711 # (2) the target is a redirect to the source, and has no history
2712 # (so we can undo bad moves right after they're done).
2714 if ( 0 != $newid ) { # Target exists; check for validity
2715 if ( ! $this->isValidMoveTarget( $nt ) ) {
2716 $errors[] = array('articleexists');
2719 $tp = $nt->getTitleProtection();
2720 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2721 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2722 $errors[] = array('cantmove-titleprotected');
2731 * Move a title to a new location
2732 * @param &$nt \type{Title} the new title
2733 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2735 * @param $reason \type{\string} The reason for the move
2736 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2737 * Ignored if the user doesn't have the suppressredirect right.
2738 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2740 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2741 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2742 if( is_array( $err ) ) {
2746 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2747 $dbw = wfGetDB( DB_MASTER
);
2748 if( $this->getNamespace() == NS_FILE
) {
2749 $file = wfLocalFile( $this );
2750 if( $file->exists() ) {
2751 $status = $file->move( $nt );
2752 if( !$status->isOk() ) {
2753 return $status->getErrorsArray();
2758 $pageid = $this->getArticleID();
2759 $protected = $this->isProtected();
2760 if( $nt->exists() ) {
2761 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2762 $pageCountChange = ($createRedirect ?
0 : -1);
2763 } else { # Target didn't exist, do normal move.
2764 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2765 $pageCountChange = ($createRedirect ?
1 : 0);
2768 if( is_array( $err ) ) {
2771 $redirid = $this->getArticleID();
2773 // Category memberships include a sort key which may be customized.
2774 // If it's left as the default (the page title), we need to update
2775 // the sort key to match the new title.
2777 // Be careful to avoid resetting cl_timestamp, which may disturb
2778 // time-based lists on some sites.
2780 // Warning -- if the sort key is *explicitly* set to the old title,
2781 // we can't actually distinguish it from a default here, and it'll
2782 // be set to the new title even though it really shouldn't.
2783 // It'll get corrected on the next edit, but resetting cl_timestamp.
2784 $dbw->update( 'categorylinks',
2786 'cl_sortkey' => $nt->getPrefixedText(),
2787 'cl_timestamp=cl_timestamp' ),
2789 'cl_from' => $pageid,
2790 'cl_sortkey' => $this->getPrefixedText() ),
2794 # Protect the redirect title as the title used to be...
2795 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2797 'pr_page' => $redirid,
2798 'pr_type' => 'pr_type',
2799 'pr_level' => 'pr_level',
2800 'pr_cascade' => 'pr_cascade',
2801 'pr_user' => 'pr_user',
2802 'pr_expiry' => 'pr_expiry'
2804 array( 'pr_page' => $pageid ),
2808 # Update the protection log
2809 $log = new LogPage( 'protect' );
2810 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2811 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2812 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2816 $oldnamespace = $this->getNamespace() & ~
1;
2817 $newnamespace = $nt->getNamespace() & ~
1;
2818 $oldtitle = $this->getDBkey();
2819 $newtitle = $nt->getDBkey();
2821 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2822 WatchedItem
::duplicateEntries( $this, $nt );
2825 # Update search engine
2826 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2828 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2832 if( $this->isContentPage() && !$nt->isContentPage() ) {
2833 # No longer a content page
2834 # Not viewed, edited, removing
2835 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2836 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2837 # Now a content page
2838 # Not viewed, edited, adding
2839 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2840 } elseif( $pageCountChange ) {
2842 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2849 # Update message cache for interface messages
2850 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2851 global $wgMessageCache;
2853 # @bug 17860: old article can be deleted, if this the case,
2854 # delete it from message cache
2855 if ( $this->getArticleID() === 0 ) {
2856 $wgMessageCache->replace( $this->getDBkey(), false );
2858 $oldarticle = new Article( $this );
2859 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2862 $newarticle = new Article( $nt );
2863 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2867 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2872 * Move page to a title which is at present a redirect to the
2875 * @param &$nt \type{Title} the page to move to, which should currently
2877 * @param $reason \type{\string} The reason for the move
2878 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2879 * Ignored if the user doesn't have the suppressredirect right
2881 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2882 global $wgUseSquid, $wgUser;
2884 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2887 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2890 $now = wfTimestampNow();
2891 $newid = $nt->getArticleID();
2892 $oldid = $this->getArticleID();
2893 $latest = $this->getLatestRevID();
2895 $dbw = wfGetDB( DB_MASTER
);
2897 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
2898 $newns = $nt->getNamespace();
2899 $newdbk = $nt->getDBkey();
2901 # Delete the old redirect. We don't save it to history since
2902 # by definition if we've got here it's rather uninteresting.
2903 # We have to remove it so that the next step doesn't trigger
2904 # a conflict on the unique namespace+title index...
2905 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
2906 if ( !$dbw->cascadingDeletes() ) {
2907 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2908 global $wgUseTrackbacks;
2909 if ($wgUseTrackbacks)
2910 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2911 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2912 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2913 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2914 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2915 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2916 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2917 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2919 // If the redirect was recently created, it may have an entry in recentchanges still
2920 $dbw->delete( 'recentchanges',
2921 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
2925 # Save a null revision in the page's history notifying of the move
2926 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2927 $nullRevId = $nullRevision->insertOn( $dbw );
2929 $article = new Article( $this );
2930 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2932 # Change the name of the target page:
2933 $dbw->update( 'page',
2935 'page_touched' => $dbw->timestamp($now),
2936 'page_namespace' => $nt->getNamespace(),
2937 'page_title' => $nt->getDBkey(),
2938 'page_latest' => $nullRevId,
2940 /* WHERE */ array( 'page_id' => $oldid ),
2943 $nt->resetArticleID( $oldid );
2945 # Recreate the redirect, this time in the other direction.
2946 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2947 $mwRedir = MagicWord
::get( 'redirect' );
2948 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2949 $redirectArticle = new Article( $this );
2950 $newid = $redirectArticle->insertOn( $dbw );
2951 $redirectRevision = new Revision( array(
2953 'comment' => $comment,
2954 'text' => $redirectText ) );
2955 $redirectRevision->insertOn( $dbw );
2956 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2958 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2960 # Now, we record the link from the redirect to the new title.
2961 # It should have no other outgoing links...
2962 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2963 $dbw->insert( 'pagelinks',
2965 'pl_from' => $newid,
2966 'pl_namespace' => $nt->getNamespace(),
2967 'pl_title' => $nt->getDBkey() ),
2969 $redirectSuppressed = false;
2971 $this->resetArticleID( 0 );
2972 $redirectSuppressed = true;
2976 $log = new LogPage( 'move' );
2977 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2980 if ( $wgUseSquid ) {
2981 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2982 $u = new SquidUpdate( $urls );
2989 * Move page to non-existing title.
2990 * @param &$nt \type{Title} the new Title
2991 * @param $reason \type{\string} The reason for the move
2992 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2993 * Ignored if the user doesn't have the suppressredirect right
2995 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2996 global $wgUseSquid, $wgUser;
2998 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3000 $comment .= wfMsgExt( 'colon-separator',
3001 array( 'escapenoentities', 'content' ) );
3002 $comment .= $reason;
3005 $newid = $nt->getArticleID();
3006 $oldid = $this->getArticleID();
3007 $latest = $this->getLatestRevId();
3009 $dbw = wfGetDB( DB_MASTER
);
3010 $now = $dbw->timestamp();
3012 # Save a null revision in the page's history notifying of the move
3013 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3014 if ( !is_object( $nullRevision ) ) {
3015 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3017 $nullRevId = $nullRevision->insertOn( $dbw );
3019 $article = new Article( $this );
3020 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3023 $dbw->update( 'page',
3025 'page_touched' => $now,
3026 'page_namespace' => $nt->getNamespace(),
3027 'page_title' => $nt->getDBkey(),
3028 'page_latest' => $nullRevId,
3030 /* WHERE */ array( 'page_id' => $oldid ),
3033 $nt->resetArticleID( $oldid );
3035 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3037 $mwRedir = MagicWord
::get( 'redirect' );
3038 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3039 $redirectArticle = new Article( $this );
3040 $newid = $redirectArticle->insertOn( $dbw );
3041 $redirectRevision = new Revision( array(
3043 'comment' => $comment,
3044 'text' => $redirectText ) );
3045 $redirectRevision->insertOn( $dbw );
3046 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3048 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3050 # Record the just-created redirect's linking to the page
3051 $dbw->insert( 'pagelinks',
3053 'pl_from' => $newid,
3054 'pl_namespace' => $nt->getNamespace(),
3055 'pl_title' => $nt->getDBkey() ),
3057 $redirectSuppressed = false;
3059 $this->resetArticleID( 0 );
3060 $redirectSuppressed = true;
3064 $log = new LogPage( 'move' );
3065 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3067 # Purge caches as per article creation
3068 Article
::onArticleCreate( $nt );
3070 # Purge old title from squid
3071 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3072 $this->purgeSquid();
3077 * Move this page's subpages to be subpages of $nt
3078 * @param $nt Title Move target
3079 * @param $auth bool Whether $wgUser's permissions should be checked
3080 * @param $reason string The reason for the move
3081 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3082 * Ignored if the user doesn't have the 'suppressredirect' right
3083 * @return mixed array with old page titles as keys, and strings (new page titles) or
3084 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3086 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3087 global $wgMaximumMovedPages;
3088 // Check permissions
3089 if( !$this->userCan( 'move-subpages' ) )
3090 return array( 'cant-move-subpages' );
3091 // Do the source and target namespaces support subpages?
3092 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3093 return array( 'namespace-nosubpages',
3094 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3095 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3096 return array( 'namespace-nosubpages',
3097 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3099 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3102 foreach( $subpages as $oldSubpage ) {
3104 if( $count > $wgMaximumMovedPages ) {
3105 $retval[$oldSubpage->getPrefixedTitle()] =
3106 array( 'movepage-max-pages',
3107 $wgMaximumMovedPages );
3111 // We don't know whether this function was called before
3112 // or after moving the root page, so check both
3114 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3115 $oldSubpage->getArticleID() == $nt->getArticleId() )
3116 // When moving a page to a subpage of itself,
3117 // don't move it twice
3119 $newPageName = preg_replace(
3120 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3121 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3122 $oldSubpage->getDBkey() );
3123 if( $oldSubpage->isTalkPage() ) {
3124 $newNs = $nt->getTalkPage()->getNamespace();
3126 $newNs = $nt->getSubjectPage()->getNamespace();
3128 # Bug 14385: we need makeTitleSafe because the new page names may
3129 # be longer than 255 characters.
3130 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3132 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3133 if( $success === true ) {
3134 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3136 $retval[$oldSubpage->getPrefixedText()] = $success;
3143 * Checks if this page is just a one-rev redirect.
3144 * Adds lock, so don't use just for light purposes.
3146 * @return \type{\bool} TRUE or FALSE
3148 public function isSingleRevRedirect() {
3149 $dbw = wfGetDB( DB_MASTER
);
3151 $row = $dbw->selectRow( 'page',
3152 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3155 array( 'FOR UPDATE' )
3157 # Cache some fields we may want
3158 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3159 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3160 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3161 if( !$this->mRedirect
) {
3164 # Does the article have a history?
3165 $row = $dbw->selectField( array( 'page', 'revision'),
3167 array( 'page_namespace' => $this->getNamespace(),
3168 'page_title' => $this->getDBkey(),
3170 'page_latest != rev_id'
3173 array( 'FOR UPDATE' )
3175 # Return true if there was no history
3176 return ($row === false);
3180 * Checks if $this can be moved to a given Title
3181 * - Selects for update, so don't call it unless you mean business
3183 * @param &$nt \type{Title} the new title to check
3184 * @return \type{\bool} TRUE or FALSE
3186 public function isValidMoveTarget( $nt ) {
3187 $dbw = wfGetDB( DB_MASTER
);
3188 # Is it an existsing file?
3189 if( $nt->getNamespace() == NS_FILE
) {
3190 $file = wfLocalFile( $nt );
3191 if( $file->exists() ) {
3192 wfDebug( __METHOD__
. ": file exists\n" );
3196 # Is it a redirect with no history?
3197 if( !$nt->isSingleRevRedirect() ) {
3198 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3201 # Get the article text
3202 $rev = Revision
::newFromTitle( $nt );
3203 $text = $rev->getText();
3204 # Does the redirect point to the source?
3205 # Or is it a broken self-redirect, usually caused by namespace collisions?
3207 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3208 $redirTitle = Title
::newFromText( $m[1] );
3209 if( !is_object( $redirTitle ) ||
3210 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3211 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3212 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3217 wfDebug( __METHOD__
. ": failsafe\n" );
3224 * Can this title be added to a user's watchlist?
3226 * @return \type{\bool} TRUE or FALSE
3228 public function isWatchable() {
3229 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3233 * Get categories to which this Title belongs and return an array of
3234 * categories' names.
3236 * @return \type{\array} array an array of parents in the form:
3237 * $parent => $currentarticle
3239 public function getParentCategories() {
3242 $titlekey = $this->getArticleId();
3243 $dbr = wfGetDB( DB_SLAVE
);
3244 $categorylinks = $dbr->tableName( 'categorylinks' );
3247 $sql = "SELECT * FROM $categorylinks"
3248 ." WHERE cl_from='$titlekey'"
3249 ." AND cl_from <> '0'"
3250 ." ORDER BY cl_sortkey";
3252 $res = $dbr->query( $sql );
3254 if( $dbr->numRows( $res ) > 0 ) {
3255 foreach( $res as $row )
3256 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3257 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3258 $dbr->freeResult( $res );
3266 * Get a tree of parent categories
3267 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3268 * @return \type{\array} Tree of parent categories
3270 public function getParentCategoryTree( $children = array() ) {
3272 $parents = $this->getParentCategories();
3275 foreach( $parents as $parent => $current ) {
3276 if ( array_key_exists( $parent, $children ) ) {
3277 # Circular reference
3278 $stack[$parent] = array();
3280 $nt = Title
::newFromText($parent);
3282 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3294 * Get an associative array for selecting this title from
3297 * @return \type{\array} Selection array
3299 public function pageCond() {
3300 if( $this->mArticleID
> 0 ) {
3301 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3302 return array( 'page_id' => $this->mArticleID
);
3304 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3309 * Get the revision ID of the previous revision
3311 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3312 * @param $flags \type{\int} GAID_FOR_UPDATE
3313 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3315 public function getPreviousRevisionID( $revId, $flags=0 ) {
3316 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3317 return $db->selectField( 'revision', 'rev_id',
3319 'rev_page' => $this->getArticleId($flags),
3320 'rev_id < ' . intval( $revId )
3323 array( 'ORDER BY' => 'rev_id DESC' )
3328 * Get the revision ID of the next revision
3330 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3331 * @param $flags \type{\int} GAID_FOR_UPDATE
3332 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3334 public function getNextRevisionID( $revId, $flags=0 ) {
3335 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3336 return $db->selectField( 'revision', 'rev_id',
3338 'rev_page' => $this->getArticleId($flags),
3339 'rev_id > ' . intval( $revId )
3342 array( 'ORDER BY' => 'rev_id' )
3347 * Get the first revision of the page
3349 * @param $flags \type{\int} GAID_FOR_UPDATE
3350 * @return Revision (or NULL if page doesn't exist)
3352 public function getFirstRevision( $flags=0 ) {
3353 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3354 $pageId = $this->getArticleId($flags);
3355 if( !$pageId ) return null;
3356 $row = $db->selectRow( 'revision', '*',
3357 array( 'rev_page' => $pageId ),
3359 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3364 return new Revision( $row );
3369 * Check if this is a new page
3373 public function isNewPage() {
3374 $dbr = wfGetDB( DB_SLAVE
);
3375 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3379 * Get the oldest revision timestamp of this page
3381 * @return string, MW timestamp
3383 public function getEarliestRevTime() {
3384 $dbr = wfGetDB( DB_SLAVE
);
3385 if( $this->exists() ) {
3386 $min = $dbr->selectField( 'revision',
3387 'MIN(rev_timestamp)',
3388 array( 'rev_page' => $this->getArticleId() ),
3390 return wfTimestampOrNull( TS_MW
, $min );
3396 * Get the number of revisions between the given revision IDs.
3397 * Used for diffs and other things that really need it.
3399 * @param $old \type{\int} Revision ID.
3400 * @param $new \type{\int} Revision ID.
3401 * @return \type{\int} Number of revisions between these IDs.
3403 public function countRevisionsBetween( $old, $new ) {
3404 $dbr = wfGetDB( DB_SLAVE
);
3405 return (int)$dbr->selectField( 'revision', 'count(*)',
3406 'rev_page = ' . intval( $this->getArticleId() ) .
3407 ' AND rev_id > ' . intval( $old ) .
3408 ' AND rev_id < ' . intval( $new ),
3414 * Compare with another title.
3416 * @param \type{Title} $title
3417 * @return \type{\bool} TRUE or FALSE
3419 public function equals( Title
$title ) {
3420 // Note: === is necessary for proper matching of number-like titles.
3421 return $this->getInterwiki() === $title->getInterwiki()
3422 && $this->getNamespace() == $title->getNamespace()
3423 && $this->getDBkey() === $title->getDBkey();
3427 * Callback for usort() to do title sorts by (namespace, title)
3429 public static function compare( $a, $b ) {
3430 if( $a->getNamespace() == $b->getNamespace() ) {
3431 return strcmp( $a->getText(), $b->getText() );
3433 return $a->getNamespace() - $b->getNamespace();
3438 * Return a string representation of this title
3440 * @return \type{\string} String representation of this title
3442 public function __toString() {
3443 return $this->getPrefixedText();
3447 * Check if page exists. For historical reasons, this function simply
3448 * checks for the existence of the title in the page table, and will
3449 * thus return false for interwiki links, special pages and the like.
3450 * If you want to know if a title can be meaningfully viewed, you should
3451 * probably call the isKnown() method instead.
3453 * @return \type{\bool} TRUE or FALSE
3455 public function exists() {
3456 return $this->getArticleId() != 0;
3460 * Should links to this title be shown as potentially viewable (i.e. as
3461 * "bluelinks"), even if there's no record by this title in the page
3464 * This function is semi-deprecated for public use, as well as somewhat
3465 * misleadingly named. You probably just want to call isKnown(), which
3466 * calls this function internally.
3468 * (ISSUE: Most of these checks are cheap, but the file existence check
3469 * can potentially be quite expensive. Including it here fixes a lot of
3470 * existing code, but we might want to add an optional parameter to skip
3471 * it and any other expensive checks.)
3473 * @return \type{\bool} TRUE or FALSE
3475 public function isAlwaysKnown() {
3476 if( $this->mInterwiki
!= '' ) {
3477 return true; // any interwiki link might be viewable, for all we know
3479 switch( $this->mNamespace
) {
3482 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3484 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3486 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3488 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3489 // the full l10n of that language to be loaded. That takes much memory and
3490 // isn't needed. So we strip the language part away.
3491 // Also, extension messages which are not loaded, are shown as red, because
3492 // we don't call MessageCache::loadAllMessages.
3493 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3494 return wfMsgWeirdKey( $basename ); // known system message
3501 * Does this title refer to a page that can (or might) be meaningfully
3502 * viewed? In particular, this function may be used to determine if
3503 * links to the title should be rendered as "bluelinks" (as opposed to
3504 * "redlinks" to non-existent pages).
3506 * @return \type{\bool} TRUE or FALSE
3508 public function isKnown() {
3509 return $this->exists() ||
$this->isAlwaysKnown();
3513 * Is this in a namespace that allows actual pages?
3515 * @return \type{\bool} TRUE or FALSE
3517 public function canExist() {
3518 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3522 * Update page_touched timestamps and send squid purge messages for
3523 * pages linking to this title. May be sent to the job queue depending
3524 * on the number of links. Typically called on create and delete.
3526 public function touchLinks() {
3527 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3530 if ( $this->getNamespace() == NS_CATEGORY
) {
3531 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3537 * Get the last touched timestamp
3538 * @param Database $db, optional db
3539 * @return \type{\string} Last touched timestamp
3541 public function getTouched( $db = null ) {
3542 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3543 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3548 * Get the timestamp when this page was updated since the user last saw it.
3550 * @return mixed string/NULL
3552 public function getNotificationTimestamp( $user = null ) {
3553 global $wgUser, $wgShowUpdatedMarker;
3554 // Assume current user if none given
3555 if( !$user ) $user = $wgUser;
3556 // Check cache first
3557 $uid = $user->getId();
3558 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3559 return $this->mNotificationTimestamp
[$uid];
3561 if( !$uid ||
!$wgShowUpdatedMarker ) {
3562 return $this->mNotificationTimestamp
[$uid] = false;
3564 // Don't cache too much!
3565 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3566 $this->mNotificationTimestamp
= array();
3568 $dbr = wfGetDB( DB_SLAVE
);
3569 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3570 'wl_notificationtimestamp',
3571 array( 'wl_namespace' => $this->getNamespace(),
3572 'wl_title' => $this->getDBkey(),
3573 'wl_user' => $user->getId()
3577 return $this->mNotificationTimestamp
[$uid];
3581 * Get the trackback URL for this page
3582 * @return \type{\string} Trackback URL
3584 public function trackbackURL() {
3585 global $wgScriptPath, $wgServer, $wgScriptExtension;
3587 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3588 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3592 * Get the trackback RDF for this page
3593 * @return \type{\string} Trackback RDF
3595 public function trackbackRDF() {
3596 $url = htmlspecialchars($this->getFullURL());
3597 $title = htmlspecialchars($this->getText());
3598 $tburl = $this->trackbackURL();
3600 // Autodiscovery RDF is placed in comments so HTML validator
3601 // won't barf. This is a rather icky workaround, but seems
3602 // frequently used by this kind of RDF thingy.
3604 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3606 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3607 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3608 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3611 dc:identifier=\"$url\"
3613 trackback:ping=\"$tburl\" />
3619 * Generate strings used for xml 'id' names in monobook tabs
3620 * @return \type{\string} XML 'id' name
3622 public function getNamespaceKey( $prepend = 'nstab-' ) {
3624 // Gets the subject namespace if this title
3625 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3626 // Checks if cononical namespace name exists for namespace
3627 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3628 // Uses canonical namespace name
3629 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3631 // Uses text of namespace
3632 $namespaceKey = $this->getSubjectNsText();
3634 // Makes namespace key lowercase
3635 $namespaceKey = $wgContLang->lc( $namespaceKey );
3637 if ( $namespaceKey == '' ) {
3638 $namespaceKey = 'main';
3640 // Changes file to image for backwards compatibility
3641 if ( $namespaceKey == 'file' ) {
3642 $namespaceKey = 'image';
3644 return $prepend . $namespaceKey;
3648 * Returns true if this title resolves to the named special page
3649 * @param $name \type{\string} The special page name
3651 public function isSpecial( $name ) {
3652 if ( $this->getNamespace() == NS_SPECIAL
) {
3653 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3654 if ( $name == $thisName ) {
3662 * If the Title refers to a special page alias which is not the local default,
3663 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3665 public function fixSpecialName() {
3666 if ( $this->getNamespace() == NS_SPECIAL
) {
3667 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3668 if ( $canonicalName ) {
3669 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3670 if ( $localName != $this->mDbkeyform
) {
3671 return Title
::makeTitle( NS_SPECIAL
, $localName );
3679 * Is this Title in a namespace which contains content?
3680 * In other words, is this a content page, for the purposes of calculating
3683 * @return \type{\bool} TRUE or FALSE
3685 public function isContentPage() {
3686 return MWNamespace
::isContent( $this->getNamespace() );
3690 * Get all extant redirects to this Title
3692 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3693 * NULL to consider all namespaces
3694 * @return \type{\arrayof{Title}} Redirects to this title
3696 public function getRedirectsHere( $ns = null ) {
3699 $dbr = wfGetDB( DB_SLAVE
);
3701 'rd_namespace' => $this->getNamespace(),
3702 'rd_title' => $this->getDBkey(),
3705 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3707 $res = $dbr->select(
3708 array( 'redirect', 'page' ),
3709 array( 'page_namespace', 'page_title' ),
3715 foreach( $res as $row ) {
3716 $redirs[] = self
::newFromRow( $row );
3722 * Check if this Title is a valid redirect target
3724 * @return \type{\bool} TRUE or FALSE
3726 public function isValidRedirectTarget() {
3727 global $wgInvalidRedirectTargets;
3729 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3730 if( $this->isSpecial( 'Userlogout' ) ) {
3734 foreach( $wgInvalidRedirectTargets as $target ) {
3735 if( $this->isSpecial( $target ) ) {
3744 * Get a backlink cache object
3746 function getBacklinkCache() {
3747 if ( is_null( $this->mBacklinkCache
) ) {
3748 $this->mBacklinkCache
= new BacklinkCache( $this );
3750 return $this->mBacklinkCache
;
3754 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3758 public function canUseNoindex(){
3759 global $wgArticleRobotPolicies, $wgContentNamespaces,
3760 $wgExemptFromUserRobotsControl;
3762 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3763 ?
$wgContentNamespaces
3764 : $wgExemptFromUserRobotsControl;
3766 return !in_array( $this->mNamespace
, $bannedNamespaces );
3770 public function getRestrictionTypes() {
3771 global $wgRestrictionTypes;
3772 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3774 if ( $this->getNamespace() == NS_FILE
) {
3775 $types[] = 'upload';
3778 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );