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->normalizeForSearch( $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 # Note that we don't urlencode the fragment. urlencoded Unicode
505 # fragments appear not to work in IE (at least up to 7) or in at least
506 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
507 # to care if they aren't encoded.
508 return Sanitizer
::escapeId( $fragment, 'noninitial' );
511 #----------------------------------------------------------------------------
513 #----------------------------------------------------------------------------
515 /** Simple accessors */
517 * Get the text form (spaces not underscores) of the main part
518 * @return \type{\string} Main part of the title
520 public function getText() { return $this->mTextform
; }
522 * Get the URL-encoded form of the main part
523 * @return \type{\string} Main part of the title, URL-encoded
525 public function getPartialURL() { return $this->mUrlform
; }
527 * Get the main part with underscores
528 * @return \type{\string} Main part of the title, with underscores
530 public function getDBkey() { return $this->mDbkeyform
; }
532 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
533 * @return \type{\int} Namespace index
535 public function getNamespace() { return $this->mNamespace
; }
537 * Get the namespace text
538 * @return \type{\string} Namespace text
540 public function getNsText() {
543 if ( $this->mInterwiki
!= '' ) {
544 // This probably shouldn't even happen. ohh man, oh yuck.
545 // But for interwiki transclusion it sometimes does.
546 // Shit. Shit shit shit.
548 // Use the canonical namespaces if possible to try to
549 // resolve a foreign namespace.
550 if( MWNamespace
::exists( $this->mNamespace
) ) {
551 return MWNamespace
::getCanonicalName( $this->mNamespace
);
554 return $wgContLang->getNsText( $this->mNamespace
);
557 * Get the DB key with the initial letter case as specified by the user
558 * @return \type{\string} DB key
560 function getUserCaseDBKey() {
561 return $this->mUserCaseDBKey
;
564 * Get the namespace text of the subject (rather than talk) page
565 * @return \type{\string} Namespace text
567 public function getSubjectNsText() {
569 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
572 * Get the namespace text of the talk page
573 * @return \type{\string} Namespace text
575 public function getTalkNsText() {
577 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
580 * Could this title have a corresponding talk page?
581 * @return \type{\bool} TRUE or FALSE
583 public function canTalk() {
584 return( MWNamespace
::canTalk( $this->mNamespace
) );
587 * Get the interwiki prefix (or null string)
588 * @return \type{\string} Interwiki prefix
590 public function getInterwiki() { return $this->mInterwiki
; }
592 * Get the Title fragment (i.e.\ the bit after the #) in text form
593 * @return \type{\string} Title fragment
595 public function getFragment() { return $this->mFragment
; }
597 * Get the fragment in URL form, including the "#" character if there is one
598 * @return \type{\string} Fragment in URL form
600 public function getFragmentForURL() {
601 if ( $this->mFragment
== '' ) {
604 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
608 * Get the default namespace index, for when there is no namespace
609 * @return \type{\int} Default namespace index
611 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
614 * Get title for search index
615 * @return \type{\string} a stripped-down title string ready for the
618 public function getIndexTitle() {
619 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
623 * Get the prefixed database key form
624 * @return \type{\string} the prefixed title, with underscores and
625 * any interwiki and namespace prefixes
627 public function getPrefixedDBkey() {
628 $s = $this->prefix( $this->mDbkeyform
);
629 $s = str_replace( ' ', '_', $s );
634 * Get the prefixed title with spaces.
635 * This is the form usually used for display
636 * @return \type{\string} the prefixed title, with spaces
638 public function getPrefixedText() {
639 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
640 $s = $this->prefix( $this->mTextform
);
641 $s = str_replace( '_', ' ', $s );
642 $this->mPrefixedText
= $s;
644 return $this->mPrefixedText
;
648 * Get the prefixed title with spaces, plus any fragment
649 * (part beginning with '#')
650 * @return \type{\string} the prefixed title, with spaces and
651 * the fragment, including '#'
653 public function getFullText() {
654 $text = $this->getPrefixedText();
655 if( $this->mFragment
!= '' ) {
656 $text .= '#' . $this->mFragment
;
662 * Get the base name, i.e. the leftmost parts before the /
663 * @return \type{\string} Base name
665 public function getBaseText() {
666 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
667 return $this->getText();
670 $parts = explode( '/', $this->getText() );
671 # Don't discard the real title if there's no subpage involved
672 if( count( $parts ) > 1 )
673 unset( $parts[ count( $parts ) - 1 ] );
674 return implode( '/', $parts );
678 * Get the lowest-level subpage name, i.e. the rightmost part after /
679 * @return \type{\string} Subpage name
681 public function getSubpageText() {
682 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
683 return( $this->mTextform
);
685 $parts = explode( '/', $this->mTextform
);
686 return( $parts[ count( $parts ) - 1 ] );
690 * Get a URL-encoded form of the subpage text
691 * @return \type{\string} URL-encoded subpage name
693 public function getSubpageUrlForm() {
694 $text = $this->getSubpageText();
695 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
700 * Get a URL-encoded title (not an actual URL) including interwiki
701 * @return \type{\string} the URL-encoded form
703 public function getPrefixedURL() {
704 $s = $this->prefix( $this->mDbkeyform
);
705 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
710 * Get a real URL referring to this title, with interwiki link and
713 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
714 * links. Can be specified as an associative array as well, e.g.,
715 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
716 * @param $variant \type{\string} language variant of url (for sr, zh..)
717 * @return \type{\string} the URL
719 public function getFullURL( $query = '', $variant = false ) {
720 global $wgContLang, $wgServer, $wgRequest;
722 if( is_array( $query ) ) {
723 $query = wfArrayToCGI( $query );
726 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
728 $url = $this->getLocalURL( $query, $variant );
730 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
731 // Correct fix would be to move the prepending elsewhere.
732 if ($wgRequest->getVal('action') != 'render') {
733 $url = $wgServer . $url;
736 $baseUrl = $interwiki->getURL( );
738 $namespace = wfUrlencode( $this->getNsText() );
739 if ( $namespace != '' ) {
740 # Can this actually happen? Interwikis shouldn't be parsed.
741 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
744 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
745 $url = wfAppendQuery( $url, $query );
748 # Finally, add the fragment.
749 $url .= $this->getFragmentForURL();
751 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
756 * Get a URL with no fragment or server name. If this page is generated
757 * with action=render, $wgServer is prepended.
758 * @param mixed $query an optional query string; if not specified,
759 * $wgArticlePath will be used. Can be specified as an associative array
760 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
762 * @param $variant \type{\string} language variant of url (for sr, zh..)
763 * @return \type{\string} the URL
765 public function getLocalURL( $query = '', $variant = false ) {
766 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
767 global $wgVariantArticlePath, $wgContLang, $wgUser;
769 if( is_array( $query ) ) {
770 $query = wfArrayToCGI( $query );
773 // internal links should point to same variant as current page (only anonymous users)
774 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
775 $pref = $wgContLang->getPreferredVariant(false);
776 if($pref != $wgContLang->getCode())
780 if ( $this->isExternal() ) {
781 $url = $this->getFullURL();
783 // This is currently only used for edit section links in the
784 // context of interwiki transclusion. In theory we should
785 // append the query to the end of any existing query string,
786 // but interwiki transclusion is already broken in that case.
790 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
791 if ( $query == '' ) {
792 if( $variant != false && $wgContLang->hasVariants() ) {
793 if( $wgVariantArticlePath == false ) {
794 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
796 $variantArticlePath = $wgVariantArticlePath;
798 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
799 $url = str_replace( '$1', $dbkey, $url );
801 $url = str_replace( '$1', $dbkey, $wgArticlePath );
804 global $wgActionPaths;
807 if( !empty( $wgActionPaths ) &&
808 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
810 $action = urldecode( $matches[2] );
811 if( isset( $wgActionPaths[$action] ) ) {
812 $query = $matches[1];
813 if( isset( $matches[4] ) ) $query .= $matches[4];
814 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
816 $url = wfAppendQuery( $url, $query );
820 if ( $url === false ) {
821 if ( $query == '-' ) {
824 $url = "{$wgScript}?title={$dbkey}&{$query}";
828 // FIXME: this causes breakage in various places when we
829 // actually expected a local URL and end up with dupe prefixes.
830 if ($wgRequest->getVal('action') == 'render') {
831 $url = $wgServer . $url;
834 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
839 * Get a URL that's the simplest URL that will be valid to link, locally,
840 * to the current Title. It includes the fragment, but does not include
841 * the server unless action=render is used (or the link is external). If
842 * there's a fragment but the prefixed text is empty, we just return a link
845 * The result obviously should not be URL-escaped, but does need to be
846 * HTML-escaped if it's being output in HTML.
848 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
849 * query string. Keys and values will be escaped.
850 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
851 * for external links. Default is "false" (same variant as current page,
852 * for anonymous users).
853 * @return \type{\string} the URL
855 public function getLinkUrl( $query = array(), $variant = false ) {
856 wfProfileIn( __METHOD__
);
857 if( $this->isExternal() ) {
858 $ret = $this->getFullURL( $query );
859 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
860 $ret = $this->getFragmentForURL();
862 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
864 wfProfileOut( __METHOD__
);
869 * Get an HTML-escaped version of the URL form, suitable for
870 * using in a link, without a server name or fragment
871 * @param $query \type{\string} an optional query string
872 * @return \type{\string} the URL
874 public function escapeLocalURL( $query = '' ) {
875 return htmlspecialchars( $this->getLocalURL( $query ) );
879 * Get an HTML-escaped version of the URL form, suitable for
880 * using in a link, including the server name and fragment
882 * @param $query \type{\string} an optional query string
883 * @return \type{\string} the URL
885 public function escapeFullURL( $query = '' ) {
886 return htmlspecialchars( $this->getFullURL( $query ) );
890 * Get the URL form for an internal link.
891 * - Used in various Squid-related code, in case we have a different
892 * internal hostname for the server from the exposed one.
894 * @param $query \type{\string} an optional query string
895 * @param $variant \type{\string} language variant of url (for sr, zh..)
896 * @return \type{\string} the URL
898 public function getInternalURL( $query = '', $variant = false ) {
899 global $wgInternalServer;
900 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
901 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
906 * Get the edit URL for this Title
907 * @return \type{\string} the URL, or a null string if this is an
910 public function getEditURL() {
911 if ( $this->mInterwiki
!= '' ) { return ''; }
912 $s = $this->getLocalURL( 'action=edit' );
918 * Get the HTML-escaped displayable text form.
919 * Used for the title field in <a> tags.
920 * @return \type{\string} the text, including any prefixes
922 public function getEscapedText() {
923 return htmlspecialchars( $this->getPrefixedText() );
927 * Is this Title interwiki?
928 * @return \type{\bool}
930 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
933 * Is this page "semi-protected" - the *only* protection is autoconfirm?
935 * @param $action \type{\string} Action to check (default: edit)
936 * @return \type{\bool}
938 public function isSemiProtected( $action = 'edit' ) {
939 if( $this->exists() ) {
940 $restrictions = $this->getRestrictions( $action );
941 if( count( $restrictions ) > 0 ) {
942 foreach( $restrictions as $restriction ) {
943 if( strtolower( $restriction ) != 'autoconfirmed' )
952 # If it doesn't exist, it can't be protected
958 * Does the title correspond to a protected article?
959 * @param $action \type{\string} the action the page is protected from,
960 * by default checks all actions.
961 * @return \type{\bool}
963 public function isProtected( $action = '' ) {
964 global $wgRestrictionLevels;
966 $restrictionTypes = $this->getRestrictionTypes();
968 # Special pages have inherent protection
969 if( $this->getNamespace() == NS_SPECIAL
)
972 # Check regular protection levels
973 foreach( $restrictionTypes as $type ){
974 if( $action == $type ||
$action == '' ) {
975 $r = $this->getRestrictions( $type );
976 foreach( $wgRestrictionLevels as $level ) {
977 if( in_array( $level, $r ) && $level != '' ) {
988 * Is this a conversion table for the LanguageConverter?
989 * @return \type{\bool}
991 public function isConversionTable() {
992 if($this->getNamespace() == NS_MEDIAWIKI
993 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1001 * Is $wgUser watching this page?
1002 * @return \type{\bool}
1004 public function userIsWatching() {
1007 if ( is_null( $this->mWatched
) ) {
1008 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1009 $this->mWatched
= false;
1011 $this->mWatched
= $wgUser->isWatched( $this );
1014 return $this->mWatched
;
1018 * Can $wgUser perform $action on this page?
1019 * This skips potentially expensive cascading permission checks
1020 * as well as avoids expensive error formatting
1022 * Suitable for use for nonessential UI controls in common cases, but
1023 * _not_ for functional access control.
1025 * May provide false positives, but should never provide a false negative.
1027 * @param $action \type{\string} action that permission needs to be checked for
1028 * @return \type{\bool}
1030 public function quickUserCan( $action ) {
1031 return $this->userCan( $action, false );
1035 * Determines if $wgUser is unable to edit this page because it has been protected
1036 * by $wgNamespaceProtection.
1038 * @return \type{\bool}
1040 public function isNamespaceProtected() {
1041 global $wgNamespaceProtection, $wgUser;
1042 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1043 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1044 if( $right != '' && !$wgUser->isAllowed( $right ) )
1052 * Can $wgUser perform $action on this page?
1053 * @param $action \type{\string} action that permission needs to be checked for
1054 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1055 * @return \type{\bool}
1057 public function userCan( $action, $doExpensiveQueries = true ) {
1059 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1063 * Can $user perform $action on this page?
1065 * FIXME: This *does not* check throttles (User::pingLimiter()).
1067 * @param $action \type{\string}action that permission needs to be checked for
1068 * @param $user \type{User} user to check
1069 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1070 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1071 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1073 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1074 if( !StubObject
::isRealObject( $user ) ) {
1075 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1077 $wgUser->_unstub( '', 5 );
1080 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1084 global $wgEmailConfirmToEdit;
1086 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1087 $errors[] = array( 'confirmedittext' );
1090 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1091 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1092 $block = $user->mBlock
;
1094 // This is from OutputPage::blockedPage
1095 // Copied at r23888 by werdna
1097 $id = $user->blockedBy();
1098 $reason = $user->blockedFor();
1099 if( $reason == '' ) {
1100 $reason = wfMsg( 'blockednoreason' );
1104 if ( is_numeric( $id ) ) {
1105 $name = User
::whoIs( $id );
1110 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1111 $blockid = $block->mId
;
1112 $blockExpiry = $user->mBlock
->mExpiry
;
1113 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1115 if ( $blockExpiry == 'infinity' ) {
1116 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1117 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1119 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1120 if ( strpos( $option, ':' ) == false )
1123 list ($show, $value) = explode( ":", $option );
1125 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1126 $blockExpiry = $show;
1131 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1134 $intended = $user->mBlock
->mAddress
;
1136 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1137 $blockid, $blockExpiry, $intended, $blockTimestamp );
1140 // Remove the errors being ignored.
1142 foreach( $errors as $index => $error ) {
1143 $error_key = is_array($error) ?
$error[0] : $error;
1145 if (in_array( $error_key, $ignoreErrors )) {
1146 unset($errors[$index]);
1154 * Can $user perform $action on this page? This is an internal function,
1155 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1156 * checks on wfReadOnly() and blocks)
1158 * @param $action \type{\string} action that permission needs to be checked for
1159 * @param $user \type{User} user to check
1160 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1161 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1162 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1164 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1165 wfProfileIn( __METHOD__
);
1169 // First stop is permissions checks, which fail most often, and which are easiest to test.
1170 if ( $action == 'move' ) {
1171 if( !$user->isAllowed( 'move-rootuserpages' )
1172 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1174 // Show user page-specific message only if the user can move other pages
1175 $errors[] = array( 'cant-move-user-page' );
1178 // Check if user is allowed to move files if it's a file
1179 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1180 $errors[] = array( 'movenotallowedfile' );
1183 if( !$user->isAllowed( 'move' ) ) {
1184 // User can't move anything
1185 global $wgGroupPermissions;
1186 $userCanMove = false;
1187 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1188 $userCanMove = $wgGroupPermissions['user']['move'];
1190 $autoconfirmedCanMove = false;
1191 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1192 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1194 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1195 // custom message if logged-in users without any special rights can move
1196 $errors[] = array ( 'movenologintext' );
1198 $errors[] = array ('movenotallowed');
1201 } elseif ( $action == 'create' ) {
1202 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1203 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1205 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1207 } elseif( $action == 'move-target' ) {
1208 if( !$user->isAllowed( 'move' ) ) {
1209 // User can't move anything
1210 $errors[] = array ('movenotallowed');
1211 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1212 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1214 // Show user page-specific message only if the user can move other pages
1215 $errors[] = array( 'cant-move-to-user-page' );
1217 } elseif( !$user->isAllowed( $action ) ) {
1220 // We avoid expensive display logic for quickUserCan's and such
1223 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1224 User
::getGroupsWithPermission( $action ) );
1231 $wgLang->commaList( $groups ),
1235 $return = array( "badaccess-group0" );
1237 $errors[] = $return;
1240 # Short-circuit point
1241 if( $short && count($errors) > 0 ) {
1242 wfProfileOut( __METHOD__
);
1246 // Use getUserPermissionsErrors instead
1247 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1248 wfProfileOut( __METHOD__
);
1249 return $result ?
array() : array( array( 'badaccess-group0' ) );
1251 // Check getUserPermissionsErrors hook
1252 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1253 if( is_array($result) && count($result) && !is_array($result[0]) )
1254 $errors[] = $result; # A single array representing an error
1255 else if( is_array($result) && is_array($result[0]) )
1256 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1257 else if( $result !== '' && is_string($result) )
1258 $errors[] = array($result); # A string representing a message-id
1259 else if( $result === false )
1260 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1262 # Short-circuit point
1263 if( $short && count($errors) > 0 ) {
1264 wfProfileOut( __METHOD__
);
1267 // Check getUserPermissionsErrorsExpensive hook
1268 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1269 if( is_array($result) && count($result) && !is_array($result[0]) )
1270 $errors[] = $result; # A single array representing an error
1271 else if( is_array($result) && is_array($result[0]) )
1272 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1273 else if( $result !== '' && is_string($result) )
1274 $errors[] = array($result); # A string representing a message-id
1275 else if( $result === false )
1276 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1278 # Short-circuit point
1279 if( $short && count($errors) > 0 ) {
1280 wfProfileOut( __METHOD__
);
1284 # Only 'createaccount' and 'execute' can be performed on
1285 # special pages, which don't actually exist in the DB.
1286 $specialOKActions = array( 'createaccount', 'execute' );
1287 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1288 $errors[] = array('ns-specialprotected');
1291 # Check $wgNamespaceProtection for restricted namespaces
1292 if( $this->isNamespaceProtected() ) {
1293 $ns = $this->getNamespace() == NS_MAIN ?
1294 wfMsg( 'nstab-main' ) : $this->getNsText();
1295 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1296 array('protectedinterface') : array( 'namespaceprotected', $ns );
1299 # Protect css/js subpages of user pages
1300 # XXX: this might be better using restrictions
1301 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1302 # and $this->userCanEditJsSubpage() from working
1303 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1304 if( $this->isCssSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('editusercss') )
1305 && $action != 'patrol'
1306 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1308 $errors[] = array('customcssjsprotected');
1309 } else if( $this->isJsSubpage() && !( $user->isAllowed('editusercssjs') ||
$user->isAllowed('edituserjs') )
1310 && $action != 'patrol'
1311 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1313 $errors[] = array('customcssjsprotected');
1316 # Check against page_restrictions table requirements on this
1317 # page. The user must possess all required rights for this action.
1318 foreach( $this->getRestrictions($action) as $right ) {
1319 // Backwards compatibility, rewrite sysop -> protect
1320 if( $right == 'sysop' ) {
1323 if( $right != '' && !$user->isAllowed( $right ) ) {
1324 // Users with 'editprotected' permission can edit protected pages
1325 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1326 // Users with 'editprotected' permission cannot edit protected pages
1327 // with cascading option turned on.
1328 if( $this->mCascadeRestriction
) {
1329 $errors[] = array( 'protectedpagetext', $right );
1332 $errors[] = array( 'protectedpagetext', $right );
1336 # Short-circuit point
1337 if( $short && count($errors) > 0 ) {
1338 wfProfileOut( __METHOD__
);
1342 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1343 # We /could/ use the protection level on the source page, but it's fairly ugly
1344 # as we have to establish a precedence hierarchy for pages included by multiple
1345 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1346 # as they could remove the protection anyway.
1347 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1348 # Cascading protection depends on more than this page...
1349 # Several cascading protected pages may include this page...
1350 # Check each cascading level
1351 # This is only for protection restrictions, not for all actions
1352 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1353 foreach( $restrictions[$action] as $right ) {
1354 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1355 if( $right != '' && !$user->isAllowed( $right ) ) {
1357 foreach( $cascadingSources as $page )
1358 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1359 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1364 # Short-circuit point
1365 if( $short && count($errors) > 0 ) {
1366 wfProfileOut( __METHOD__
);
1370 if( $action == 'protect' ) {
1371 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1372 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1376 if( $action == 'create' ) {
1377 $title_protection = $this->getTitleProtection();
1378 if( is_array($title_protection) ) {
1379 extract($title_protection); // is this extract() really needed?
1381 if( $pt_create_perm == 'sysop' ) {
1382 $pt_create_perm = 'protect'; // B/C
1384 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1385 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1388 } elseif( $action == 'move' ) {
1389 // Check for immobile pages
1390 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1391 // Specific message for this case
1392 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1393 } elseif( !$this->isMovable() ) {
1394 // Less specific message for rarer cases
1395 $errors[] = array( 'immobile-page' );
1397 } elseif( $action == 'move-target' ) {
1398 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1399 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1400 } elseif( !$this->isMovable() ) {
1401 $errors[] = array( 'immobile-target-page' );
1405 wfProfileOut( __METHOD__
);
1410 * Is this title subject to title protection?
1411 * @return \type{\mixed} An associative array representing any existent title
1412 * protection, or false if there's none.
1414 private function getTitleProtection() {
1415 // Can't protect pages in special namespaces
1416 if ( $this->getNamespace() < 0 ) {
1420 // Can't protect pages that exist.
1421 if ($this->exists()) {
1425 $dbr = wfGetDB( DB_SLAVE
);
1426 $res = $dbr->select( 'protected_titles', '*',
1427 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1430 if ($row = $dbr->fetchRow( $res )) {
1438 * Update the title protection status
1439 * @param $create_perm \type{\string} Permission required for creation
1440 * @param $reason \type{\string} Reason for protection
1441 * @param $expiry \type{\string} Expiry timestamp
1443 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1444 global $wgUser,$wgContLang;
1446 if ($create_perm == implode(',',$this->getRestrictions('create'))
1447 && $expiry == $this->mRestrictionsExpiry
['create']) {
1452 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1454 $dbw = wfGetDB( DB_MASTER
);
1456 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1458 $expiry_description = '';
1459 if ( $encodedExpiry != 'infinity' ) {
1460 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring',$wgContLang->timeanddate( $expiry ),
1461 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1464 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1467 # Update protection table
1468 if ($create_perm != '' ) {
1469 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1471 'pt_namespace' => $namespace,
1472 'pt_title' => $title,
1473 'pt_create_perm' => $create_perm,
1474 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw),
1475 'pt_expiry' => $encodedExpiry,
1476 'pt_user' => $wgUser->getId(),
1477 'pt_reason' => $reason,
1481 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1482 'pt_title' => $title ), __METHOD__
);
1484 # Update the protection log
1485 if( $dbw->affectedRows() ) {
1486 $log = new LogPage( 'protect' );
1488 if( $create_perm ) {
1489 $params = array("[create=$create_perm] $expiry_description",'');
1490 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1492 $log->addEntry( 'unprotect', $this, $reason );
1500 * Remove any title protection due to page existing
1502 public function deleteTitleProtection() {
1503 $dbw = wfGetDB( DB_MASTER
);
1505 $dbw->delete( 'protected_titles',
1506 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1511 * Would anybody with sufficient privileges be able to move this page?
1512 * Some pages just aren't movable.
1514 * @return \type{\bool} TRUE or FALSE
1516 public function isMovable() {
1517 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1521 * Can $wgUser read this page?
1522 * @return \type{\bool} TRUE or FALSE
1523 * @todo fold these checks into userCan()
1525 public function userCanRead() {
1526 global $wgUser, $wgGroupPermissions;
1528 static $useShortcut = null;
1530 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1531 if( is_null( $useShortcut ) ) {
1532 global $wgRevokePermissions;
1533 $useShortcut = true;
1534 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1535 # Not a public wiki, so no shortcut
1536 $useShortcut = false;
1537 } elseif( !empty( $wgRevokePermissions ) ) {
1539 * Iterate through each group with permissions being revoked (key not included since we don't care
1540 * what the group name is), then check if the read permission is being revoked. If it is, then
1541 * we don't use the shortcut below since the user might not be able to read, even though anon
1542 * reading is allowed.
1544 foreach( $wgRevokePermissions as $perms ) {
1545 if( !empty( $perms['read'] ) ) {
1546 # We might be removing the read right from the user, so no shortcut
1547 $useShortcut = false;
1555 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1556 if ( $result !== null ) {
1560 # Shortcut for public wikis, allows skipping quite a bit of code
1564 if( $wgUser->isAllowed( 'read' ) ) {
1567 global $wgWhitelistRead;
1570 * Always grant access to the login page.
1571 * Even anons need to be able to log in.
1573 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1578 * Bail out if there isn't whitelist
1580 if( !is_array($wgWhitelistRead) ) {
1585 * Check for explicit whitelisting
1587 $name = $this->getPrefixedText();
1588 $dbName = $this->getPrefixedDBKey();
1589 // Check with and without underscores
1590 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1594 * Old settings might have the title prefixed with
1595 * a colon for main-namespace pages
1597 if( $this->getNamespace() == NS_MAIN
) {
1598 if( in_array( ':' . $name, $wgWhitelistRead ) )
1603 * If it's a special page, ditch the subpage bit
1606 if( $this->getNamespace() == NS_SPECIAL
) {
1607 $name = $this->getDBkey();
1608 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1609 if ( $name === false ) {
1610 # Invalid special page, but we show standard login required message
1614 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1615 if( in_array( $pure, $wgWhitelistRead, true ) )
1624 * Is this a talk page of some sort?
1625 * @return \type{\bool} TRUE or FALSE
1627 public function isTalkPage() {
1628 return MWNamespace
::isTalk( $this->getNamespace() );
1632 * Is this a subpage?
1633 * @return \type{\bool} TRUE or FALSE
1635 public function isSubpage() {
1636 return MWNamespace
::hasSubpages( $this->mNamespace
)
1637 ?
strpos( $this->getText(), '/' ) !== false
1642 * Does this have subpages? (Warning, usually requires an extra DB query.)
1643 * @return \type{\bool} TRUE or FALSE
1645 public function hasSubpages() {
1646 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1651 # We dynamically add a member variable for the purpose of this method
1652 # alone to cache the result. There's no point in having it hanging
1653 # around uninitialized in every Title object; therefore we only add it
1654 # if needed and don't declare it statically.
1655 if( isset( $this->mHasSubpages
) ) {
1656 return $this->mHasSubpages
;
1659 $subpages = $this->getSubpages( 1 );
1660 if( $subpages instanceof TitleArray
)
1661 return $this->mHasSubpages
= (bool)$subpages->count();
1662 return $this->mHasSubpages
= false;
1666 * Get all subpages of this page.
1667 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1668 * @return mixed TitleArray, or empty array if this page's namespace
1669 * doesn't allow subpages
1671 public function getSubpages( $limit = -1 ) {
1672 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1675 $dbr = wfGetDB( DB_SLAVE
);
1676 $conds['page_namespace'] = $this->getNamespace();
1677 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1680 $options['LIMIT'] = $limit;
1681 return $this->mSubpages
= TitleArray
::newFromResult(
1682 $dbr->select( 'page',
1683 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1692 * Could this page contain custom CSS or JavaScript, based
1695 * @return \type{\bool} TRUE or FALSE
1697 public function isCssOrJsPage() {
1698 return $this->mNamespace
== NS_MEDIAWIKI
1699 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1703 * Is this a .css or .js subpage of a user page?
1704 * @return \type{\bool} TRUE or FALSE
1706 public function isCssJsSubpage() {
1707 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1710 * Is this a *valid* .css or .js subpage of a user page?
1711 * Check that the corresponding skin exists
1712 * @return \type{\bool} TRUE or FALSE
1714 public function isValidCssJsSubpage() {
1715 if ( $this->isCssJsSubpage() ) {
1716 $name = $this->getSkinFromCssJsSubpage();
1717 if ( $name == 'common' ) return true;
1718 $skinNames = Skin
::getSkinNames();
1719 return array_key_exists( $name, $skinNames );
1725 * Trim down a .css or .js subpage title to get the corresponding skin name
1727 public function getSkinFromCssJsSubpage() {
1728 $subpage = explode( '/', $this->mTextform
);
1729 $subpage = $subpage[ count( $subpage ) - 1 ];
1730 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1733 * Is this a .css subpage of a user page?
1734 * @return \type{\bool} TRUE or FALSE
1736 public function isCssSubpage() {
1737 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1740 * Is this a .js subpage of a user page?
1741 * @return \type{\bool} TRUE or FALSE
1743 public function isJsSubpage() {
1744 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1747 * Protect css subpages of user pages: can $wgUser edit
1750 * @return \type{\bool} TRUE or FALSE
1751 * @todo XXX: this might be better using restrictions
1753 public function userCanEditCssSubpage() {
1755 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('editusercss') )
1756 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1759 * Protect js subpages of user pages: can $wgUser edit
1762 * @return \type{\bool} TRUE or FALSE
1763 * @todo XXX: this might be better using restrictions
1765 public function userCanEditJsSubpage() {
1767 return ( ( $wgUser->isAllowed('editusercssjs') && $wgUser->isAllowed('edituserjs') )
1768 ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1772 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1774 * @return \type{\bool} If the page is subject to cascading restrictions.
1776 public function isCascadeProtected() {
1777 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1778 return ( $sources > 0 );
1782 * Cascading protection: Get the source of any cascading restrictions on this page.
1784 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1785 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1786 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1787 * The restriction array is an array of each type, each of which contains an array of unique groups.
1789 public function getCascadeProtectionSources( $get_pages = true ) {
1790 $pagerestrictions = array();
1792 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1793 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1794 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1795 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1798 wfProfileIn( __METHOD__
);
1800 $dbr = wfGetDB( DB_SLAVE
);
1802 if ( $this->getNamespace() == NS_FILE
) {
1803 $tables = array ('imagelinks', 'page_restrictions');
1804 $where_clauses = array(
1805 'il_to' => $this->getDBkey(),
1807 'pr_cascade' => 1 );
1809 $tables = array ('templatelinks', 'page_restrictions');
1810 $where_clauses = array(
1811 'tl_namespace' => $this->getNamespace(),
1812 'tl_title' => $this->getDBkey(),
1814 'pr_cascade' => 1 );
1818 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1819 $where_clauses[] = 'page_id=pr_page';
1822 $cols = array( 'pr_expiry' );
1825 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1827 $sources = $get_pages ?
array() : false;
1828 $now = wfTimestampNow();
1829 $purgeExpired = false;
1831 foreach( $res as $row ) {
1832 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1833 if( $expiry > $now ) {
1835 $page_id = $row->pr_page
;
1836 $page_ns = $row->page_namespace
;
1837 $page_title = $row->page_title
;
1838 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1839 # Add groups needed for each restriction type if its not already there
1840 # Make sure this restriction type still exists
1842 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1843 $pagerestrictions[$row->pr_type
] = array();
1846 if ( isset($pagerestrictions[$row->pr_type
]) &&
1847 !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1848 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1854 // Trigger lazy purge of expired restrictions from the db
1855 $purgeExpired = true;
1858 if( $purgeExpired ) {
1859 Title
::purgeExpiredRestrictions();
1862 wfProfileOut( __METHOD__
);
1865 $this->mCascadeSources
= $sources;
1866 $this->mCascadingRestrictions
= $pagerestrictions;
1868 $this->mHasCascadingRestrictions
= $sources;
1870 return array( $sources, $pagerestrictions );
1873 function areRestrictionsCascading() {
1874 if (!$this->mRestrictionsLoaded
) {
1875 $this->loadRestrictions();
1878 return $this->mCascadeRestriction
;
1882 * Loads a string into mRestrictions array
1883 * @param $res \type{Resource} restrictions as an SQL result.
1885 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
1887 $dbr = wfGetDB( DB_SLAVE
);
1889 while( $row = $dbr->fetchObject( $res ) ) {
1893 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
1896 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
1897 $dbr = wfGetDB( DB_SLAVE
);
1899 $restrictionTypes = $this->getRestrictionTypes();
1901 foreach( $restrictionTypes as $type ){
1902 $this->mRestrictions
[$type] = array();
1903 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1906 $this->mCascadeRestriction
= false;
1908 # Backwards-compatibility: also load the restrictions from the page record (old format).
1910 if ( $oldFashionedRestrictions === null ) {
1911 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1912 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1915 if ($oldFashionedRestrictions != '') {
1917 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1918 $temp = explode( '=', trim( $restrict ) );
1919 if(count($temp) == 1) {
1920 // old old format should be treated as edit/move restriction
1921 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1922 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1924 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1928 $this->mOldRestrictions
= true;
1932 if( count($rows) ) {
1933 # Current system - load second to make them override.
1934 $now = wfTimestampNow();
1935 $purgeExpired = false;
1937 foreach( $rows as $row ) {
1938 # Cycle through all the restrictions.
1940 // Don't take care of restrictions types that aren't allowed
1942 if( !in_array( $row->pr_type
, $restrictionTypes ) )
1945 // This code should be refactored, now that it's being used more generally,
1946 // But I don't really see any harm in leaving it in Block for now -werdna
1947 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1949 // Only apply the restrictions if they haven't expired!
1950 if ( !$expiry ||
$expiry > $now ) {
1951 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1952 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1954 $this->mCascadeRestriction |
= $row->pr_cascade
;
1956 // Trigger a lazy purge of expired restrictions
1957 $purgeExpired = true;
1961 if( $purgeExpired ) {
1962 Title
::purgeExpiredRestrictions();
1966 $this->mRestrictionsLoaded
= true;
1970 * Load restrictions from the page_restrictions table
1972 public function loadRestrictions( $oldFashionedRestrictions = null ) {
1973 if( !$this->mRestrictionsLoaded
) {
1974 if ($this->exists()) {
1975 $dbr = wfGetDB( DB_SLAVE
);
1977 $res = $dbr->select( 'page_restrictions', '*',
1978 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1980 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
1982 $title_protection = $this->getTitleProtection();
1984 if (is_array($title_protection)) {
1985 extract($title_protection);
1987 $now = wfTimestampNow();
1988 $expiry = Block
::decodeExpiry($pt_expiry);
1990 if (!$expiry ||
$expiry > $now) {
1991 // Apply the restrictions
1992 $this->mRestrictionsExpiry
['create'] = $expiry;
1993 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1994 } else { // Get rid of the old restrictions
1995 Title
::purgeExpiredRestrictions();
1998 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
2000 $this->mRestrictionsLoaded
= true;
2006 * Purge expired restrictions from the page_restrictions table
2008 static function purgeExpiredRestrictions() {
2009 $dbw = wfGetDB( DB_MASTER
);
2010 $dbw->delete( 'page_restrictions',
2011 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2014 $dbw->delete( 'protected_titles',
2015 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2020 * Accessor/initialisation for mRestrictions
2022 * @param $action \type{\string} action that permission needs to be checked for
2023 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2025 public function getRestrictions( $action ) {
2026 if( !$this->mRestrictionsLoaded
) {
2027 $this->loadRestrictions();
2029 return isset( $this->mRestrictions
[$action] )
2030 ?
$this->mRestrictions
[$action]
2035 * Get the expiry time for the restriction against a given action
2036 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2037 * or not protected at all, or false if the action is not recognised.
2039 public function getRestrictionExpiry( $action ) {
2040 if( !$this->mRestrictionsLoaded
) {
2041 $this->loadRestrictions();
2043 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2047 * Is there a version of this page in the deletion archive?
2048 * @return \type{\int} the number of archived revisions
2050 public function isDeleted() {
2051 if( $this->getNamespace() < 0 ) {
2054 $dbr = wfGetDB( DB_SLAVE
);
2055 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2056 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2059 if( $this->getNamespace() == NS_FILE
) {
2060 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2061 array( 'fa_name' => $this->getDBkey() ),
2070 * Is there a version of this page in the deletion archive?
2073 public function isDeletedQuick() {
2074 if( $this->getNamespace() < 0 ) {
2077 $dbr = wfGetDB( DB_SLAVE
);
2078 $deleted = (bool)$dbr->selectField( 'archive', '1',
2079 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2082 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2083 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2084 array( 'fa_name' => $this->getDBkey() ),
2092 * Get the article ID for this Title from the link cache,
2093 * adding it if necessary
2094 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2096 * @return \type{\int} the ID
2098 public function getArticleID( $flags = 0 ) {
2099 if( $this->getNamespace() < 0 ) {
2100 return $this->mArticleID
= 0;
2102 $linkCache = LinkCache
::singleton();
2103 if( $flags & GAID_FOR_UPDATE
) {
2104 $oldUpdate = $linkCache->forUpdate( true );
2105 $linkCache->clearLink( $this );
2106 $this->mArticleID
= $linkCache->addLinkObj( $this );
2107 $linkCache->forUpdate( $oldUpdate );
2109 if( -1 == $this->mArticleID
) {
2110 $this->mArticleID
= $linkCache->addLinkObj( $this );
2113 return $this->mArticleID
;
2117 * Is this an article that is a redirect page?
2118 * Uses link cache, adding it if necessary
2119 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2120 * @return \type{\bool}
2122 public function isRedirect( $flags = 0 ) {
2123 if( !is_null($this->mRedirect
) )
2124 return $this->mRedirect
;
2125 # Calling getArticleID() loads the field from cache as needed
2126 if( !$this->getArticleID($flags) ) {
2127 return $this->mRedirect
= false;
2129 $linkCache = LinkCache
::singleton();
2130 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2132 return $this->mRedirect
;
2136 * What is the length of this page?
2137 * Uses link cache, adding it if necessary
2138 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2139 * @return \type{\bool}
2141 public function getLength( $flags = 0 ) {
2142 if( $this->mLength
!= -1 )
2143 return $this->mLength
;
2144 # Calling getArticleID() loads the field from cache as needed
2145 if( !$this->getArticleID($flags) ) {
2146 return $this->mLength
= 0;
2148 $linkCache = LinkCache
::singleton();
2149 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2151 return $this->mLength
;
2155 * What is the page_latest field for this page?
2156 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2157 * @return \type{\int} or false if the page doesn't exist
2159 public function getLatestRevID( $flags = 0 ) {
2160 if( $this->mLatestID
!== false )
2161 return $this->mLatestID
;
2163 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2164 $this->mLatestID
= (int)$db->selectField(
2165 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2166 return $this->mLatestID
;
2170 * This clears some fields in this object, and clears any associated
2171 * keys in the "bad links" section of the link cache.
2173 * - This is called from Article::insertNewArticle() to allow
2174 * loading of the new page_id. It's also called from
2175 * Article::doDeleteArticle()
2177 * @param $newid \type{\int} the new Article ID
2179 public function resetArticleID( $newid ) {
2180 $linkCache = LinkCache
::singleton();
2181 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2183 if ( $newid === false ) {
2184 $this->mArticleID
= -1;
2186 $this->mArticleID
= intval( $newid );
2188 $this->mRestrictionsLoaded
= false;
2189 $this->mRestrictions
= array();
2190 $this->mRedirect
= null;
2191 $this->mLength
= -1;
2192 $this->mLatestID
= false;
2196 * Updates page_touched for this page; called from LinksUpdate.php
2197 * @return \type{\bool} true if the update succeded
2199 public function invalidateCache() {
2200 if( wfReadOnly() ) {
2203 $dbw = wfGetDB( DB_MASTER
);
2204 $success = $dbw->update( 'page',
2205 array( 'page_touched' => $dbw->timestamp() ),
2209 HTMLFileCache
::clearFileCache( $this );
2214 * Prefix some arbitrary text with the namespace or interwiki prefix
2217 * @param $name \type{\string} the text
2218 * @return \type{\string} the prefixed text
2221 /* private */ function prefix( $name ) {
2223 if ( $this->mInterwiki
!= '' ) {
2224 $p = $this->mInterwiki
. ':';
2226 if ( 0 != $this->mNamespace
) {
2227 $p .= $this->getNsText() . ':';
2232 // Returns a simple regex that will match on characters and sequences invalid in titles.
2233 // Note that this doesn't pick up many things that could be wrong with titles, but that
2234 // replacing this regex with something valid will make many titles valid.
2235 static function getTitleInvalidRegex() {
2236 static $rxTc = false;
2238 # Matching titles will be held as illegal.
2240 # Any character not allowed is forbidden...
2241 '[^' . Title
::legalChars() . ']' .
2242 # URL percent encoding sequences interfere with the ability
2243 # to round-trip titles -- you can't link to them consistently.
2244 '|%[0-9A-Fa-f]{2}' .
2245 # XML/HTML character references produce similar issues.
2246 '|&[A-Za-z0-9\x80-\xff]+;' .
2248 '|&#x[0-9A-Fa-f]+;' .
2256 * Capitalize a text if it belongs to a namespace that capitalizes
2258 public static function capitalize( $text, $ns = NS_MAIN
) {
2261 if ( MWNamespace
::isCapitalized( $ns ) )
2262 return $wgContLang->ucfirst( $text );
2268 * Secure and split - main initialisation function for this object
2270 * Assumes that mDbkeyform has been set, and is urldecoded
2271 * and uses underscores, but not otherwise munged. This function
2272 * removes illegal characters, splits off the interwiki and
2273 * namespace prefixes, sets the other forms, and canonicalizes
2275 * @return \type{\bool} true on success
2277 private function secureAndSplit() {
2278 global $wgContLang, $wgLocalInterwiki;
2281 $rxTc = self
::getTitleInvalidRegex();
2283 $this->mInterwiki
= $this->mFragment
= '';
2284 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2286 $dbkey = $this->mDbkeyform
;
2288 # Strip Unicode bidi override characters.
2289 # Sometimes they slip into cut-n-pasted page titles, where the
2290 # override chars get included in list displays.
2291 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2293 # Clean up whitespace
2294 # Note: use of the /u option on preg_replace here will cause
2295 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2296 # conveniently disabling them.
2298 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2299 $dbkey = trim( $dbkey, '_' );
2301 if ( $dbkey == '' ) {
2305 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2306 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2310 $this->mDbkeyform
= $dbkey;
2312 # Initial colon indicates main namespace rather than specified default
2313 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2314 if ( ':' == $dbkey{0} ) {
2315 $this->mNamespace
= NS_MAIN
;
2316 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2317 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2320 # Namespace or interwiki prefix
2322 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2325 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2327 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2328 # Ordinary namespace
2330 $this->mNamespace
= $ns;
2331 # For Talk:X pages, check if X has a "namespace" prefix
2332 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2333 if( $wgContLang->getNsIndex( $x[1] ) )
2334 return false; # Disallow Talk:File:x type titles...
2335 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2336 return false; # Disallow Talk:Interwiki:x type titles...
2338 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2340 # Can't make a local interwiki link to an interwiki link.
2341 # That's just crazy!
2347 $this->mInterwiki
= $wgContLang->lc( $p );
2349 # Redundant interwiki prefix to the local wiki
2350 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2351 if( $dbkey == '' ) {
2352 # Can't have an empty self-link
2355 $this->mInterwiki
= '';
2357 # Do another namespace split...
2361 # If there's an initial colon after the interwiki, that also
2362 # resets the default namespace
2363 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2364 $this->mNamespace
= NS_MAIN
;
2365 $dbkey = substr( $dbkey, 1 );
2368 # If there's no recognized interwiki or namespace,
2369 # then let the colon expression be part of the title.
2374 # We already know that some pages won't be in the database!
2376 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2377 $this->mArticleID
= 0;
2379 $fragment = strstr( $dbkey, '#' );
2380 if ( false !== $fragment ) {
2381 $this->setFragment( $fragment );
2382 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2383 # remove whitespace again: prevents "Foo_bar_#"
2384 # becoming "Foo_bar_"
2385 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2388 # Reject illegal characters.
2390 if( preg_match( $rxTc, $dbkey ) ) {
2395 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2396 * reachable due to the way web browsers deal with 'relative' URLs.
2397 * Also, they conflict with subpage syntax. Forbid them explicitly.
2399 if ( strpos( $dbkey, '.' ) !== false &&
2400 ( $dbkey === '.' ||
$dbkey === '..' ||
2401 strpos( $dbkey, './' ) === 0 ||
2402 strpos( $dbkey, '../' ) === 0 ||
2403 strpos( $dbkey, '/./' ) !== false ||
2404 strpos( $dbkey, '/../' ) !== false ||
2405 substr( $dbkey, -2 ) == '/.' ||
2406 substr( $dbkey, -3 ) == '/..' ) )
2412 * Magic tilde sequences? Nu-uh!
2414 if( strpos( $dbkey, '~~~' ) !== false ) {
2419 * Limit the size of titles to 255 bytes.
2420 * This is typically the size of the underlying database field.
2421 * We make an exception for special pages, which don't need to be stored
2422 * in the database, and may edge over 255 bytes due to subpage syntax
2423 * for long titles, e.g. [[Special:Block/Long name]]
2425 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2426 strlen( $dbkey ) > 512 )
2432 * Normally, all wiki links are forced to have
2433 * an initial capital letter so [[foo]] and [[Foo]]
2434 * point to the same place.
2436 * Don't force it for interwikis, since the other
2437 * site might be case-sensitive.
2439 $this->mUserCaseDBKey
= $dbkey;
2440 if( $this->mInterwiki
== '') {
2441 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2445 * Can't make a link to a namespace alone...
2446 * "empty" local links can only be self-links
2447 * with a fragment identifier.
2450 $this->mInterwiki
== '' &&
2451 $this->mNamespace
!= NS_MAIN
) {
2454 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2455 // IP names are not allowed for accounts, and can only be referring to
2456 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2457 // there are numerous ways to present the same IP. Having sp:contribs scan
2458 // them all is silly and having some show the edits and others not is
2459 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2460 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2461 IP
::sanitizeIP( $dbkey ) : $dbkey;
2462 // Any remaining initial :s are illegal.
2463 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2468 $this->mDbkeyform
= $dbkey;
2469 $this->mUrlform
= wfUrlencode( $dbkey );
2471 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2477 * Set the fragment for this title. Removes the first character from the
2478 * specified fragment before setting, so it assumes you're passing it with
2481 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2482 * Still in active use privately.
2484 * @param $fragment \type{\string} text
2486 public function setFragment( $fragment ) {
2487 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2491 * Get a Title object associated with the talk page of this article
2492 * @return \type{Title} the object for the talk page
2494 public function getTalkPage() {
2495 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2499 * Get a title object associated with the subject page of this
2502 * @return \type{Title} the object for the subject page
2504 public function getSubjectPage() {
2505 // Is this the same title?
2506 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2507 if( $this->getNamespace() == $subjectNS ) {
2510 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2514 * Get an array of Title objects linking to this Title
2515 * Also stores the IDs in the link cache.
2517 * WARNING: do not use this function on arbitrary user-supplied titles!
2518 * On heavily-used templates it will max out the memory.
2520 * @param array $options may be FOR UPDATE
2521 * @return \type{\arrayof{Title}} the Title objects linking here
2523 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2524 $linkCache = LinkCache
::singleton();
2526 if ( count( $options ) > 0 ) {
2527 $db = wfGetDB( DB_MASTER
);
2529 $db = wfGetDB( DB_SLAVE
);
2532 $res = $db->select( array( 'page', $table ),
2533 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2535 "{$prefix}_from=page_id",
2536 "{$prefix}_namespace" => $this->getNamespace(),
2537 "{$prefix}_title" => $this->getDBkey() ),
2542 if ( $db->numRows( $res ) ) {
2543 foreach( $res as $row ) {
2544 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2545 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2546 $retVal[] = $titleObj;
2550 $db->freeResult( $res );
2555 * Get an array of Title objects using this Title as a template
2556 * Also stores the IDs in the link cache.
2558 * WARNING: do not use this function on arbitrary user-supplied titles!
2559 * On heavily-used templates it will max out the memory.
2561 * @param array $options may be FOR UPDATE
2562 * @return \type{\arrayof{Title}} the Title objects linking here
2564 public function getTemplateLinksTo( $options = array() ) {
2565 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2569 * Get an array of Title objects referring to non-existent articles linked from this page
2571 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2572 * @return \type{\arrayof{Title}} the Title objects
2574 public function getBrokenLinksFrom() {
2575 if ( $this->getArticleId() == 0 ) {
2576 # All links from article ID 0 are false positives
2580 $dbr = wfGetDB( DB_SLAVE
);
2581 $res = $dbr->select(
2582 array( 'page', 'pagelinks' ),
2583 array( 'pl_namespace', 'pl_title' ),
2585 'pl_from' => $this->getArticleId(),
2586 'page_namespace IS NULL'
2588 __METHOD__
, array(),
2592 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2598 foreach( $res as $row ) {
2599 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2606 * Get a list of URLs to purge from the Squid cache when this
2609 * @return \type{\arrayof{\string}} the URLs
2611 public function getSquidURLs() {
2615 $this->getInternalURL(),
2616 $this->getInternalURL( 'action=history' )
2619 // purge variant urls as well
2620 if($wgContLang->hasVariants()){
2621 $variants = $wgContLang->getVariants();
2622 foreach($variants as $vCode){
2623 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2624 $urls[] = $this->getInternalURL('',$vCode);
2632 * Purge all applicable Squid URLs
2634 public function purgeSquid() {
2636 if ( $wgUseSquid ) {
2637 $urls = $this->getSquidURLs();
2638 $u = new SquidUpdate( $urls );
2644 * Move this page without authentication
2645 * @param &$nt \type{Title} the new page Title
2647 public function moveNoAuth( &$nt ) {
2648 return $this->moveTo( $nt, false );
2652 * Check whether a given move operation would be valid.
2653 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2654 * @param &$nt \type{Title} the new title
2655 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2657 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2658 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2660 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2665 // Normally we'd add this to $errors, but we'll get
2666 // lots of syntax errors if $nt is not an object
2667 return array(array('badtitletext'));
2669 if( $this->equals( $nt ) ) {
2670 $errors[] = array('selfmove');
2672 if( !$this->isMovable() ) {
2673 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2675 if ( $nt->getInterwiki() != '' ) {
2676 $errors[] = array( 'immobile-target-namespace-iw' );
2678 if ( !$nt->isMovable() ) {
2679 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2682 $oldid = $this->getArticleID();
2683 $newid = $nt->getArticleID();
2685 if ( strlen( $nt->getDBkey() ) < 1 ) {
2686 $errors[] = array('articleexists');
2688 if ( ( $this->getDBkey() == '' ) ||
2690 ( $nt->getDBkey() == '' ) ) {
2691 $errors[] = array('badarticleerror');
2694 // Image-specific checks
2695 if( $this->getNamespace() == NS_FILE
) {
2696 $file = wfLocalFile( $this );
2697 if( $file->exists() ) {
2698 if( $nt->getNamespace() != NS_FILE
) {
2699 $errors[] = array('imagenocrossnamespace');
2701 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2702 $errors[] = array('imageinvalidfilename');
2704 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2705 $errors[] = array('imagetypemismatch');
2708 $destfile = wfLocalFile( $nt );
2709 if( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2710 $errors[] = array( 'file-exists-sharedrepo' );
2716 $errors = wfMergeErrorArrays( $errors,
2717 $this->getUserPermissionsErrors('move', $wgUser),
2718 $this->getUserPermissionsErrors('edit', $wgUser),
2719 $nt->getUserPermissionsErrors('move-target', $wgUser),
2720 $nt->getUserPermissionsErrors('edit', $wgUser) );
2723 $match = EditPage
::matchSummarySpamRegex( $reason );
2724 if( $match !== false ) {
2725 // This is kind of lame, won't display nice
2726 $errors[] = array('spamprotectiontext');
2730 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2731 $errors[] = array('hookaborted', $err);
2734 # The move is allowed only if (1) the target doesn't exist, or
2735 # (2) the target is a redirect to the source, and has no history
2736 # (so we can undo bad moves right after they're done).
2738 if ( 0 != $newid ) { # Target exists; check for validity
2739 if ( ! $this->isValidMoveTarget( $nt ) ) {
2740 $errors[] = array('articleexists');
2743 $tp = $nt->getTitleProtection();
2744 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2745 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2746 $errors[] = array('cantmove-titleprotected');
2755 * Move a title to a new location
2756 * @param &$nt \type{Title} the new title
2757 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2759 * @param $reason \type{\string} The reason for the move
2760 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2761 * Ignored if the user doesn't have the suppressredirect right.
2762 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2764 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2765 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2766 if( is_array( $err ) ) {
2770 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2771 $dbw = wfGetDB( DB_MASTER
);
2772 if( $this->getNamespace() == NS_FILE
) {
2773 $file = wfLocalFile( $this );
2774 if( $file->exists() ) {
2775 $status = $file->move( $nt );
2776 if( !$status->isOk() ) {
2777 return $status->getErrorsArray();
2782 $pageid = $this->getArticleID();
2783 $protected = $this->isProtected();
2784 if( $nt->exists() ) {
2785 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2786 $pageCountChange = ($createRedirect ?
0 : -1);
2787 } else { # Target didn't exist, do normal move.
2788 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2789 $pageCountChange = ($createRedirect ?
1 : 0);
2792 if( is_array( $err ) ) {
2795 $redirid = $this->getArticleID();
2797 // Category memberships include a sort key which may be customized.
2798 // If it's left as the default (the page title), we need to update
2799 // the sort key to match the new title.
2801 // Be careful to avoid resetting cl_timestamp, which may disturb
2802 // time-based lists on some sites.
2804 // Warning -- if the sort key is *explicitly* set to the old title,
2805 // we can't actually distinguish it from a default here, and it'll
2806 // be set to the new title even though it really shouldn't.
2807 // It'll get corrected on the next edit, but resetting cl_timestamp.
2808 $dbw->update( 'categorylinks',
2810 'cl_sortkey' => $nt->getPrefixedText(),
2811 'cl_timestamp=cl_timestamp' ),
2813 'cl_from' => $pageid,
2814 'cl_sortkey' => $this->getPrefixedText() ),
2818 # Protect the redirect title as the title used to be...
2819 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2821 'pr_page' => $redirid,
2822 'pr_type' => 'pr_type',
2823 'pr_level' => 'pr_level',
2824 'pr_cascade' => 'pr_cascade',
2825 'pr_user' => 'pr_user',
2826 'pr_expiry' => 'pr_expiry'
2828 array( 'pr_page' => $pageid ),
2832 # Update the protection log
2833 $log = new LogPage( 'protect' );
2834 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2835 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2836 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2840 $oldnamespace = $this->getNamespace() & ~
1;
2841 $newnamespace = $nt->getNamespace() & ~
1;
2842 $oldtitle = $this->getDBkey();
2843 $newtitle = $nt->getDBkey();
2845 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2846 WatchedItem
::duplicateEntries( $this, $nt );
2849 # Update search engine
2850 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2852 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2856 if( $this->isContentPage() && !$nt->isContentPage() ) {
2857 # No longer a content page
2858 # Not viewed, edited, removing
2859 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2860 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2861 # Now a content page
2862 # Not viewed, edited, adding
2863 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2864 } elseif( $pageCountChange ) {
2866 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2873 # Update message cache for interface messages
2874 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2875 global $wgMessageCache;
2877 # @bug 17860: old article can be deleted, if this the case,
2878 # delete it from message cache
2879 if ( $this->getArticleID() === 0 ) {
2880 $wgMessageCache->replace( $this->getDBkey(), false );
2882 $oldarticle = new Article( $this );
2883 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2886 $newarticle = new Article( $nt );
2887 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2891 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2896 * Move page to a title which is at present a redirect to the
2899 * @param &$nt \type{Title} the page to move to, which should currently
2901 * @param $reason \type{\string} The reason for the move
2902 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2903 * Ignored if the user doesn't have the suppressredirect right
2905 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2906 global $wgUseSquid, $wgUser, $wgContLang;
2908 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2911 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2913 # Truncate for whole multibyte characters. +5 bytes for ellipsis
2914 $comment = $wgContLang->truncate( $comment, 250 );
2916 $now = wfTimestampNow();
2917 $newid = $nt->getArticleID();
2918 $oldid = $this->getArticleID();
2919 $latest = $this->getLatestRevID();
2921 $dbw = wfGetDB( DB_MASTER
);
2923 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
2924 $newns = $nt->getNamespace();
2925 $newdbk = $nt->getDBkey();
2927 # Delete the old redirect. We don't save it to history since
2928 # by definition if we've got here it's rather uninteresting.
2929 # We have to remove it so that the next step doesn't trigger
2930 # a conflict on the unique namespace+title index...
2931 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
2932 if ( !$dbw->cascadingDeletes() ) {
2933 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2934 global $wgUseTrackbacks;
2935 if ($wgUseTrackbacks)
2936 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2937 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2938 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2939 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2940 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2941 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2942 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2943 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2945 // If the redirect was recently created, it may have an entry in recentchanges still
2946 $dbw->delete( 'recentchanges',
2947 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
2951 # Save a null revision in the page's history notifying of the move
2952 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2953 $nullRevId = $nullRevision->insertOn( $dbw );
2955 $article = new Article( $this );
2956 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2958 # Change the name of the target page:
2959 $dbw->update( 'page',
2961 'page_touched' => $dbw->timestamp($now),
2962 'page_namespace' => $nt->getNamespace(),
2963 'page_title' => $nt->getDBkey(),
2964 'page_latest' => $nullRevId,
2966 /* WHERE */ array( 'page_id' => $oldid ),
2969 $nt->resetArticleID( $oldid );
2971 # Recreate the redirect, this time in the other direction.
2972 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2973 $mwRedir = MagicWord
::get( 'redirect' );
2974 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2975 $redirectArticle = new Article( $this );
2976 $newid = $redirectArticle->insertOn( $dbw );
2977 $redirectRevision = new Revision( array(
2979 'comment' => $comment,
2980 'text' => $redirectText ) );
2981 $redirectRevision->insertOn( $dbw );
2982 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2984 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2986 # Now, we record the link from the redirect to the new title.
2987 # It should have no other outgoing links...
2988 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2989 $dbw->insert( 'pagelinks',
2991 'pl_from' => $newid,
2992 'pl_namespace' => $nt->getNamespace(),
2993 'pl_title' => $nt->getDBkey() ),
2995 $redirectSuppressed = false;
2997 $this->resetArticleID( 0 );
2998 $redirectSuppressed = true;
3002 $log = new LogPage( 'move' );
3003 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3006 if ( $wgUseSquid ) {
3007 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3008 $u = new SquidUpdate( $urls );
3015 * Move page to non-existing title.
3016 * @param &$nt \type{Title} the new Title
3017 * @param $reason \type{\string} The reason for the move
3018 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3019 * Ignored if the user doesn't have the suppressredirect right
3021 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3022 global $wgUseSquid, $wgUser, $wgContLang;
3024 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3026 $comment .= wfMsgExt( 'colon-separator',
3027 array( 'escapenoentities', 'content' ) );
3028 $comment .= $reason;
3030 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3031 $comment = $wgContLang->truncate( $comment, 250 );
3033 $newid = $nt->getArticleID();
3034 $oldid = $this->getArticleID();
3035 $latest = $this->getLatestRevId();
3037 $dbw = wfGetDB( DB_MASTER
);
3038 $now = $dbw->timestamp();
3040 # Save a null revision in the page's history notifying of the move
3041 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3042 if ( !is_object( $nullRevision ) ) {
3043 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3045 $nullRevId = $nullRevision->insertOn( $dbw );
3047 $article = new Article( $this );
3048 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
3051 $dbw->update( 'page',
3053 'page_touched' => $now,
3054 'page_namespace' => $nt->getNamespace(),
3055 'page_title' => $nt->getDBkey(),
3056 'page_latest' => $nullRevId,
3058 /* WHERE */ array( 'page_id' => $oldid ),
3061 $nt->resetArticleID( $oldid );
3063 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
3065 $mwRedir = MagicWord
::get( 'redirect' );
3066 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3067 $redirectArticle = new Article( $this );
3068 $newid = $redirectArticle->insertOn( $dbw );
3069 $redirectRevision = new Revision( array(
3071 'comment' => $comment,
3072 'text' => $redirectText ) );
3073 $redirectRevision->insertOn( $dbw );
3074 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3076 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
3078 # Record the just-created redirect's linking to the page
3079 $dbw->insert( 'pagelinks',
3081 'pl_from' => $newid,
3082 'pl_namespace' => $nt->getNamespace(),
3083 'pl_title' => $nt->getDBkey() ),
3085 $redirectSuppressed = false;
3087 $this->resetArticleID( 0 );
3088 $redirectSuppressed = true;
3092 $log = new LogPage( 'move' );
3093 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3095 # Purge caches as per article creation
3096 Article
::onArticleCreate( $nt );
3098 # Purge old title from squid
3099 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3100 $this->purgeSquid();
3105 * Move this page's subpages to be subpages of $nt
3106 * @param $nt Title Move target
3107 * @param $auth bool Whether $wgUser's permissions should be checked
3108 * @param $reason string The reason for the move
3109 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3110 * Ignored if the user doesn't have the 'suppressredirect' right
3111 * @return mixed array with old page titles as keys, and strings (new page titles) or
3112 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3114 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3115 global $wgMaximumMovedPages;
3116 // Check permissions
3117 if( !$this->userCan( 'move-subpages' ) )
3118 return array( 'cant-move-subpages' );
3119 // Do the source and target namespaces support subpages?
3120 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3121 return array( 'namespace-nosubpages',
3122 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3123 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3124 return array( 'namespace-nosubpages',
3125 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3127 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3130 foreach( $subpages as $oldSubpage ) {
3132 if( $count > $wgMaximumMovedPages ) {
3133 $retval[$oldSubpage->getPrefixedTitle()] =
3134 array( 'movepage-max-pages',
3135 $wgMaximumMovedPages );
3139 // We don't know whether this function was called before
3140 // or after moving the root page, so check both
3142 if( $oldSubpage->getArticleId() == $this->getArticleId() ||
3143 $oldSubpage->getArticleID() == $nt->getArticleId() )
3144 // When moving a page to a subpage of itself,
3145 // don't move it twice
3147 $newPageName = preg_replace(
3148 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3149 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3150 $oldSubpage->getDBkey() );
3151 if( $oldSubpage->isTalkPage() ) {
3152 $newNs = $nt->getTalkPage()->getNamespace();
3154 $newNs = $nt->getSubjectPage()->getNamespace();
3156 # Bug 14385: we need makeTitleSafe because the new page names may
3157 # be longer than 255 characters.
3158 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3160 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3161 if( $success === true ) {
3162 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3164 $retval[$oldSubpage->getPrefixedText()] = $success;
3171 * Checks if this page is just a one-rev redirect.
3172 * Adds lock, so don't use just for light purposes.
3174 * @return \type{\bool} TRUE or FALSE
3176 public function isSingleRevRedirect() {
3177 $dbw = wfGetDB( DB_MASTER
);
3179 $row = $dbw->selectRow( 'page',
3180 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3183 array( 'FOR UPDATE' )
3185 # Cache some fields we may want
3186 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3187 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3188 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3189 if( !$this->mRedirect
) {
3192 # Does the article have a history?
3193 $row = $dbw->selectField( array( 'page', 'revision'),
3195 array( 'page_namespace' => $this->getNamespace(),
3196 'page_title' => $this->getDBkey(),
3198 'page_latest != rev_id'
3201 array( 'FOR UPDATE' )
3203 # Return true if there was no history
3204 return ($row === false);
3208 * Checks if $this can be moved to a given Title
3209 * - Selects for update, so don't call it unless you mean business
3211 * @param &$nt \type{Title} the new title to check
3212 * @return \type{\bool} TRUE or FALSE
3214 public function isValidMoveTarget( $nt ) {
3215 $dbw = wfGetDB( DB_MASTER
);
3216 # Is it an existsing file?
3217 if( $nt->getNamespace() == NS_FILE
) {
3218 $file = wfLocalFile( $nt );
3219 if( $file->exists() ) {
3220 wfDebug( __METHOD__
. ": file exists\n" );
3224 # Is it a redirect with no history?
3225 if( !$nt->isSingleRevRedirect() ) {
3226 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3229 # Get the article text
3230 $rev = Revision
::newFromTitle( $nt );
3231 $text = $rev->getText();
3232 # Does the redirect point to the source?
3233 # Or is it a broken self-redirect, usually caused by namespace collisions?
3235 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3236 $redirTitle = Title
::newFromText( $m[1] );
3237 if( !is_object( $redirTitle ) ||
3238 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3239 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3240 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3245 wfDebug( __METHOD__
. ": failsafe\n" );
3252 * Can this title be added to a user's watchlist?
3254 * @return \type{\bool} TRUE or FALSE
3256 public function isWatchable() {
3257 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3261 * Get categories to which this Title belongs and return an array of
3262 * categories' names.
3264 * @return \type{\array} array an array of parents in the form:
3265 * $parent => $currentarticle
3267 public function getParentCategories() {
3270 $titlekey = $this->getArticleId();
3271 $dbr = wfGetDB( DB_SLAVE
);
3272 $categorylinks = $dbr->tableName( 'categorylinks' );
3275 $sql = "SELECT * FROM $categorylinks"
3276 ." WHERE cl_from='$titlekey'"
3277 ." AND cl_from <> '0'"
3278 ." ORDER BY cl_sortkey";
3280 $res = $dbr->query( $sql );
3282 if( $dbr->numRows( $res ) > 0 ) {
3283 foreach( $res as $row )
3284 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3285 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3286 $dbr->freeResult( $res );
3294 * Get a tree of parent categories
3295 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3296 * @return \type{\array} Tree of parent categories
3298 public function getParentCategoryTree( $children = array() ) {
3300 $parents = $this->getParentCategories();
3303 foreach( $parents as $parent => $current ) {
3304 if ( array_key_exists( $parent, $children ) ) {
3305 # Circular reference
3306 $stack[$parent] = array();
3308 $nt = Title
::newFromText($parent);
3310 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3322 * Get an associative array for selecting this title from
3325 * @return \type{\array} Selection array
3327 public function pageCond() {
3328 if( $this->mArticleID
> 0 ) {
3329 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3330 return array( 'page_id' => $this->mArticleID
);
3332 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3337 * Get the revision ID of the previous revision
3339 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3340 * @param $flags \type{\int} GAID_FOR_UPDATE
3341 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3343 public function getPreviousRevisionID( $revId, $flags=0 ) {
3344 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3345 return $db->selectField( 'revision', 'rev_id',
3347 'rev_page' => $this->getArticleId($flags),
3348 'rev_id < ' . intval( $revId )
3351 array( 'ORDER BY' => 'rev_id DESC' )
3356 * Get the revision ID of the next revision
3358 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3359 * @param $flags \type{\int} GAID_FOR_UPDATE
3360 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3362 public function getNextRevisionID( $revId, $flags=0 ) {
3363 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3364 return $db->selectField( 'revision', 'rev_id',
3366 'rev_page' => $this->getArticleId($flags),
3367 'rev_id > ' . intval( $revId )
3370 array( 'ORDER BY' => 'rev_id' )
3375 * Get the first revision of the page
3377 * @param $flags \type{\int} GAID_FOR_UPDATE
3378 * @return Revision (or NULL if page doesn't exist)
3380 public function getFirstRevision( $flags=0 ) {
3381 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3382 $pageId = $this->getArticleId($flags);
3383 if( !$pageId ) return null;
3384 $row = $db->selectRow( 'revision', '*',
3385 array( 'rev_page' => $pageId ),
3387 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3392 return new Revision( $row );
3397 * Check if this is a new page
3401 public function isNewPage() {
3402 $dbr = wfGetDB( DB_SLAVE
);
3403 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3407 * Get the oldest revision timestamp of this page
3409 * @return string, MW timestamp
3411 public function getEarliestRevTime() {
3412 $dbr = wfGetDB( DB_SLAVE
);
3413 if( $this->exists() ) {
3414 $min = $dbr->selectField( 'revision',
3415 'MIN(rev_timestamp)',
3416 array( 'rev_page' => $this->getArticleId() ),
3418 return wfTimestampOrNull( TS_MW
, $min );
3424 * Get the number of revisions between the given revision IDs.
3425 * Used for diffs and other things that really need it.
3427 * @param $old \type{\int} Revision ID.
3428 * @param $new \type{\int} Revision ID.
3429 * @return \type{\int} Number of revisions between these IDs.
3431 public function countRevisionsBetween( $old, $new ) {
3432 $dbr = wfGetDB( DB_SLAVE
);
3433 return (int)$dbr->selectField( 'revision', 'count(*)',
3434 'rev_page = ' . intval( $this->getArticleId() ) .
3435 ' AND rev_id > ' . intval( $old ) .
3436 ' AND rev_id < ' . intval( $new ),
3442 * Compare with another title.
3444 * @param \type{Title} $title
3445 * @return \type{\bool} TRUE or FALSE
3447 public function equals( Title
$title ) {
3448 // Note: === is necessary for proper matching of number-like titles.
3449 return $this->getInterwiki() === $title->getInterwiki()
3450 && $this->getNamespace() == $title->getNamespace()
3451 && $this->getDBkey() === $title->getDBkey();
3455 * Callback for usort() to do title sorts by (namespace, title)
3457 public static function compare( $a, $b ) {
3458 if( $a->getNamespace() == $b->getNamespace() ) {
3459 return strcmp( $a->getText(), $b->getText() );
3461 return $a->getNamespace() - $b->getNamespace();
3466 * Return a string representation of this title
3468 * @return \type{\string} String representation of this title
3470 public function __toString() {
3471 return $this->getPrefixedText();
3475 * Check if page exists. For historical reasons, this function simply
3476 * checks for the existence of the title in the page table, and will
3477 * thus return false for interwiki links, special pages and the like.
3478 * If you want to know if a title can be meaningfully viewed, you should
3479 * probably call the isKnown() method instead.
3481 * @return \type{\bool} TRUE or FALSE
3483 public function exists() {
3484 return $this->getArticleId() != 0;
3488 * Should links to this title be shown as potentially viewable (i.e. as
3489 * "bluelinks"), even if there's no record by this title in the page
3492 * This function is semi-deprecated for public use, as well as somewhat
3493 * misleadingly named. You probably just want to call isKnown(), which
3494 * calls this function internally.
3496 * (ISSUE: Most of these checks are cheap, but the file existence check
3497 * can potentially be quite expensive. Including it here fixes a lot of
3498 * existing code, but we might want to add an optional parameter to skip
3499 * it and any other expensive checks.)
3501 * @return \type{\bool} TRUE or FALSE
3503 public function isAlwaysKnown() {
3504 if( $this->mInterwiki
!= '' ) {
3505 return true; // any interwiki link might be viewable, for all we know
3507 switch( $this->mNamespace
) {
3510 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3512 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3514 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3516 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3517 // the full l10n of that language to be loaded. That takes much memory and
3518 // isn't needed. So we strip the language part away.
3519 // Also, extension messages which are not loaded, are shown as red, because
3520 // we don't call MessageCache::loadAllMessages.
3521 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3522 return wfMsgWeirdKey( $basename ); // known system message
3529 * Does this title refer to a page that can (or might) be meaningfully
3530 * viewed? In particular, this function may be used to determine if
3531 * links to the title should be rendered as "bluelinks" (as opposed to
3532 * "redlinks" to non-existent pages).
3534 * @return \type{\bool} TRUE or FALSE
3536 public function isKnown() {
3537 return $this->exists() ||
$this->isAlwaysKnown();
3541 * Is this in a namespace that allows actual pages?
3543 * @return \type{\bool} TRUE or FALSE
3545 public function canExist() {
3546 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3550 * Update page_touched timestamps and send squid purge messages for
3551 * pages linking to this title. May be sent to the job queue depending
3552 * on the number of links. Typically called on create and delete.
3554 public function touchLinks() {
3555 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3558 if ( $this->getNamespace() == NS_CATEGORY
) {
3559 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3565 * Get the last touched timestamp
3566 * @param Database $db, optional db
3567 * @return \type{\string} Last touched timestamp
3569 public function getTouched( $db = null ) {
3570 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3571 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3576 * Get the timestamp when this page was updated since the user last saw it.
3578 * @return mixed string/NULL
3580 public function getNotificationTimestamp( $user = null ) {
3581 global $wgUser, $wgShowUpdatedMarker;
3582 // Assume current user if none given
3583 if( !$user ) $user = $wgUser;
3584 // Check cache first
3585 $uid = $user->getId();
3586 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3587 return $this->mNotificationTimestamp
[$uid];
3589 if( !$uid ||
!$wgShowUpdatedMarker ) {
3590 return $this->mNotificationTimestamp
[$uid] = false;
3592 // Don't cache too much!
3593 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3594 $this->mNotificationTimestamp
= array();
3596 $dbr = wfGetDB( DB_SLAVE
);
3597 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3598 'wl_notificationtimestamp',
3599 array( 'wl_namespace' => $this->getNamespace(),
3600 'wl_title' => $this->getDBkey(),
3601 'wl_user' => $user->getId()
3605 return $this->mNotificationTimestamp
[$uid];
3609 * Get the trackback URL for this page
3610 * @return \type{\string} Trackback URL
3612 public function trackbackURL() {
3613 global $wgScriptPath, $wgServer, $wgScriptExtension;
3615 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3616 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3620 * Get the trackback RDF for this page
3621 * @return \type{\string} Trackback RDF
3623 public function trackbackRDF() {
3624 $url = htmlspecialchars($this->getFullURL());
3625 $title = htmlspecialchars($this->getText());
3626 $tburl = $this->trackbackURL();
3628 // Autodiscovery RDF is placed in comments so HTML validator
3629 // won't barf. This is a rather icky workaround, but seems
3630 // frequently used by this kind of RDF thingy.
3632 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3634 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3635 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3636 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3639 dc:identifier=\"$url\"
3641 trackback:ping=\"$tburl\" />
3647 * Generate strings used for xml 'id' names in monobook tabs
3648 * @return \type{\string} XML 'id' name
3650 public function getNamespaceKey( $prepend = 'nstab-' ) {
3652 // Gets the subject namespace if this title
3653 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3654 // Checks if cononical namespace name exists for namespace
3655 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3656 // Uses canonical namespace name
3657 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3659 // Uses text of namespace
3660 $namespaceKey = $this->getSubjectNsText();
3662 // Makes namespace key lowercase
3663 $namespaceKey = $wgContLang->lc( $namespaceKey );
3665 if ( $namespaceKey == '' ) {
3666 $namespaceKey = 'main';
3668 // Changes file to image for backwards compatibility
3669 if ( $namespaceKey == 'file' ) {
3670 $namespaceKey = 'image';
3672 return $prepend . $namespaceKey;
3676 * Returns true if this is a special page.
3678 public function isSpecialPage( ) {
3679 return $this->getNamespace() == NS_SPECIAL
;
3683 * Returns true if this title resolves to the named special page
3684 * @param $name \type{\string} The special page name
3686 public function isSpecial( $name ) {
3687 if ( $this->getNamespace() == NS_SPECIAL
) {
3688 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3689 if ( $name == $thisName ) {
3697 * If the Title refers to a special page alias which is not the local default,
3698 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3700 public function fixSpecialName() {
3701 if ( $this->getNamespace() == NS_SPECIAL
) {
3702 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3703 if ( $canonicalName ) {
3704 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3705 if ( $localName != $this->mDbkeyform
) {
3706 return Title
::makeTitle( NS_SPECIAL
, $localName );
3714 * Is this Title in a namespace which contains content?
3715 * In other words, is this a content page, for the purposes of calculating
3718 * @return \type{\bool} TRUE or FALSE
3720 public function isContentPage() {
3721 return MWNamespace
::isContent( $this->getNamespace() );
3725 * Get all extant redirects to this Title
3727 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3728 * NULL to consider all namespaces
3729 * @return \type{\arrayof{Title}} Redirects to this title
3731 public function getRedirectsHere( $ns = null ) {
3734 $dbr = wfGetDB( DB_SLAVE
);
3736 'rd_namespace' => $this->getNamespace(),
3737 'rd_title' => $this->getDBkey(),
3740 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3742 $res = $dbr->select(
3743 array( 'redirect', 'page' ),
3744 array( 'page_namespace', 'page_title' ),
3750 foreach( $res as $row ) {
3751 $redirs[] = self
::newFromRow( $row );
3757 * Check if this Title is a valid redirect target
3759 * @return \type{\bool} TRUE or FALSE
3761 public function isValidRedirectTarget() {
3762 global $wgInvalidRedirectTargets;
3764 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3765 if( $this->isSpecial( 'Userlogout' ) ) {
3769 foreach( $wgInvalidRedirectTargets as $target ) {
3770 if( $this->isSpecial( $target ) ) {
3779 * Get a backlink cache object
3781 function getBacklinkCache() {
3782 if ( is_null( $this->mBacklinkCache
) ) {
3783 $this->mBacklinkCache
= new BacklinkCache( $this );
3785 return $this->mBacklinkCache
;
3789 * Whether the magic words __INDEX__ and __NOINDEX__ function for
3793 public function canUseNoindex(){
3794 global $wgArticleRobotPolicies, $wgContentNamespaces,
3795 $wgExemptFromUserRobotsControl;
3797 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
3798 ?
$wgContentNamespaces
3799 : $wgExemptFromUserRobotsControl;
3801 return !in_array( $this->mNamespace
, $bannedNamespaces );
3805 public function getRestrictionTypes() {
3806 global $wgRestrictionTypes;
3807 $types = $this->exists() ?
$wgRestrictionTypes : array('create');
3809 if ( $this->getNamespace() == NS_FILE
) {
3810 $types[] = 'upload';
3813 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );