8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname( __FILE__
) . '/normal/UtfNormal.php' );
16 define ( 'GAID_FOR_UPDATE', 1 );
19 * Represents a title within MediaWiki.
20 * Optionally may contain an interwiki designation or namespace.
21 * @note This class can fetch various kinds of data from the database;
22 * however, it does so inefficiently.
24 * @internal documentation reviewed 15 Mar 2010
27 /** @name Static cache variables */
29 static private $titleCache = array();
30 static private $interwikiCache = array();
34 * Title::newFromText maintains a cache to avoid expensive re-normalization of
35 * commonly used titles. On a batch operation this can become a memory leak
36 * if not bounded. After hitting this many titles reset the cache.
38 const CACHE_MAX
= 1000;
42 * @name Private member variables
43 * Please use the accessor functions instead.
48 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; // /< URL-encoded form of the main part
50 var $mDbkeyform = ''; // /< Main part with underscores
51 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
54 var $mFragment; // /< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; // /< ID of most recent revision
57 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
61 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
62 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
63 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
64 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
65 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
66 var $mTitleProtection; ///< Cached value of getTitleProtection
67 # Don't change the following default, NS_MAIN is hardcoded in several
68 # places. See bug 696.
69 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
70 # Zero except in {{transclusion}} tags
71 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
72 var $mLength = -1; // /< The page length, 0 for special pages
73 var $mRedirect = null; // /< Is the article at this title a redirect?
74 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
75 var $mBacklinkCache = null; // /< Cache of links to this title
83 /* private */ function __construct() { }
86 * Create a new Title from a prefixed DB key
88 * @param $key \type{\string} The database key, which has underscores
89 * instead of spaces, possibly including namespace and
91 * @return \type{Title} the new object, or NULL on an error
93 public static function newFromDBkey( $key ) {
95 $t->mDbkeyform
= $key;
96 if ( $t->secureAndSplit() )
103 * Create a new Title from text, such as what one would find in a link. De-
104 * codes any HTML entities in the text.
106 * @param $text string The link text; spaces, prefixes, and an
107 * initial ':' indicating the main namespace are accepted.
108 * @param $defaultNamespace int The namespace to use if none is speci-
109 * fied by a prefix. If you want to force a specific namespace even if
110 * $text might begin with a namespace prefix, use makeTitle() or
112 * @return Title The new object, or null on an error.
114 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
115 if ( is_object( $text ) ) {
116 throw new MWException( 'Title::newFromText given an object' );
120 * Wiki pages often contain multiple links to the same page.
121 * Title normalization and parsing can become expensive on
122 * pages with many links, so we can save a little time by
125 * In theory these are value objects and won't get changed...
127 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
128 return Title
::$titleCache[$text];
132 * Convert things like é ā or 〗 into normalized(bug 14952) text
134 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
137 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
138 $t->mDefaultNamespace
= $defaultNamespace;
140 static $cachedcount = 0 ;
141 if ( $t->secureAndSplit() ) {
142 if ( $defaultNamespace == NS_MAIN
) {
143 if ( $cachedcount >= self
::CACHE_MAX
) {
144 # Avoid memory leaks on mass operations...
145 Title
::$titleCache = array();
149 Title
::$titleCache[$text] =& $t;
159 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
161 * Example of wrong and broken code:
162 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
164 * Example of right code:
165 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
167 * Create a new Title from URL-encoded text. Ensures that
168 * the given title's length does not exceed the maximum.
170 * @param $url \type{\string} the title, as might be taken from a URL
171 * @return \type{Title} the new object, or NULL on an error
173 public static function newFromURL( $url ) {
174 global $wgLegalTitleChars;
177 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
178 # but some URLs used it as a space replacement and they still come
179 # from some external search tools.
180 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
181 $url = str_replace( '+', ' ', $url );
184 $t->mDbkeyform
= str_replace( ' ', '_', $url );
185 if ( $t->secureAndSplit() ) {
193 * Create a new Title from an article ID
195 * @param $id \type{\int} the page_id corresponding to the Title to create
196 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
197 * @return \type{Title} the new object, or NULL on an error
199 public static function newFromID( $id, $flags = 0 ) {
200 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
201 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
202 if ( $row !== false ) {
203 $title = Title
::newFromRow( $row );
211 * Make an array of titles from an array of IDs
213 * @param $ids \type{\arrayof{\int}} Array of IDs
214 * @return \type{\arrayof{Title}} Array of Titles
216 public static function newFromIDs( $ids ) {
217 if ( !count( $ids ) ) {
220 $dbr = wfGetDB( DB_SLAVE
);
221 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
222 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
225 foreach ( $res as $row ) {
226 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
232 * Make a Title object from a DB row
234 * @param $row \type{Row} (needs at least page_title,page_namespace)
235 * @return \type{Title} corresponding Title
237 public static function newFromRow( $row ) {
238 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
240 $t->mArticleID
= isset( $row->page_id
) ?
intval( $row->page_id
) : -1;
241 $t->mLength
= isset( $row->page_len
) ?
intval( $row->page_len
) : -1;
242 $t->mRedirect
= isset( $row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
243 $t->mLatestID
= isset( $row->page_latest
) ?
$row->page_latest
: false;
249 * Create a new Title from a namespace index and a DB key.
250 * It's assumed that $ns and $title are *valid*, for instance when
251 * they came directly from the database or a special page name.
252 * For convenience, spaces are converted to underscores so that
253 * eg user_text fields can be used directly.
255 * @param $ns \type{\int} the namespace of the article
256 * @param $title \type{\string} the unprefixed database key form
257 * @param $fragment \type{\string} The link fragment (after the "#")
258 * @return \type{Title} the new object
260 public static function &makeTitle( $ns, $title, $fragment = '' ) {
263 $t->mFragment
= $fragment;
264 $t->mNamespace
= $ns = intval( $ns );
265 $t->mDbkeyform
= str_replace( ' ', '_', $title );
266 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
267 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
268 $t->mTextform
= str_replace( '_', ' ', $title );
273 * Create a new Title from a namespace index and a DB key.
274 * The parameters will be checked for validity, which is a bit slower
275 * than makeTitle() but safer for user-provided data.
277 * @param $ns \type{\int} the namespace of the article
278 * @param $title \type{\string} the database key form
279 * @param $fragment \type{\string} The link fragment (after the "#")
280 * @return \type{Title} the new object, or NULL on an error
282 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
284 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
285 if ( $t->secureAndSplit() ) {
293 * Create a new Title for the Main Page
295 * @return \type{Title} the new object
297 public static function newMainPage() {
298 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
299 // Don't give fatal errors if the message is broken
301 $title = Title
::newFromText( 'Main Page' );
307 * Extract a redirect destination from a string and return the
308 * Title, or null if the text doesn't contain a valid redirect
309 * This will only return the very next target, useful for
310 * the redirect table and other checks that don't need full recursion
312 * @param $text \type{\string} Text with possible redirect
313 * @return \type{Title} The corresponding Title
315 public static function newFromRedirect( $text ) {
316 return self
::newFromRedirectInternal( $text );
320 * Extract a redirect destination from a string and return the
321 * Title, or null if the text doesn't contain a valid redirect
322 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
323 * in order to provide (hopefully) the Title of the final destination instead of another redirect
325 * @param $text \type{\string} Text with possible redirect
326 * @return \type{Title} The corresponding Title
328 public static function newFromRedirectRecurse( $text ) {
329 $titles = self
::newFromRedirectArray( $text );
330 return $titles ?
array_pop( $titles ) : null;
334 * Extract a redirect destination from a string and return an
335 * array of Titles, or null if the text doesn't contain a valid redirect
336 * The last element in the array is the final destination after all redirects
337 * have been resolved (up to $wgMaxRedirects times)
339 * @param $text \type{\string} Text with possible redirect
340 * @return \type{\array} Array of Titles, with the destination last
342 public static function newFromRedirectArray( $text ) {
343 global $wgMaxRedirects;
344 // are redirects disabled?
345 if ( $wgMaxRedirects < 1 )
347 $title = self
::newFromRedirectInternal( $text );
348 if ( is_null( $title ) )
350 // recursive check to follow double redirects
351 $recurse = $wgMaxRedirects;
352 $titles = array( $title );
353 while ( --$recurse > 0 ) {
354 if ( $title->isRedirect() ) {
355 $article = new Article( $title, 0 );
356 $newtitle = $article->getRedirectTarget();
360 // Redirects to some special pages are not permitted
361 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
362 // the new title passes the checks, so make that our current title so that further recursion can be checked
364 $titles[] = $newtitle;
373 * Really extract the redirect destination
374 * Do not call this function directly, use one of the newFromRedirect* functions above
376 * @param $text \type{\string} Text with possible redirect
377 * @return \type{Title} The corresponding Title
379 protected static function newFromRedirectInternal( $text ) {
380 $redir = MagicWord
::get( 'redirect' );
381 $text = trim( $text );
382 if ( $redir->matchStartAndRemove( $text ) ) {
383 // Extract the first link and see if it's usable
384 // Ensure that it really does come directly after #REDIRECT
385 // Some older redirects included a colon, so don't freak about that!
387 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
388 // Strip preceding colon used to "escape" categories, etc.
389 // and URL-decode links
390 if ( strpos( $m[1], '%' ) !== false ) {
391 // Match behavior of inline link parsing here;
392 // don't interpret + as " " most of the time!
393 // It might be safe to just use rawurldecode instead, though.
394 $m[1] = urldecode( ltrim( $m[1], ':' ) );
396 $title = Title
::newFromText( $m[1] );
397 // If the title is a redirect to bad special pages or is invalid, return null
398 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
407 # ----------------------------------------------------------------------------
409 # ----------------------------------------------------------------------------
412 * Get the prefixed DB key associated with an ID
414 * @param $id \type{\int} the page_id of the article
415 * @return \type{Title} an object representing the article, or NULL
416 * if no such article was found
418 public static function nameOf( $id ) {
419 $dbr = wfGetDB( DB_SLAVE
);
421 $s = $dbr->selectRow( 'page',
422 array( 'page_namespace', 'page_title' ),
423 array( 'page_id' => $id ),
425 if ( $s === false ) { return null; }
427 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
432 * Get a regex character class describing the legal characters in a link
434 * @return \type{\string} the list of characters, not delimited
436 public static function legalChars() {
437 global $wgLegalTitleChars;
438 return $wgLegalTitleChars;
442 * Get a string representation of a title suitable for
443 * including in a search index
445 * @param $ns \type{\int} a namespace index
446 * @param $title \type{\string} text-form main part
447 * @return \type{\string} a stripped-down title string ready for the
450 public static function indexTitle( $ns, $title ) {
453 $lc = SearchEngine
::legalSearchChars() . '&#;';
454 $t = $wgContLang->normalizeForSearch( $title );
455 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
456 $t = $wgContLang->lc( $t );
459 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
460 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
462 $t = preg_replace( "/\\s+/", ' ', $t );
464 if ( $ns == NS_FILE
) {
465 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
471 * Make a prefixed DB key from a DB key and a namespace index
473 * @param $ns \type{\int} numerical representation of the namespace
474 * @param $title \type{\string} the DB key form the title
475 * @param $fragment \type{\string} The link fragment (after the "#")
476 * @return \type{\string} the prefixed form of the title
478 public static function makeName( $ns, $title, $fragment = '' ) {
481 $namespace = $wgContLang->getNsText( $ns );
482 $name = $namespace == '' ?
$title : "$namespace:$title";
483 if ( strval( $fragment ) != '' ) {
484 $name .= '#' . $fragment;
490 * Determine whether the object refers to a page within
493 * @return \type{\bool} TRUE if this is an in-project interwiki link
494 * or a wikilink, FALSE otherwise
496 public function isLocal() {
497 if ( $this->mInterwiki
!= '' ) {
498 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
505 * Determine whether the object refers to a page within
506 * this project and is transcludable.
508 * @return \type{\bool} TRUE if this is transcludable
510 public function isTrans() {
511 if ( $this->mInterwiki
== '' )
514 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
518 * Escape a text fragment, say from a link, for a URL
520 * @param $fragment string containing a URL or link fragment (after the "#")
521 * @return String: escaped string
523 static function escapeFragmentForURL( $fragment ) {
524 # Note that we don't urlencode the fragment. urlencoded Unicode
525 # fragments appear not to work in IE (at least up to 7) or in at least
526 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
527 # to care if they aren't encoded.
528 return Sanitizer
::escapeId( $fragment, 'noninitial' );
531 # ----------------------------------------------------------------------------
533 # ----------------------------------------------------------------------------
535 /** Simple accessors */
537 * Get the text form (spaces not underscores) of the main part
539 * @return \type{\string} Main part of the title
541 public function getText() { return $this->mTextform
; }
544 * Get the URL-encoded form of the main part
546 * @return \type{\string} Main part of the title, URL-encoded
548 public function getPartialURL() { return $this->mUrlform
; }
551 * Get the main part with underscores
553 * @return \type{\string} Main part of the title, with underscores
555 public function getDBkey() { return $this->mDbkeyform
; }
558 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
560 * @return \type{\int} Namespace index
562 public function getNamespace() { return $this->mNamespace
; }
565 * Get the namespace text
567 * @return \type{\string} Namespace text
569 public function getNsText() {
572 if ( $this->mInterwiki
!= '' ) {
573 // This probably shouldn't even happen. ohh man, oh yuck.
574 // But for interwiki transclusion it sometimes does.
575 // Shit. Shit shit shit.
577 // Use the canonical namespaces if possible to try to
578 // resolve a foreign namespace.
579 if ( MWNamespace
::exists( $this->mNamespace
) ) {
580 return MWNamespace
::getCanonicalName( $this->mNamespace
);
583 return $wgContLang->getNsText( $this->mNamespace
);
587 * Get the DB key with the initial letter case as specified by the user
589 * @return \type{\string} DB key
591 function getUserCaseDBKey() {
592 return $this->mUserCaseDBKey
;
596 * Get the namespace text of the subject (rather than talk) page
598 * @return \type{\string} Namespace text
600 public function getSubjectNsText() {
602 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
606 * Get the namespace text of the talk page
608 * @return \type{\string} Namespace text
610 public function getTalkNsText() {
612 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
616 * Could this title have a corresponding talk page?
618 * @return \type{\bool} TRUE or FALSE
620 public function canTalk() {
621 return( MWNamespace
::canTalk( $this->mNamespace
) );
625 * Get the interwiki prefix (or null string)
627 * @return \type{\string} Interwiki prefix
629 public function getInterwiki() { return $this->mInterwiki
; }
632 * Get the Title fragment (i.e.\ the bit after the #) in text form
634 * @return \type{\string} Title fragment
636 public function getFragment() { return $this->mFragment
; }
639 * Get the fragment in URL form, including the "#" character if there is one
640 * @return \type{\string} Fragment in URL form
642 public function getFragmentForURL() {
643 if ( $this->mFragment
== '' ) {
646 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
651 * Get the default namespace index, for when there is no namespace
653 * @return \type{\int} Default namespace index
655 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
658 * Get title for search index
660 * @return \type{\string} a stripped-down title string ready for the
663 public function getIndexTitle() {
664 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
668 * Get the prefixed database key form
670 * @return \type{\string} the prefixed title, with underscores and
671 * any interwiki and namespace prefixes
673 public function getPrefixedDBkey() {
674 $s = $this->prefix( $this->mDbkeyform
);
675 $s = str_replace( ' ', '_', $s );
680 * Get the prefixed title with spaces.
681 * This is the form usually used for display
683 * @return \type{\string} the prefixed title, with spaces
685 public function getPrefixedText() {
686 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
687 $s = $this->prefix( $this->mTextform
);
688 $s = str_replace( '_', ' ', $s );
689 $this->mPrefixedText
= $s;
691 return $this->mPrefixedText
;
695 * Get the prefixed title with spaces, plus any fragment
696 * (part beginning with '#')
698 * @return \type{\string} the prefixed title, with spaces and
699 * the fragment, including '#'
701 public function getFullText() {
702 $text = $this->getPrefixedText();
703 if ( $this->mFragment
!= '' ) {
704 $text .= '#' . $this->mFragment
;
710 * Get the base name, i.e. the leftmost parts before the /
712 * @return \type{\string} Base name
714 public function getBaseText() {
715 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
716 return $this->getText();
719 $parts = explode( '/', $this->getText() );
720 # Don't discard the real title if there's no subpage involved
721 if ( count( $parts ) > 1 )
722 unset( $parts[ count( $parts ) - 1 ] );
723 return implode( '/', $parts );
727 * Get the lowest-level subpage name, i.e. the rightmost part after /
729 * @return \type{\string} Subpage name
731 public function getSubpageText() {
732 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
733 return( $this->mTextform
);
735 $parts = explode( '/', $this->mTextform
);
736 return( $parts[ count( $parts ) - 1 ] );
740 * Get a URL-encoded form of the subpage text
742 * @return \type{\string} URL-encoded subpage name
744 public function getSubpageUrlForm() {
745 $text = $this->getSubpageText();
746 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
751 * Get a URL-encoded title (not an actual URL) including interwiki
753 * @return \type{\string} the URL-encoded form
755 public function getPrefixedURL() {
756 $s = $this->prefix( $this->mDbkeyform
);
757 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
762 * Get a real URL referring to this title, with interwiki link and
765 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
766 * links. Can be specified as an associative array as well, e.g.,
767 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
768 * @param $variant \type{\string} language variant of url (for sr, zh..)
769 * @return \type{\string} the URL
771 public function getFullURL( $query = '', $variant = false ) {
772 global $wgContLang, $wgServer, $wgRequest;
774 if ( is_array( $query ) ) {
775 $query = wfArrayToCGI( $query );
778 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
780 $url = $this->getLocalURL( $query, $variant );
782 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
783 // Correct fix would be to move the prepending elsewhere.
784 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
785 $url = $wgServer . $url;
788 $baseUrl = $interwiki->getURL( );
790 $namespace = wfUrlencode( $this->getNsText() );
791 if ( $namespace != '' ) {
792 # Can this actually happen? Interwikis shouldn't be parsed.
793 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
796 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
797 $url = wfAppendQuery( $url, $query );
800 # Finally, add the fragment.
801 $url .= $this->getFragmentForURL();
803 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
808 * Get a URL with no fragment or server name. If this page is generated
809 * with action=render, $wgServer is prepended.
811 * @param $query Mixed: an optional query string; if not specified,
812 * $wgArticlePath will be used. Can be specified as an associative array
813 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
815 * @param $variant \type{\string} language variant of url (for sr, zh..)
816 * @return \type{\string} the URL
818 public function getLocalURL( $query = '', $variant = false ) {
819 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
820 global $wgVariantArticlePath, $wgContLang, $wgUser;
822 if ( is_array( $query ) ) {
823 $query = wfArrayToCGI( $query );
826 // internal links should point to same variant as current page (only anonymous users)
827 if ( !$variant && $wgContLang->hasVariants() && !$wgUser->isLoggedIn() ) {
828 $pref = $wgContLang->getPreferredVariant( false );
829 if ( $pref != $wgContLang->getCode() )
833 if ( $this->isExternal() ) {
834 $url = $this->getFullURL();
836 // This is currently only used for edit section links in the
837 // context of interwiki transclusion. In theory we should
838 // append the query to the end of any existing query string,
839 // but interwiki transclusion is already broken in that case.
843 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
844 if ( $query == '' ) {
845 if ( $variant != false && $wgContLang->hasVariants() ) {
846 if ( !$wgVariantArticlePath ) {
847 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
849 $variantArticlePath = $wgVariantArticlePath;
851 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
852 $url = str_replace( '$1', $dbkey, $url );
854 $url = str_replace( '$1', $dbkey, $wgArticlePath );
857 global $wgActionPaths;
860 if ( !empty( $wgActionPaths ) &&
861 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
863 $action = urldecode( $matches[2] );
864 if ( isset( $wgActionPaths[$action] ) ) {
865 $query = $matches[1];
866 if ( isset( $matches[4] ) ) $query .= $matches[4];
867 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
868 if ( $query != '' ) {
869 $url = wfAppendQuery( $url, $query );
873 if ( $url === false ) {
874 if ( $query == '-' ) {
877 $url = "{$wgScript}?title={$dbkey}&{$query}";
881 // FIXME: this causes breakage in various places when we
882 // actually expected a local URL and end up with dupe prefixes.
883 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
884 $url = $wgServer . $url;
887 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
892 * Get a URL that's the simplest URL that will be valid to link, locally,
893 * to the current Title. It includes the fragment, but does not include
894 * the server unless action=render is used (or the link is external). If
895 * there's a fragment but the prefixed text is empty, we just return a link
898 * The result obviously should not be URL-escaped, but does need to be
899 * HTML-escaped if it's being output in HTML.
901 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
902 * query string. Keys and values will be escaped.
903 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
904 * for external links. Default is "false" (same variant as current page,
905 * for anonymous users).
906 * @return \type{\string} the URL
908 public function getLinkUrl( $query = array(), $variant = false ) {
909 wfProfileIn( __METHOD__
);
910 if ( $this->isExternal() ) {
911 $ret = $this->getFullURL( $query );
912 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
913 $ret = $this->getFragmentForURL();
915 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
917 wfProfileOut( __METHOD__
);
922 * Get an HTML-escaped version of the URL form, suitable for
923 * using in a link, without a server name or fragment
925 * @param $query \type{\string} an optional query string
926 * @return \type{\string} the URL
928 public function escapeLocalURL( $query = '' ) {
929 return htmlspecialchars( $this->getLocalURL( $query ) );
933 * Get an HTML-escaped version of the URL form, suitable for
934 * using in a link, including the server name and fragment
936 * @param $query \type{\string} an optional query string
937 * @return \type{\string} the URL
939 public function escapeFullURL( $query = '' ) {
940 return htmlspecialchars( $this->getFullURL( $query ) );
944 * Get the URL form for an internal link.
945 * - Used in various Squid-related code, in case we have a different
946 * internal hostname for the server from the exposed one.
948 * @param $query \type{\string} an optional query string
949 * @param $variant \type{\string} language variant of url (for sr, zh..)
950 * @return \type{\string} the URL
952 public function getInternalURL( $query = '', $variant = false ) {
953 global $wgInternalServer;
954 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
955 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
960 * Get the edit URL for this Title
962 * @return \type{\string} the URL, or a null string if this is an
965 public function getEditURL() {
966 if ( $this->mInterwiki
!= '' ) { return ''; }
967 $s = $this->getLocalURL( 'action=edit' );
973 * Get the HTML-escaped displayable text form.
974 * Used for the title field in <a> tags.
976 * @return \type{\string} the text, including any prefixes
978 public function getEscapedText() {
979 return htmlspecialchars( $this->getPrefixedText() );
983 * Is this Title interwiki?
985 * @return \type{\bool}
987 public function isExternal() { return ( $this->mInterwiki
!= '' ); }
990 * Is this page "semi-protected" - the *only* protection is autoconfirm?
992 * @param $action \type{\string} Action to check (default: edit)
993 * @return \type{\bool}
995 public function isSemiProtected( $action = 'edit' ) {
996 if ( $this->exists() ) {
997 $restrictions = $this->getRestrictions( $action );
998 if ( count( $restrictions ) > 0 ) {
999 foreach ( $restrictions as $restriction ) {
1000 if ( strtolower( $restriction ) != 'autoconfirmed' )
1009 # If it doesn't exist, it can't be protected
1015 * Does the title correspond to a protected article?
1017 * @param $action \type{\string} the action the page is protected from,
1018 * by default checks all actions.
1019 * @return \type{\bool}
1021 public function isProtected( $action = '' ) {
1022 global $wgRestrictionLevels;
1024 $restrictionTypes = $this->getRestrictionTypes();
1026 # Special pages have inherent protection
1027 if( $this->getNamespace() == NS_SPECIAL
)
1030 # Check regular protection levels
1031 foreach ( $restrictionTypes as $type ) {
1032 if ( $action == $type ||
$action == '' ) {
1033 $r = $this->getRestrictions( $type );
1034 foreach ( $wgRestrictionLevels as $level ) {
1035 if ( in_array( $level, $r ) && $level != '' ) {
1046 * Is this a conversion table for the LanguageConverter?
1048 * @return \type{\bool}
1050 public function isConversionTable() {
1051 if($this->getNamespace() == NS_MEDIAWIKI
1052 && strpos( $this->getText(), 'Conversiontable' ) !== false ) {
1060 * Is $wgUser watching this page?
1062 * @return \type{\bool}
1064 public function userIsWatching() {
1067 if ( is_null( $this->mWatched
) ) {
1068 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1069 $this->mWatched
= false;
1071 $this->mWatched
= $wgUser->isWatched( $this );
1074 return $this->mWatched
;
1078 * Can $wgUser perform $action on this page?
1079 * This skips potentially expensive cascading permission checks
1080 * as well as avoids expensive error formatting
1082 * Suitable for use for nonessential UI controls in common cases, but
1083 * _not_ for functional access control.
1085 * May provide false positives, but should never provide a false negative.
1087 * @param $action \type{\string} action that permission needs to be checked for
1088 * @return \type{\bool}
1090 public function quickUserCan( $action ) {
1091 return $this->userCan( $action, false );
1095 * Determines if $wgUser is unable to edit this page because it has been protected
1096 * by $wgNamespaceProtection.
1098 * @return \type{\bool}
1100 public function isNamespaceProtected() {
1101 global $wgNamespaceProtection, $wgUser;
1102 if ( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1103 foreach ( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1104 if ( $right != '' && !$wgUser->isAllowed( $right ) )
1112 * Can $wgUser perform $action on this page?
1114 * @param $action \type{\string} action that permission needs to be checked for
1115 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1116 * @return \type{\bool}
1118 public function userCan( $action, $doExpensiveQueries = true ) {
1120 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1124 * Can $user perform $action on this page?
1126 * FIXME: This *does not* check throttles (User::pingLimiter()).
1128 * @param $action \type{\string}action that permission needs to be checked for
1129 * @param $user \type{User} user to check
1130 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1131 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1132 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1134 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1135 if ( !StubObject
::isRealObject( $user ) ) {
1136 // Since StubObject is always used on globals, we can
1137 // unstub $wgUser here and set $user = $wgUser
1139 $wgUser->_unstub( '', 5 );
1143 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1145 // Remove the errors being ignored.
1146 foreach ( $errors as $index => $error ) {
1147 $error_key = is_array( $error ) ?
$error[0] : $error;
1149 if ( in_array( $error_key, $ignoreErrors ) ) {
1150 unset( $errors[$index] );
1158 * Permissions checks that fail most often, and which are easiest to test.
1160 * @param $action String the action to check
1161 * @param $user User user to check
1162 * @param $errors Array list of current errors
1163 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1164 * @param $short Boolean short circuit on first error
1166 * @return Array list of errors
1168 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1169 if ( $action == 'create' ) {
1170 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1171 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1172 $errors[] = $user->isAnon() ?
array ( 'nocreatetext' ) : array ( 'nocreate-loggedin' );
1174 } elseif ( $action == 'move' ) {
1175 if ( !$user->isAllowed( 'move-rootuserpages' )
1176 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1177 // Show user page-specific message only if the user can move other pages
1178 $errors[] = array( 'cant-move-user-page' );
1181 // Check if user is allowed to move files if it's a file
1182 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1183 $errors[] = array( 'movenotallowedfile' );
1186 if ( !$user->isAllowed( 'move' ) ) {
1187 // User can't move anything
1188 global $wgGroupPermissions;
1189 $userCanMove = false;
1190 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1191 $userCanMove = $wgGroupPermissions['user']['move'];
1193 $autoconfirmedCanMove = false;
1194 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1195 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1197 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1198 // custom message if logged-in users without any special rights can move
1199 $errors[] = array ( 'movenologintext' );
1201 $errors[] = array ( 'movenotallowed' );
1204 } elseif ( $action == 'move-target' ) {
1205 if ( !$user->isAllowed( 'move' ) ) {
1206 // User can't move anything
1207 $errors[] = array ( 'movenotallowed' );
1208 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1209 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1210 // Show user page-specific message only if the user can move other pages
1211 $errors[] = array( 'cant-move-to-user-page' );
1213 } elseif ( !$user->isAllowed( $action ) ) {
1216 // We avoid expensive display logic for quickUserCan's and such
1219 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1220 User
::getGroupsWithPermission( $action ) );
1227 $wgLang->commaList( $groups ),
1231 $return = array( "badaccess-group0" );
1233 $errors[] = $return;
1240 * Add the resulting error code to the errors array
1242 * @param $errors Array list of current errors
1243 * @param $result Mixed result of errors
1245 * @return Array list of errors
1247 private function resultToError( $errors, $result ) {
1248 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1249 // A single array representing an error
1250 $errors[] = $result;
1251 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1252 // A nested array representing multiple errors
1253 $errors = array_merge( $errors, $result );
1254 } else if ( $result !== '' && is_string( $result ) ) {
1255 // A string representing a message-id
1256 $errors[] = array( $result );
1257 } else if ( $result === false ) {
1258 // a generic "We don't want them to do that"
1259 $errors[] = array( 'badaccess-group0' );
1265 * Check various permission hooks
1266 * @see checkQuickPermissions for parameter information
1268 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1269 // Use getUserPermissionsErrors instead
1270 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1271 return $result ?
array() : array( array( 'badaccess-group0' ) );
1273 // Check getUserPermissionsErrors hook
1274 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1275 $errors = $this->resultToError( $errors, $result );
1277 // Check getUserPermissionsErrorsExpensive hook
1278 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1279 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1280 $errors = $this->resultToError( $errors, $result );
1287 * Check permissions on special pages & namespaces
1288 * @see checkQuickPermissions for parameter information
1290 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1291 # Only 'createaccount' and 'execute' can be performed on
1292 # special pages, which don't actually exist in the DB.
1293 $specialOKActions = array( 'createaccount', 'execute' );
1294 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1295 $errors[] = array( 'ns-specialprotected' );
1298 # Check $wgNamespaceProtection for restricted namespaces
1299 if ( $this->isNamespaceProtected() ) {
1300 $ns = $this->mNamespace
== NS_MAIN ?
1301 wfMsg( 'nstab-main' ) : $this->getNsText();
1302 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1303 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1310 * Check CSS/JS sub-page permissions
1311 * @see checkQuickPermissions for parameter information
1313 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1314 # Protect css/js subpages of user pages
1315 # XXX: this might be better using restrictions
1316 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1317 # and $this->userCanEditJsSubpage() from working
1318 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1319 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1320 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1321 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1322 $errors[] = array( 'customcssjsprotected' );
1323 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1324 $errors[] = array( 'customcssjsprotected' );
1332 * Check against page_restrictions table requirements on this
1333 * page. The user must possess all required rights for this
1335 * @see checkQuickPermissions for parameter information
1337 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1338 foreach ( $this->getRestrictions( $action ) as $right ) {
1339 // Backwards compatibility, rewrite sysop -> protect
1340 if ( $right == 'sysop' ) {
1343 if ( $right != '' && !$user->isAllowed( $right ) ) {
1344 // Users with 'editprotected' permission can edit protected pages
1345 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1346 // Users with 'editprotected' permission cannot edit protected pages
1347 // with cascading option turned on.
1348 if ( $this->mCascadeRestriction
) {
1349 $errors[] = array( 'protectedpagetext', $right );
1352 $errors[] = array( 'protectedpagetext', $right );
1361 * Check restrictions on cascading pages.
1362 * @see checkQuickPermissions for parameter information
1364 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1365 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1366 # We /could/ use the protection level on the source page, but it's
1367 # fairly ugly as we have to establish a precedence hierarchy for pages
1368 # included by multiple cascade-protected pages. So just restrict
1369 # it to people with 'protect' permission, as they could remove the
1370 # protection anyway.
1371 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1372 # Cascading protection depends on more than this page...
1373 # Several cascading protected pages may include this page...
1374 # Check each cascading level
1375 # This is only for protection restrictions, not for all actions
1376 if ( isset( $restrictions[$action] ) ) {
1377 foreach ( $restrictions[$action] as $right ) {
1378 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1379 if ( $right != '' && !$user->isAllowed( $right ) ) {
1381 foreach ( $cascadingSources as $page )
1382 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1383 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1393 * Check action permissions not already checked in checkQuickPermissions
1394 * @see checkQuickPermissions for parameter information
1396 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1397 if ( $action == 'protect' ) {
1398 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1399 // If they can't edit, they shouldn't protect.
1400 $errors[] = array( 'protect-cantedit' );
1402 } elseif ( $action == 'create' ) {
1403 $title_protection = $this->getTitleProtection();
1404 if( $title_protection ) {
1405 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1406 $title_protection['pt_create_perm'] = 'protect'; // B/C
1408 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1409 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1412 } elseif ( $action == 'move' ) {
1413 // Check for immobile pages
1414 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1415 // Specific message for this case
1416 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1417 } elseif ( !$this->isMovable() ) {
1418 // Less specific message for rarer cases
1419 $errors[] = array( 'immobile-page' );
1421 } elseif ( $action == 'move-target' ) {
1422 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1423 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1424 } elseif ( !$this->isMovable() ) {
1425 $errors[] = array( 'immobile-target-page' );
1432 * Check that the user isn't blocked from editting.
1433 * @see checkQuickPermissions for parameter information
1435 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1442 global $wgEmailConfirmToEdit;
1444 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1445 $errors[] = array( 'confirmedittext' );
1448 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1449 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1450 $block = $user->mBlock
;
1452 // This is from OutputPage::blockedPage
1453 // Copied at r23888 by werdna
1455 $id = $user->blockedBy();
1456 $reason = $user->blockedFor();
1457 if ( $reason == '' ) {
1458 $reason = wfMsg( 'blockednoreason' );
1462 if ( is_numeric( $id ) ) {
1463 $name = User
::whoIs( $id );
1468 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1469 $blockid = $block->mId
;
1470 $blockExpiry = $user->mBlock
->mExpiry
;
1471 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1472 if ( $blockExpiry == 'infinity' ) {
1473 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1474 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1476 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1477 if ( !strpos( $option, ':' ) )
1480 list ( $show, $value ) = explode( ":", $option );
1482 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1483 $blockExpiry = $show;
1488 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1491 $intended = $user->mBlock
->mAddress
;
1493 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1494 $blockid, $blockExpiry, $intended, $blockTimestamp );
1501 * Can $user perform $action on this page? This is an internal function,
1502 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1503 * checks on wfReadOnly() and blocks)
1505 * @param $action \type{\string} action that permission needs to be checked for
1506 * @param $user \type{User} user to check
1507 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1508 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1509 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1511 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1512 wfProfileIn( __METHOD__
);
1515 $checks = array( 'checkQuickPermissions',
1516 'checkPermissionHooks',
1517 'checkSpecialsAndNSPermissions',
1518 'checkCSSandJSPermissions',
1519 'checkPageRestrictions',
1520 'checkCascadingSourcesRestrictions',
1521 'checkActionPermissions',
1524 while( count( $checks ) > 0 &&
1525 !( $short && count( $errors ) > 0 ) ) {
1526 $method = array_shift( $checks );
1527 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1530 wfProfileOut( __METHOD__
);
1535 * Is this title subject to title protection?
1537 * @return \type{\mixed} An associative array representing any existent title
1538 * protection, or false if there's none.
1540 private function getTitleProtection() {
1541 // Can't protect pages in special namespaces
1542 if ( $this->getNamespace() < 0 ) {
1546 // Can't protect pages that exist.
1547 if ( $this->exists() ) {
1551 if ( !isset( $this->mTitleProtection
) ) {
1552 $dbr = wfGetDB( DB_SLAVE
);
1553 $res = $dbr->select( 'protected_titles', '*',
1554 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1557 // fetchRow returns false if there are no rows.
1558 $this->mTitleProtection
= $dbr->fetchRow( $res );
1560 return $this->mTitleProtection
;
1564 * Update the title protection status
1566 * @param $create_perm \type{\string} Permission required for creation
1567 * @param $reason \type{\string} Reason for protection
1568 * @param $expiry \type{\string} Expiry timestamp
1569 * @return boolean true
1571 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1572 global $wgUser, $wgContLang;
1574 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1575 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1580 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1582 $dbw = wfGetDB( DB_MASTER
);
1584 $encodedExpiry = Block
::encodeExpiry( $expiry, $dbw );
1586 $expiry_description = '';
1587 if ( $encodedExpiry != 'infinity' ) {
1588 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1589 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1592 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1595 # Update protection table
1596 if ( $create_perm != '' ) {
1597 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1599 'pt_namespace' => $namespace,
1600 'pt_title' => $title,
1601 'pt_create_perm' => $create_perm,
1602 'pt_timestamp' => Block
::encodeExpiry( wfTimestampNow(), $dbw ),
1603 'pt_expiry' => $encodedExpiry,
1604 'pt_user' => $wgUser->getId(),
1605 'pt_reason' => $reason,
1609 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1610 'pt_title' => $title ), __METHOD__
);
1612 # Update the protection log
1613 if ( $dbw->affectedRows() ) {
1614 $log = new LogPage( 'protect' );
1616 if ( $create_perm ) {
1617 $params = array( "[create=$create_perm] $expiry_description", '' );
1618 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1620 $log->addEntry( 'unprotect', $this, $reason );
1628 * Remove any title protection due to page existing
1630 public function deleteTitleProtection() {
1631 $dbw = wfGetDB( DB_MASTER
);
1633 $dbw->delete( 'protected_titles',
1634 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1639 * Would anybody with sufficient privileges be able to move this page?
1640 * Some pages just aren't movable.
1642 * @return \type{\bool} TRUE or FALSE
1644 public function isMovable() {
1645 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1649 * Can $wgUser read this page?
1651 * @return \type{\bool}
1652 * @todo fold these checks into userCan()
1654 public function userCanRead() {
1655 global $wgUser, $wgGroupPermissions;
1657 static $useShortcut = null;
1659 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1660 if ( is_null( $useShortcut ) ) {
1661 global $wgRevokePermissions;
1662 $useShortcut = true;
1663 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1664 # Not a public wiki, so no shortcut
1665 $useShortcut = false;
1666 } elseif ( !empty( $wgRevokePermissions ) ) {
1668 * Iterate through each group with permissions being revoked (key not included since we don't care
1669 * what the group name is), then check if the read permission is being revoked. If it is, then
1670 * we don't use the shortcut below since the user might not be able to read, even though anon
1671 * reading is allowed.
1673 foreach ( $wgRevokePermissions as $perms ) {
1674 if ( !empty( $perms['read'] ) ) {
1675 # We might be removing the read right from the user, so no shortcut
1676 $useShortcut = false;
1684 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1685 if ( $result !== null ) {
1689 # Shortcut for public wikis, allows skipping quite a bit of code
1693 if ( $wgUser->isAllowed( 'read' ) ) {
1696 global $wgWhitelistRead;
1699 * Always grant access to the login page.
1700 * Even anons need to be able to log in.
1702 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1707 * Bail out if there isn't whitelist
1709 if ( !is_array( $wgWhitelistRead ) ) {
1714 * Check for explicit whitelisting
1716 $name = $this->getPrefixedText();
1717 $dbName = $this->getPrefixedDBKey();
1718 // Check with and without underscores
1719 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1723 * Old settings might have the title prefixed with
1724 * a colon for main-namespace pages
1726 if ( $this->getNamespace() == NS_MAIN
) {
1727 if ( in_array( ':' . $name, $wgWhitelistRead ) )
1732 * If it's a special page, ditch the subpage bit
1735 if ( $this->getNamespace() == NS_SPECIAL
) {
1736 $name = $this->getDBkey();
1737 list( $name, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $name );
1738 if ( $name === false ) {
1739 # Invalid special page, but we show standard login required message
1743 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1744 if ( in_array( $pure, $wgWhitelistRead, true ) )
1753 * Is this a talk page of some sort?
1755 * @return \type{\bool}
1757 public function isTalkPage() {
1758 return MWNamespace
::isTalk( $this->getNamespace() );
1762 * Is this a subpage?
1764 * @return \type{\bool}
1766 public function isSubpage() {
1767 return MWNamespace
::hasSubpages( $this->mNamespace
)
1768 ?
strpos( $this->getText(), '/' ) !== false
1773 * Does this have subpages? (Warning, usually requires an extra DB query.)
1775 * @return \type{\bool}
1777 public function hasSubpages() {
1778 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1783 # We dynamically add a member variable for the purpose of this method
1784 # alone to cache the result. There's no point in having it hanging
1785 # around uninitialized in every Title object; therefore we only add it
1786 # if needed and don't declare it statically.
1787 if ( isset( $this->mHasSubpages
) ) {
1788 return $this->mHasSubpages
;
1791 $subpages = $this->getSubpages( 1 );
1792 if ( $subpages instanceof TitleArray
)
1793 return $this->mHasSubpages
= (bool)$subpages->count();
1794 return $this->mHasSubpages
= false;
1798 * Get all subpages of this page.
1800 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1801 * @return mixed TitleArray, or empty array if this page's namespace
1802 * doesn't allow subpages
1804 public function getSubpages( $limit = -1 ) {
1805 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1808 $dbr = wfGetDB( DB_SLAVE
);
1809 $conds['page_namespace'] = $this->getNamespace();
1810 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1813 $options['LIMIT'] = $limit;
1814 return $this->mSubpages
= TitleArray
::newFromResult(
1815 $dbr->select( 'page',
1816 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1825 * Could this page contain custom CSS or JavaScript, based
1828 * @return \type{\bool}
1830 public function isCssOrJsPage() {
1831 return $this->mNamespace
== NS_MEDIAWIKI
1832 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1836 * Is this a .css or .js subpage of a user page?
1837 * @return \type{\bool}
1839 public function isCssJsSubpage() {
1840 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1844 * Is this a *valid* .css or .js subpage of a user page?
1845 * Check that the corresponding skin exists
1847 * @return \type{\bool}
1849 public function isValidCssJsSubpage() {
1850 if ( $this->isCssJsSubpage() ) {
1851 $name = $this->getSkinFromCssJsSubpage();
1852 if ( $name == 'common' ) return true;
1853 $skinNames = Skin
::getSkinNames();
1854 return array_key_exists( $name, $skinNames );
1861 * Trim down a .css or .js subpage title to get the corresponding skin name
1863 * @return string containing skin name from .css or .js subpage title
1865 public function getSkinFromCssJsSubpage() {
1866 $subpage = explode( '/', $this->mTextform
);
1867 $subpage = $subpage[ count( $subpage ) - 1 ];
1868 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1872 * Is this a .css subpage of a user page?
1874 * @return \type{\bool}
1876 public function isCssSubpage() {
1877 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1881 * Is this a .js subpage of a user page?
1883 * @return \type{\bool}
1885 public function isJsSubpage() {
1886 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1890 * Protect css subpages of user pages: can $wgUser edit
1893 * @return \type{\bool}
1894 * @todo XXX: this might be better using restrictions
1896 public function userCanEditCssSubpage() {
1898 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
1899 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1902 * Protect js subpages of user pages: can $wgUser edit
1905 * @return \type{\bool}
1906 * @todo XXX: this might be better using restrictions
1908 public function userCanEditJsSubpage() {
1910 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
1911 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1915 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1917 * @return \type{\bool} If the page is subject to cascading restrictions.
1919 public function isCascadeProtected() {
1920 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1921 return ( $sources > 0 );
1925 * Cascading protection: Get the source of any cascading restrictions on this page.
1927 * @param $getPages \type{\bool} Whether or not to retrieve the actual pages
1928 * that the restrictions have come from.
1929 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1930 * objects of the pages from which cascading restrictions have come,
1931 * false for none, or true if such restrictions exist, but $getPages was not set.
1932 * The restriction array is an array of each type, each of which contains a
1933 * array of unique groups.
1935 public function getCascadeProtectionSources( $getPages = true ) {
1936 $pagerestrictions = array();
1938 if ( isset( $this->mCascadeSources
) && $getPages ) {
1939 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1940 } else if ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
1941 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1944 wfProfileIn( __METHOD__
);
1946 $dbr = wfGetDB( DB_SLAVE
);
1948 if ( $this->getNamespace() == NS_FILE
) {
1949 $tables = array ( 'imagelinks', 'page_restrictions' );
1950 $where_clauses = array(
1951 'il_to' => $this->getDBkey(),
1953 'pr_cascade' => 1 );
1955 $tables = array ( 'templatelinks', 'page_restrictions' );
1956 $where_clauses = array(
1957 'tl_namespace' => $this->getNamespace(),
1958 'tl_title' => $this->getDBkey(),
1960 'pr_cascade' => 1 );
1964 $cols = array( 'pr_page', 'page_namespace', 'page_title',
1965 'pr_expiry', 'pr_type', 'pr_level' );
1966 $where_clauses[] = 'page_id=pr_page';
1969 $cols = array( 'pr_expiry' );
1972 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1974 $sources = $getPages ?
array() : false;
1975 $now = wfTimestampNow();
1976 $purgeExpired = false;
1978 foreach ( $res as $row ) {
1979 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1980 if ( $expiry > $now ) {
1982 $page_id = $row->pr_page
;
1983 $page_ns = $row->page_namespace
;
1984 $page_title = $row->page_title
;
1985 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
1986 # Add groups needed for each restriction type if its not already there
1987 # Make sure this restriction type still exists
1989 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
1990 $pagerestrictions[$row->pr_type
] = array();
1993 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
1994 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
1995 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2001 // Trigger lazy purge of expired restrictions from the db
2002 $purgeExpired = true;
2005 if ( $purgeExpired ) {
2006 Title
::purgeExpiredRestrictions();
2009 wfProfileOut( __METHOD__
);
2012 $this->mCascadeSources
= $sources;
2013 $this->mCascadingRestrictions
= $pagerestrictions;
2015 $this->mHasCascadingRestrictions
= $sources;
2018 return array( $sources, $pagerestrictions );
2022 * Returns cascading restrictions for the current article
2026 function areRestrictionsCascading() {
2027 if ( !$this->mRestrictionsLoaded
) {
2028 $this->loadRestrictions();
2031 return $this->mCascadeRestriction
;
2035 * Loads a string into mRestrictions array
2037 * @param $res \type{Resource} restrictions as an SQL result.
2038 * @param $oldFashionedRestrictions string comma-separated list of page
2039 * restrictions from page table (pre 1.10)
2041 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2043 $dbr = wfGetDB( DB_SLAVE
);
2045 while ( $row = $dbr->fetchObject( $res ) ) {
2049 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2053 * Compiles list of active page restrictions from both page table (pre 1.10)
2054 * and page_restrictions table
2056 * @param $rows array of db result objects
2057 * @param $oldFashionedRestrictions string comma-separated list of page
2058 * restrictions from page table (pre 1.10)
2060 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2061 $dbr = wfGetDB( DB_SLAVE
);
2063 $restrictionTypes = $this->getRestrictionTypes();
2065 foreach ( $restrictionTypes as $type ) {
2066 $this->mRestrictions
[$type] = array();
2067 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry( '' );
2070 $this->mCascadeRestriction
= false;
2072 # Backwards-compatibility: also load the restrictions from the page record (old format).
2074 if ( $oldFashionedRestrictions === null ) {
2075 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2076 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2079 if ( $oldFashionedRestrictions != '' ) {
2081 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2082 $temp = explode( '=', trim( $restrict ) );
2083 if ( count( $temp ) == 1 ) {
2084 // old old format should be treated as edit/move restriction
2085 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2086 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2088 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2092 $this->mOldRestrictions
= true;
2096 if ( count( $rows ) ) {
2097 # Current system - load second to make them override.
2098 $now = wfTimestampNow();
2099 $purgeExpired = false;
2101 foreach ( $rows as $row ) {
2102 # Cycle through all the restrictions.
2104 // Don't take care of restrictions types that aren't allowed
2106 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2109 // This code should be refactored, now that it's being used more generally,
2110 // But I don't really see any harm in leaving it in Block for now -werdna
2111 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2113 // Only apply the restrictions if they haven't expired!
2114 if ( !$expiry ||
$expiry > $now ) {
2115 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2116 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2118 $this->mCascadeRestriction |
= $row->pr_cascade
;
2120 // Trigger a lazy purge of expired restrictions
2121 $purgeExpired = true;
2125 if ( $purgeExpired ) {
2126 Title
::purgeExpiredRestrictions();
2130 $this->mRestrictionsLoaded
= true;
2134 * Load restrictions from the page_restrictions table
2136 * @param $oldFashionedRestrictions string comma-separated list of page
2137 * restrictions from page table (pre 1.10)
2139 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2140 if ( !$this->mRestrictionsLoaded
) {
2141 if ( $this->exists() ) {
2142 $dbr = wfGetDB( DB_SLAVE
);
2144 $res = $dbr->select( 'page_restrictions', '*',
2145 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2147 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2149 $title_protection = $this->getTitleProtection();
2151 if ( $title_protection ) {
2152 $now = wfTimestampNow();
2153 $expiry = Block
::decodeExpiry( $title_protection['pt_expiry'] );
2155 if ( !$expiry ||
$expiry > $now ) {
2156 // Apply the restrictions
2157 $this->mRestrictionsExpiry
['create'] = $expiry;
2158 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2159 } else { // Get rid of the old restrictions
2160 Title
::purgeExpiredRestrictions();
2163 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry( '' );
2165 $this->mRestrictionsLoaded
= true;
2171 * Purge expired restrictions from the page_restrictions table
2173 static function purgeExpiredRestrictions() {
2174 $dbw = wfGetDB( DB_MASTER
);
2175 $dbw->delete( 'page_restrictions',
2176 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2179 $dbw->delete( 'protected_titles',
2180 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2185 * Accessor/initialisation for mRestrictions
2187 * @param $action \type{\string} action that permission needs to be checked for
2188 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2190 public function getRestrictions( $action ) {
2191 if ( !$this->mRestrictionsLoaded
) {
2192 $this->loadRestrictions();
2194 return isset( $this->mRestrictions
[$action] )
2195 ?
$this->mRestrictions
[$action]
2200 * Get the expiry time for the restriction against a given action
2202 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2203 * or not protected at all, or false if the action is not recognised.
2205 public function getRestrictionExpiry( $action ) {
2206 if ( !$this->mRestrictionsLoaded
) {
2207 $this->loadRestrictions();
2209 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2213 * Is there a version of this page in the deletion archive?
2215 * @return \type{\int} the number of archived revisions
2217 public function isDeleted() {
2218 if ( $this->getNamespace() < 0 ) {
2221 $dbr = wfGetDB( DB_SLAVE
);
2222 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2223 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2226 if ( $this->getNamespace() == NS_FILE
) {
2227 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2228 array( 'fa_name' => $this->getDBkey() ),
2237 * Is there a version of this page in the deletion archive?
2241 public function isDeletedQuick() {
2242 if ( $this->getNamespace() < 0 ) {
2245 $dbr = wfGetDB( DB_SLAVE
);
2246 $deleted = (bool)$dbr->selectField( 'archive', '1',
2247 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2250 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2251 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2252 array( 'fa_name' => $this->getDBkey() ),
2260 * Get the article ID for this Title from the link cache,
2261 * adding it if necessary
2263 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2265 * @return \type{\int} the ID
2267 public function getArticleID( $flags = 0 ) {
2268 if ( $this->getNamespace() < 0 ) {
2269 return $this->mArticleID
= 0;
2271 $linkCache = LinkCache
::singleton();
2272 if ( $flags & GAID_FOR_UPDATE
) {
2273 $oldUpdate = $linkCache->forUpdate( true );
2274 $linkCache->clearLink( $this );
2275 $this->mArticleID
= $linkCache->addLinkObj( $this );
2276 $linkCache->forUpdate( $oldUpdate );
2278 if ( -1 == $this->mArticleID
) {
2279 $this->mArticleID
= $linkCache->addLinkObj( $this );
2282 return $this->mArticleID
;
2286 * Is this an article that is a redirect page?
2287 * Uses link cache, adding it if necessary
2289 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2290 * @return \type{\bool}
2292 public function isRedirect( $flags = 0 ) {
2293 if ( !is_null( $this->mRedirect
) )
2294 return $this->mRedirect
;
2295 # Calling getArticleID() loads the field from cache as needed
2296 if ( !$this->getArticleID( $flags ) ) {
2297 return $this->mRedirect
= false;
2299 $linkCache = LinkCache
::singleton();
2300 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2302 return $this->mRedirect
;
2306 * What is the length of this page?
2307 * Uses link cache, adding it if necessary
2309 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2310 * @return \type{\bool}
2312 public function getLength( $flags = 0 ) {
2313 if ( $this->mLength
!= -1 )
2314 return $this->mLength
;
2315 # Calling getArticleID() loads the field from cache as needed
2316 if ( !$this->getArticleID( $flags ) ) {
2317 return $this->mLength
= 0;
2319 $linkCache = LinkCache
::singleton();
2320 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2322 return $this->mLength
;
2326 * What is the page_latest field for this page?
2328 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2329 * @return \type{\int} or 0 if the page doesn't exist
2331 public function getLatestRevID( $flags = 0 ) {
2332 if ( $this->mLatestID
!== false )
2333 return $this->mLatestID
;
2334 # Calling getArticleID() loads the field from cache as needed
2335 if ( !$this->getArticleID( $flags ) ) {
2336 return $this->mLatestID
= 0;
2338 $linkCache = LinkCache
::singleton();
2339 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2341 return $this->mLatestID
;
2345 * This clears some fields in this object, and clears any associated
2346 * keys in the "bad links" section of the link cache.
2348 * - This is called from Article::insertNewArticle() to allow
2349 * loading of the new page_id. It's also called from
2350 * Article::doDeleteArticle()
2352 * @param $newid \type{\int} the new Article ID
2354 public function resetArticleID( $newid ) {
2355 $linkCache = LinkCache
::singleton();
2356 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2358 if ( $newid === false ) {
2359 $this->mArticleID
= -1;
2361 $this->mArticleID
= intval( $newid );
2363 $this->mRestrictionsLoaded
= false;
2364 $this->mRestrictions
= array();
2365 $this->mRedirect
= null;
2366 $this->mLength
= -1;
2367 $this->mLatestID
= false;
2371 * Updates page_touched for this page; called from LinksUpdate.php
2373 * @return \type{\bool} true if the update succeded
2375 public function invalidateCache() {
2376 if ( wfReadOnly() ) {
2379 $dbw = wfGetDB( DB_MASTER
);
2380 $success = $dbw->update( 'page',
2381 array( 'page_touched' => $dbw->timestamp() ),
2385 HTMLFileCache
::clearFileCache( $this );
2390 * Prefix some arbitrary text with the namespace or interwiki prefix
2393 * @param $name \type{\string} the text
2394 * @return \type{\string} the prefixed text
2397 /* private */ function prefix( $name ) {
2399 if ( $this->mInterwiki
!= '' ) {
2400 $p = $this->mInterwiki
. ':';
2402 if ( 0 != $this->mNamespace
) {
2403 $p .= $this->getNsText() . ':';
2409 * Returns a simple regex that will match on characters and sequences invalid in titles.
2410 * Note that this doesn't pick up many things that could be wrong with titles, but that
2411 * replacing this regex with something valid will make many titles valid.
2413 * @return string regex string
2415 static function getTitleInvalidRegex() {
2416 static $rxTc = false;
2418 # Matching titles will be held as illegal.
2420 # Any character not allowed is forbidden...
2421 '[^' . Title
::legalChars() . ']' .
2422 # URL percent encoding sequences interfere with the ability
2423 # to round-trip titles -- you can't link to them consistently.
2424 '|%[0-9A-Fa-f]{2}' .
2425 # XML/HTML character references produce similar issues.
2426 '|&[A-Za-z0-9\x80-\xff]+;' .
2428 '|&#x[0-9A-Fa-f]+;' .
2436 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2438 * @param $text string containing title to capitalize
2439 * @param $ns int namespace index, defaults to NS_MAIN
2440 * @return String containing capitalized title
2442 public static function capitalize( $text, $ns = NS_MAIN
) {
2445 if ( MWNamespace
::isCapitalized( $ns ) )
2446 return $wgContLang->ucfirst( $text );
2452 * Secure and split - main initialisation function for this object
2454 * Assumes that mDbkeyform has been set, and is urldecoded
2455 * and uses underscores, but not otherwise munged. This function
2456 * removes illegal characters, splits off the interwiki and
2457 * namespace prefixes, sets the other forms, and canonicalizes
2460 * @return \type{\bool} true on success
2462 private function secureAndSplit() {
2463 global $wgContLang, $wgLocalInterwiki;
2466 $rxTc = self
::getTitleInvalidRegex();
2468 $this->mInterwiki
= $this->mFragment
= '';
2469 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2471 $dbkey = $this->mDbkeyform
;
2473 # Strip Unicode bidi override characters.
2474 # Sometimes they slip into cut-n-pasted page titles, where the
2475 # override chars get included in list displays.
2476 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2478 # Clean up whitespace
2479 # Note: use of the /u option on preg_replace here will cause
2480 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2481 # conveniently disabling them.
2483 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2484 $dbkey = trim( $dbkey, '_' );
2486 if ( $dbkey == '' ) {
2490 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2491 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2495 $this->mDbkeyform
= $dbkey;
2497 # Initial colon indicates main namespace rather than specified default
2498 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2499 if ( ':' == $dbkey { 0 } ) {
2500 $this->mNamespace
= NS_MAIN
;
2501 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2502 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2505 # Namespace or interwiki prefix
2507 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2510 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2512 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2513 # Ordinary namespace
2515 $this->mNamespace
= $ns;
2516 # For Talk:X pages, check if X has a "namespace" prefix
2517 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2518 if ( $wgContLang->getNsIndex( $x[1] ) )
2519 return false; # Disallow Talk:File:x type titles...
2520 else if ( Interwiki
::isValidInterwiki( $x[1] ) )
2521 return false; # Disallow Talk:Interwiki:x type titles...
2523 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2524 if ( !$firstPass ) {
2525 # Can't make a local interwiki link to an interwiki link.
2526 # That's just crazy!
2532 $this->mInterwiki
= $wgContLang->lc( $p );
2534 # Redundant interwiki prefix to the local wiki
2535 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2536 if ( $dbkey == '' ) {
2537 # Can't have an empty self-link
2540 $this->mInterwiki
= '';
2542 # Do another namespace split...
2546 # If there's an initial colon after the interwiki, that also
2547 # resets the default namespace
2548 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2549 $this->mNamespace
= NS_MAIN
;
2550 $dbkey = substr( $dbkey, 1 );
2553 # If there's no recognized interwiki or namespace,
2554 # then let the colon expression be part of the title.
2559 # We already know that some pages won't be in the database!
2561 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2562 $this->mArticleID
= 0;
2564 $fragment = strstr( $dbkey, '#' );
2565 if ( false !== $fragment ) {
2566 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2567 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2568 # remove whitespace again: prevents "Foo_bar_#"
2569 # becoming "Foo_bar_"
2570 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2573 # Reject illegal characters.
2575 if ( preg_match( $rxTc, $dbkey ) ) {
2580 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2581 * reachable due to the way web browsers deal with 'relative' URLs.
2582 * Also, they conflict with subpage syntax. Forbid them explicitly.
2584 if ( strpos( $dbkey, '.' ) !== false &&
2585 ( $dbkey === '.' ||
$dbkey === '..' ||
2586 strpos( $dbkey, './' ) === 0 ||
2587 strpos( $dbkey, '../' ) === 0 ||
2588 strpos( $dbkey, '/./' ) !== false ||
2589 strpos( $dbkey, '/../' ) !== false ||
2590 substr( $dbkey, -2 ) == '/.' ||
2591 substr( $dbkey, -3 ) == '/..' ) )
2597 * Magic tilde sequences? Nu-uh!
2599 if ( strpos( $dbkey, '~~~' ) !== false ) {
2604 * Limit the size of titles to 255 bytes.
2605 * This is typically the size of the underlying database field.
2606 * We make an exception for special pages, which don't need to be stored
2607 * in the database, and may edge over 255 bytes due to subpage syntax
2608 * for long titles, e.g. [[Special:Block/Long name]]
2610 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2611 strlen( $dbkey ) > 512 )
2617 * Normally, all wiki links are forced to have
2618 * an initial capital letter so [[foo]] and [[Foo]]
2619 * point to the same place.
2621 * Don't force it for interwikis, since the other
2622 * site might be case-sensitive.
2624 $this->mUserCaseDBKey
= $dbkey;
2625 if ( $this->mInterwiki
== '' ) {
2626 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2630 * Can't make a link to a namespace alone...
2631 * "empty" local links can only be self-links
2632 * with a fragment identifier.
2634 if ( $dbkey == '' &&
2635 $this->mInterwiki
== '' &&
2636 $this->mNamespace
!= NS_MAIN
) {
2639 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2640 // IP names are not allowed for accounts, and can only be referring to
2641 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2642 // there are numerous ways to present the same IP. Having sp:contribs scan
2643 // them all is silly and having some show the edits and others not is
2644 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2645 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2646 IP
::sanitizeIP( $dbkey ) : $dbkey;
2647 // Any remaining initial :s are illegal.
2648 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2653 $this->mDbkeyform
= $dbkey;
2654 $this->mUrlform
= wfUrlencode( $dbkey );
2656 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2662 * Set the fragment for this title. Removes the first character from the
2663 * specified fragment before setting, so it assumes you're passing it with
2666 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2667 * Still in active use privately.
2669 * @param $fragment \type{\string} text
2671 public function setFragment( $fragment ) {
2672 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2676 * Get a Title object associated with the talk page of this article
2678 * @return \type{Title} the object for the talk page
2680 public function getTalkPage() {
2681 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2685 * Get a title object associated with the subject page of this
2688 * @return \type{Title} the object for the subject page
2690 public function getSubjectPage() {
2691 // Is this the same title?
2692 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2693 if ( $this->getNamespace() == $subjectNS ) {
2696 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2700 * Get an array of Title objects linking to this Title
2701 * Also stores the IDs in the link cache.
2703 * WARNING: do not use this function on arbitrary user-supplied titles!
2704 * On heavily-used templates it will max out the memory.
2706 * @param $options Array: may be FOR UPDATE
2707 * @param $table String: table name
2708 * @param $prefix String: fields prefix
2709 * @return \type{\arrayof{Title}} the Title objects linking here
2711 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2712 $linkCache = LinkCache
::singleton();
2714 if ( count( $options ) > 0 ) {
2715 $db = wfGetDB( DB_MASTER
);
2717 $db = wfGetDB( DB_SLAVE
);
2720 $res = $db->select( array( 'page', $table ),
2721 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2723 "{$prefix}_from=page_id",
2724 "{$prefix}_namespace" => $this->getNamespace(),
2725 "{$prefix}_title" => $this->getDBkey() ),
2730 if ( $db->numRows( $res ) ) {
2731 foreach ( $res as $row ) {
2732 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2733 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
2734 $retVal[] = $titleObj;
2738 $db->freeResult( $res );
2743 * Get an array of Title objects using this Title as a template
2744 * Also stores the IDs in the link cache.
2746 * WARNING: do not use this function on arbitrary user-supplied titles!
2747 * On heavily-used templates it will max out the memory.
2749 * @param $options Array: may be FOR UPDATE
2750 * @return \type{\arrayof{Title}} the Title objects linking here
2752 public function getTemplateLinksTo( $options = array() ) {
2753 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2757 * Get an array of Title objects referring to non-existent articles linked from this page
2759 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2760 * @return \type{\arrayof{Title}} the Title objects
2762 public function getBrokenLinksFrom() {
2763 if ( $this->getArticleId() == 0 ) {
2764 # All links from article ID 0 are false positives
2768 $dbr = wfGetDB( DB_SLAVE
);
2769 $res = $dbr->select(
2770 array( 'page', 'pagelinks' ),
2771 array( 'pl_namespace', 'pl_title' ),
2773 'pl_from' => $this->getArticleId(),
2774 'page_namespace IS NULL'
2776 __METHOD__
, array(),
2780 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2786 foreach ( $res as $row ) {
2787 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2794 * Get a list of URLs to purge from the Squid cache when this
2797 * @return \type{\arrayof{\string}} the URLs
2799 public function getSquidURLs() {
2803 $this->getInternalURL(),
2804 $this->getInternalURL( 'action=history' )
2807 // purge variant urls as well
2808 if ( $wgContLang->hasVariants() ) {
2809 $variants = $wgContLang->getVariants();
2810 foreach ( $variants as $vCode ) {
2811 if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
2812 $urls[] = $this->getInternalURL( '', $vCode );
2820 * Purge all applicable Squid URLs
2822 public function purgeSquid() {
2824 if ( $wgUseSquid ) {
2825 $urls = $this->getSquidURLs();
2826 $u = new SquidUpdate( $urls );
2832 * Move this page without authentication
2834 * @param $nt \type{Title} the new page Title
2835 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2837 public function moveNoAuth( &$nt ) {
2838 return $this->moveTo( $nt, false );
2842 * Check whether a given move operation would be valid.
2843 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2845 * @param $nt \type{Title} the new title
2846 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2848 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2849 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2851 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2856 // Normally we'd add this to $errors, but we'll get
2857 // lots of syntax errors if $nt is not an object
2858 return array( array( 'badtitletext' ) );
2860 if ( $this->equals( $nt ) ) {
2861 $errors[] = array( 'selfmove' );
2863 if ( !$this->isMovable() ) {
2864 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2866 if ( $nt->getInterwiki() != '' ) {
2867 $errors[] = array( 'immobile-target-namespace-iw' );
2869 if ( !$nt->isMovable() ) {
2870 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2873 $oldid = $this->getArticleID();
2874 $newid = $nt->getArticleID();
2876 if ( strlen( $nt->getDBkey() ) < 1 ) {
2877 $errors[] = array( 'articleexists' );
2879 if ( ( $this->getDBkey() == '' ) ||
2881 ( $nt->getDBkey() == '' ) ) {
2882 $errors[] = array( 'badarticleerror' );
2885 // Image-specific checks
2886 if ( $this->getNamespace() == NS_FILE
) {
2887 $file = wfLocalFile( $this );
2888 if ( $file->exists() ) {
2889 if ( $nt->getNamespace() != NS_FILE
) {
2890 $errors[] = array( 'imagenocrossnamespace' );
2892 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2893 $errors[] = array( 'imageinvalidfilename' );
2895 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2896 $errors[] = array( 'imagetypemismatch' );
2899 $destfile = wfLocalFile( $nt );
2900 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2901 $errors[] = array( 'file-exists-sharedrepo' );
2907 $errors = wfMergeErrorArrays( $errors,
2908 $this->getUserPermissionsErrors( 'move', $wgUser ),
2909 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2910 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2911 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2914 $match = EditPage
::matchSummarySpamRegex( $reason );
2915 if ( $match !== false ) {
2916 // This is kind of lame, won't display nice
2917 $errors[] = array( 'spamprotectiontext' );
2921 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2922 $errors[] = array( 'hookaborted', $err );
2925 # The move is allowed only if (1) the target doesn't exist, or
2926 # (2) the target is a redirect to the source, and has no history
2927 # (so we can undo bad moves right after they're done).
2929 if ( 0 != $newid ) { # Target exists; check for validity
2930 if ( ! $this->isValidMoveTarget( $nt ) ) {
2931 $errors[] = array( 'articleexists' );
2934 $tp = $nt->getTitleProtection();
2935 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2936 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2937 $errors[] = array( 'cantmove-titleprotected' );
2940 if ( empty( $errors ) )
2946 * Move a title to a new location
2948 * @param $nt \type{Title} the new title
2949 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2951 * @param $reason \type{\string} The reason for the move
2952 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2953 * Ignored if the user doesn't have the suppressredirect right.
2954 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2956 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2957 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2958 if ( is_array( $err ) ) {
2962 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
2963 $dbw = wfGetDB( DB_MASTER
);
2964 if ( $this->getNamespace() == NS_FILE
) {
2965 $file = wfLocalFile( $this );
2966 if ( $file->exists() ) {
2967 $status = $file->move( $nt );
2968 if ( !$status->isOk() ) {
2969 return $status->getErrorsArray();
2974 $pageid = $this->getArticleID();
2975 $protected = $this->isProtected();
2976 if ( $nt->exists() ) {
2977 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2978 $pageCountChange = ( $createRedirect ?
0 : -1 );
2979 } else { # Target didn't exist, do normal move.
2980 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2981 $pageCountChange = ( $createRedirect ?
1 : 0 );
2984 if ( is_array( $err ) ) {
2987 $redirid = $this->getArticleID();
2989 // Category memberships include a sort key which may be customized.
2990 // If it's left as the default (the page title), we need to update
2991 // the sort key to match the new title.
2993 // Be careful to avoid resetting cl_timestamp, which may disturb
2994 // time-based lists on some sites.
2996 // Warning -- if the sort key is *explicitly* set to the old title,
2997 // we can't actually distinguish it from a default here, and it'll
2998 // be set to the new title even though it really shouldn't.
2999 // It'll get corrected on the next edit, but resetting cl_timestamp.
3000 $dbw->update( 'categorylinks',
3002 'cl_sortkey' => $nt->getPrefixedText(),
3003 'cl_timestamp=cl_timestamp' ),
3005 'cl_from' => $pageid,
3006 'cl_sortkey' => $this->getPrefixedText() ),
3010 # Protect the redirect title as the title used to be...
3011 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3013 'pr_page' => $redirid,
3014 'pr_type' => 'pr_type',
3015 'pr_level' => 'pr_level',
3016 'pr_cascade' => 'pr_cascade',
3017 'pr_user' => 'pr_user',
3018 'pr_expiry' => 'pr_expiry'
3020 array( 'pr_page' => $pageid ),
3024 # Update the protection log
3025 $log = new LogPage( 'protect' );
3026 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3027 if ( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3028 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3032 $oldnamespace = $this->getNamespace() & ~
1;
3033 $newnamespace = $nt->getNamespace() & ~
1;
3034 $oldtitle = $this->getDBkey();
3035 $newtitle = $nt->getDBkey();
3037 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3038 WatchedItem
::duplicateEntries( $this, $nt );
3041 # Update search engine
3042 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3044 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3048 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3049 # No longer a content page
3050 # Not viewed, edited, removing
3051 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3052 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3053 # Now a content page
3054 # Not viewed, edited, adding
3055 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3056 } elseif ( $pageCountChange ) {
3058 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3065 # Update message cache for interface messages
3066 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3067 global $wgMessageCache;
3069 # @bug 17860: old article can be deleted, if this the case,
3070 # delete it from message cache
3071 if ( $this->getArticleID() === 0 ) {
3072 $wgMessageCache->replace( $this->getDBkey(), false );
3074 $oldarticle = new Article( $this );
3075 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3078 $newarticle = new Article( $nt );
3079 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3083 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3088 * Move page to a title which is at present a redirect to the
3091 * @param $nt \type{Title} the page to move to, which should currently
3093 * @param $reason \type{\string} The reason for the move
3094 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3095 * Ignored if the user doesn't have the suppressredirect right
3097 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3098 global $wgUseSquid, $wgUser, $wgContLang;
3100 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3103 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3105 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3106 $comment = $wgContLang->truncate( $comment, 250 );
3108 $now = wfTimestampNow();
3109 $newid = $nt->getArticleID();
3110 $oldid = $this->getArticleID();
3111 $latest = $this->getLatestRevID();
3113 $dbw = wfGetDB( DB_MASTER
);
3115 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3116 $newns = $nt->getNamespace();
3117 $newdbk = $nt->getDBkey();
3119 # Delete the old redirect. We don't save it to history since
3120 # by definition if we've got here it's rather uninteresting.
3121 # We have to remove it so that the next step doesn't trigger
3122 # a conflict on the unique namespace+title index...
3123 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3124 if ( !$dbw->cascadingDeletes() ) {
3125 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3126 global $wgUseTrackbacks;
3127 if ( $wgUseTrackbacks )
3128 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3129 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3130 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3131 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3132 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3133 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3134 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3135 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3137 // If the redirect was recently created, it may have an entry in recentchanges still
3138 $dbw->delete( 'recentchanges',
3139 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3143 # Save a null revision in the page's history notifying of the move
3144 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3145 $nullRevId = $nullRevision->insertOn( $dbw );
3147 $article = new Article( $this );
3148 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3150 # Change the name of the target page:
3151 $dbw->update( 'page',
3153 'page_touched' => $dbw->timestamp( $now ),
3154 'page_namespace' => $nt->getNamespace(),
3155 'page_title' => $nt->getDBkey(),
3156 'page_latest' => $nullRevId,
3158 /* WHERE */ array( 'page_id' => $oldid ),
3161 $nt->resetArticleID( $oldid );
3163 # Recreate the redirect, this time in the other direction.
3164 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3165 $mwRedir = MagicWord
::get( 'redirect' );
3166 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3167 $redirectArticle = new Article( $this );
3168 $newid = $redirectArticle->insertOn( $dbw );
3169 $redirectRevision = new Revision( array(
3171 'comment' => $comment,
3172 'text' => $redirectText ) );
3173 $redirectRevision->insertOn( $dbw );
3174 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3176 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3178 # Now, we record the link from the redirect to the new title.
3179 # It should have no other outgoing links...
3180 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3181 $dbw->insert( 'pagelinks',
3183 'pl_from' => $newid,
3184 'pl_namespace' => $nt->getNamespace(),
3185 'pl_title' => $nt->getDBkey() ),
3187 $redirectSuppressed = false;
3189 $this->resetArticleID( 0 );
3190 $redirectSuppressed = true;
3194 $log = new LogPage( 'move' );
3195 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3198 if ( $wgUseSquid ) {
3199 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3200 $u = new SquidUpdate( $urls );
3207 * Move page to non-existing title.
3209 * @param $nt \type{Title} the new Title
3210 * @param $reason \type{\string} The reason for the move
3211 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3212 * Ignored if the user doesn't have the suppressredirect right
3214 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3215 global $wgUseSquid, $wgUser, $wgContLang;
3217 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3219 $comment .= wfMsgExt( 'colon-separator',
3220 array( 'escapenoentities', 'content' ) );
3221 $comment .= $reason;
3223 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3224 $comment = $wgContLang->truncate( $comment, 250 );
3226 $newid = $nt->getArticleID();
3227 $oldid = $this->getArticleID();
3228 $latest = $this->getLatestRevId();
3230 $dbw = wfGetDB( DB_MASTER
);
3231 $now = $dbw->timestamp();
3233 # Save a null revision in the page's history notifying of the move
3234 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3235 if ( !is_object( $nullRevision ) ) {
3236 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3238 $nullRevId = $nullRevision->insertOn( $dbw );
3240 $article = new Article( $this );
3241 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3244 $dbw->update( 'page',
3246 'page_touched' => $now,
3247 'page_namespace' => $nt->getNamespace(),
3248 'page_title' => $nt->getDBkey(),
3249 'page_latest' => $nullRevId,
3251 /* WHERE */ array( 'page_id' => $oldid ),
3254 $nt->resetArticleID( $oldid );
3256 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3258 $mwRedir = MagicWord
::get( 'redirect' );
3259 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3260 $redirectArticle = new Article( $this );
3261 $newid = $redirectArticle->insertOn( $dbw );
3262 $redirectRevision = new Revision( array(
3264 'comment' => $comment,
3265 'text' => $redirectText ) );
3266 $redirectRevision->insertOn( $dbw );
3267 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3269 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3271 # Record the just-created redirect's linking to the page
3272 $dbw->insert( 'pagelinks',
3274 'pl_from' => $newid,
3275 'pl_namespace' => $nt->getNamespace(),
3276 'pl_title' => $nt->getDBkey() ),
3278 $redirectSuppressed = false;
3280 $this->resetArticleID( 0 );
3281 $redirectSuppressed = true;
3285 $log = new LogPage( 'move' );
3286 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3288 # Purge caches as per article creation
3289 Article
::onArticleCreate( $nt );
3291 # Purge old title from squid
3292 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3293 $this->purgeSquid();
3298 * Move this page's subpages to be subpages of $nt
3300 * @param $nt Title Move target
3301 * @param $auth bool Whether $wgUser's permissions should be checked
3302 * @param $reason string The reason for the move
3303 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3304 * Ignored if the user doesn't have the 'suppressredirect' right
3305 * @return mixed array with old page titles as keys, and strings (new page titles) or
3306 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3308 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3309 global $wgMaximumMovedPages;
3310 // Check permissions
3311 if ( !$this->userCan( 'move-subpages' ) )
3312 return array( 'cant-move-subpages' );
3313 // Do the source and target namespaces support subpages?
3314 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3315 return array( 'namespace-nosubpages',
3316 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3317 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3318 return array( 'namespace-nosubpages',
3319 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3321 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3324 foreach ( $subpages as $oldSubpage ) {
3326 if ( $count > $wgMaximumMovedPages ) {
3327 $retval[$oldSubpage->getPrefixedTitle()] =
3328 array( 'movepage-max-pages',
3329 $wgMaximumMovedPages );
3333 // We don't know whether this function was called before
3334 // or after moving the root page, so check both
3336 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3337 $oldSubpage->getArticleID() == $nt->getArticleId() )
3338 // When moving a page to a subpage of itself,
3339 // don't move it twice
3341 $newPageName = preg_replace(
3342 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3343 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3344 $oldSubpage->getDBkey() );
3345 if ( $oldSubpage->isTalkPage() ) {
3346 $newNs = $nt->getTalkPage()->getNamespace();
3348 $newNs = $nt->getSubjectPage()->getNamespace();
3350 # Bug 14385: we need makeTitleSafe because the new page names may
3351 # be longer than 255 characters.
3352 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3354 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3355 if ( $success === true ) {
3356 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3358 $retval[$oldSubpage->getPrefixedText()] = $success;
3365 * Checks if this page is just a one-rev redirect.
3366 * Adds lock, so don't use just for light purposes.
3368 * @return \type{\bool}
3370 public function isSingleRevRedirect() {
3371 $dbw = wfGetDB( DB_MASTER
);
3373 $row = $dbw->selectRow( 'page',
3374 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3377 array( 'FOR UPDATE' )
3379 # Cache some fields we may want
3380 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3381 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3382 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3383 if ( !$this->mRedirect
) {
3386 # Does the article have a history?
3387 $row = $dbw->selectField( array( 'page', 'revision' ),
3389 array( 'page_namespace' => $this->getNamespace(),
3390 'page_title' => $this->getDBkey(),
3392 'page_latest != rev_id'
3395 array( 'FOR UPDATE' )
3397 # Return true if there was no history
3398 return ( $row === false );
3402 * Checks if $this can be moved to a given Title
3403 * - Selects for update, so don't call it unless you mean business
3405 * @param $nt \type{Title} the new title to check
3406 * @return \type{\bool} TRUE or FALSE
3408 public function isValidMoveTarget( $nt ) {
3409 $dbw = wfGetDB( DB_MASTER
);
3410 # Is it an existsing file?
3411 if ( $nt->getNamespace() == NS_FILE
) {
3412 $file = wfLocalFile( $nt );
3413 if ( $file->exists() ) {
3414 wfDebug( __METHOD__
. ": file exists\n" );
3418 # Is it a redirect with no history?
3419 if ( !$nt->isSingleRevRedirect() ) {
3420 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3423 # Get the article text
3424 $rev = Revision
::newFromTitle( $nt );
3425 $text = $rev->getText();
3426 # Does the redirect point to the source?
3427 # Or is it a broken self-redirect, usually caused by namespace collisions?
3429 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3430 $redirTitle = Title
::newFromText( $m[1] );
3431 if ( !is_object( $redirTitle ) ||
3432 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3433 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3434 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3439 wfDebug( __METHOD__
. ": failsafe\n" );
3446 * Can this title be added to a user's watchlist?
3448 * @return \type{\bool} TRUE or FALSE
3450 public function isWatchable() {
3451 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3455 * Get categories to which this Title belongs and return an array of
3456 * categories' names.
3458 * @return \type{\array} array an array of parents in the form:
3459 * $parent => $currentarticle
3461 public function getParentCategories() {
3464 $titlekey = $this->getArticleId();
3465 $dbr = wfGetDB( DB_SLAVE
);
3466 $categorylinks = $dbr->tableName( 'categorylinks' );
3469 $sql = "SELECT * FROM $categorylinks"
3470 . " WHERE cl_from='$titlekey'"
3471 . " AND cl_from <> '0'"
3472 . " ORDER BY cl_sortkey";
3474 $res = $dbr->query( $sql );
3476 if ( $dbr->numRows( $res ) > 0 ) {
3477 foreach ( $res as $row )
3478 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3479 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3480 $dbr->freeResult( $res );
3488 * Get a tree of parent categories
3490 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3491 * @return \type{\array} Tree of parent categories
3493 public function getParentCategoryTree( $children = array() ) {
3495 $parents = $this->getParentCategories();
3498 foreach ( $parents as $parent => $current ) {
3499 if ( array_key_exists( $parent, $children ) ) {
3500 # Circular reference
3501 $stack[$parent] = array();
3503 $nt = Title
::newFromText( $parent );
3505 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3517 * Get an associative array for selecting this title from
3520 * @return \type{\array} Selection array
3522 public function pageCond() {
3523 if ( $this->mArticleID
> 0 ) {
3524 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3525 return array( 'page_id' => $this->mArticleID
);
3527 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3532 * Get the revision ID of the previous revision
3534 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3535 * @param $flags \type{\int} GAID_FOR_UPDATE
3536 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3538 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3539 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3540 return $db->selectField( 'revision', 'rev_id',
3542 'rev_page' => $this->getArticleId( $flags ),
3543 'rev_id < ' . intval( $revId )
3546 array( 'ORDER BY' => 'rev_id DESC' )
3551 * Get the revision ID of the next revision
3553 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3554 * @param $flags \type{\int} GAID_FOR_UPDATE
3555 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3557 public function getNextRevisionID( $revId, $flags = 0 ) {
3558 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3559 return $db->selectField( 'revision', 'rev_id',
3561 'rev_page' => $this->getArticleId( $flags ),
3562 'rev_id > ' . intval( $revId )
3565 array( 'ORDER BY' => 'rev_id' )
3570 * Get the first revision of the page
3572 * @param $flags \type{\int} GAID_FOR_UPDATE
3573 * @return Revision (or NULL if page doesn't exist)
3575 public function getFirstRevision( $flags = 0 ) {
3576 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3577 $pageId = $this->getArticleId( $flags );
3578 if ( !$pageId ) return null;
3579 $row = $db->selectRow( 'revision', '*',
3580 array( 'rev_page' => $pageId ),
3582 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3587 return new Revision( $row );
3592 * Check if this is a new page
3596 public function isNewPage() {
3597 $dbr = wfGetDB( DB_SLAVE
);
3598 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3602 * Get the oldest revision timestamp of this page
3604 * @return String: MW timestamp
3606 public function getEarliestRevTime() {
3607 $dbr = wfGetDB( DB_SLAVE
);
3608 if ( $this->exists() ) {
3609 $min = $dbr->selectField( 'revision',
3610 'MIN(rev_timestamp)',
3611 array( 'rev_page' => $this->getArticleId() ),
3613 return wfTimestampOrNull( TS_MW
, $min );
3619 * Get the number of revisions between the given revision IDs.
3620 * Used for diffs and other things that really need it.
3622 * @param $old \type{\int} Revision ID.
3623 * @param $new \type{\int} Revision ID.
3624 * @return \type{\int} Number of revisions between these IDs.
3626 public function countRevisionsBetween( $old, $new ) {
3627 $dbr = wfGetDB( DB_SLAVE
);
3628 return (int)$dbr->selectField( 'revision', 'count(*)',
3629 'rev_page = ' . intval( $this->getArticleId() ) .
3630 ' AND rev_id > ' . intval( $old ) .
3631 ' AND rev_id < ' . intval( $new ),
3637 * Compare with another title.
3639 * @param $title \type{Title}
3640 * @return \type{\bool} TRUE or FALSE
3642 public function equals( Title
$title ) {
3643 // Note: === is necessary for proper matching of number-like titles.
3644 return $this->getInterwiki() === $title->getInterwiki()
3645 && $this->getNamespace() == $title->getNamespace()
3646 && $this->getDBkey() === $title->getDBkey();
3650 * Callback for usort() to do title sorts by (namespace, title)
3652 * @return Integer: result of string comparison, or namespace comparison
3654 public static function compare( $a, $b ) {
3655 if ( $a->getNamespace() == $b->getNamespace() ) {
3656 return strcmp( $a->getText(), $b->getText() );
3658 return $a->getNamespace() - $b->getNamespace();
3663 * Return a string representation of this title
3665 * @return \type{\string} String representation of this title
3667 public function __toString() {
3668 return $this->getPrefixedText();
3672 * Check if page exists. For historical reasons, this function simply
3673 * checks for the existence of the title in the page table, and will
3674 * thus return false for interwiki links, special pages and the like.
3675 * If you want to know if a title can be meaningfully viewed, you should
3676 * probably call the isKnown() method instead.
3678 * @return \type{\bool}
3680 public function exists() {
3681 return $this->getArticleId() != 0;
3685 * Should links to this title be shown as potentially viewable (i.e. as
3686 * "bluelinks"), even if there's no record by this title in the page
3689 * This function is semi-deprecated for public use, as well as somewhat
3690 * misleadingly named. You probably just want to call isKnown(), which
3691 * calls this function internally.
3693 * (ISSUE: Most of these checks are cheap, but the file existence check
3694 * can potentially be quite expensive. Including it here fixes a lot of
3695 * existing code, but we might want to add an optional parameter to skip
3696 * it and any other expensive checks.)
3698 * @return \type{\bool}
3700 public function isAlwaysKnown() {
3701 if ( $this->mInterwiki
!= '' ) {
3702 return true; // any interwiki link might be viewable, for all we know
3704 switch( $this->mNamespace
) {
3707 return (bool)wfFindFile( $this ); // file exists, possibly in a foreign repo
3709 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3711 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3713 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3714 // the full l10n of that language to be loaded. That takes much memory and
3715 // isn't needed. So we strip the language part away.
3716 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3717 return (bool)wfMsgWeirdKey( $basename ); // known system message
3724 * Does this title refer to a page that can (or might) be meaningfully
3725 * viewed? In particular, this function may be used to determine if
3726 * links to the title should be rendered as "bluelinks" (as opposed to
3727 * "redlinks" to non-existent pages).
3729 * @return \type{\bool}
3731 public function isKnown() {
3732 return $this->exists() ||
$this->isAlwaysKnown();
3736 * Does this page have source text?
3740 public function hasSourceText() {
3741 if ( $this->exists() )
3744 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3745 // If the page doesn't exist but is a known system message, default
3746 // message content will be displayed, same for language subpages
3747 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3748 // causes the full l10n of that language to be loaded. That takes much
3749 // memory and isn't needed. So we strip the language part away.
3750 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3751 return (bool)wfMsgWeirdKey( $basename );
3758 * Is this in a namespace that allows actual pages?
3760 * @return \type{\bool}
3761 * @internal note -- uses hardcoded namespace index instead of constants
3763 public function canExist() {
3764 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3768 * Update page_touched timestamps and send squid purge messages for
3769 * pages linking to this title. May be sent to the job queue depending
3770 * on the number of links. Typically called on create and delete.
3772 public function touchLinks() {
3773 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3776 if ( $this->getNamespace() == NS_CATEGORY
) {
3777 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3783 * Get the last touched timestamp
3785 * @param $db DatabaseBase: optional db
3786 * @return \type{\string} Last touched timestamp
3788 public function getTouched( $db = null ) {
3789 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
3790 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3795 * Get the timestamp when this page was updated since the user last saw it.
3798 * @return Mixed: string/null
3800 public function getNotificationTimestamp( $user = null ) {
3801 global $wgUser, $wgShowUpdatedMarker;
3802 // Assume current user if none given
3803 if ( !$user ) $user = $wgUser;
3804 // Check cache first
3805 $uid = $user->getId();
3806 if ( isset( $this->mNotificationTimestamp
[$uid] ) ) {
3807 return $this->mNotificationTimestamp
[$uid];
3809 if ( !$uid ||
!$wgShowUpdatedMarker ) {
3810 return $this->mNotificationTimestamp
[$uid] = false;
3812 // Don't cache too much!
3813 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3814 $this->mNotificationTimestamp
= array();
3816 $dbr = wfGetDB( DB_SLAVE
);
3817 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3818 'wl_notificationtimestamp',
3819 array( 'wl_namespace' => $this->getNamespace(),
3820 'wl_title' => $this->getDBkey(),
3821 'wl_user' => $user->getId()
3825 return $this->mNotificationTimestamp
[$uid];
3829 * Get the trackback URL for this page
3831 * @return \type{\string} Trackback URL
3833 public function trackbackURL() {
3834 global $wgScriptPath, $wgServer, $wgScriptExtension;
3836 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3837 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3841 * Get the trackback RDF for this page
3843 * @return \type{\string} Trackback RDF
3845 public function trackbackRDF() {
3846 $url = htmlspecialchars( $this->getFullURL() );
3847 $title = htmlspecialchars( $this->getText() );
3848 $tburl = $this->trackbackURL();
3850 // Autodiscovery RDF is placed in comments so HTML validator
3851 // won't barf. This is a rather icky workaround, but seems
3852 // frequently used by this kind of RDF thingy.
3854 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3856 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3857 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3858 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3861 dc:identifier=\"$url\"
3863 trackback:ping=\"$tburl\" />
3869 * Generate strings used for xml 'id' names in monobook tabs
3871 * @param $prepend string defaults to 'nstab-'
3872 * @return \type{\string} XML 'id' name
3874 public function getNamespaceKey( $prepend = 'nstab-' ) {
3876 // Gets the subject namespace if this title
3877 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3878 // Checks if cononical namespace name exists for namespace
3879 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3880 // Uses canonical namespace name
3881 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3883 // Uses text of namespace
3884 $namespaceKey = $this->getSubjectNsText();
3886 // Makes namespace key lowercase
3887 $namespaceKey = $wgContLang->lc( $namespaceKey );
3889 if ( $namespaceKey == '' ) {
3890 $namespaceKey = 'main';
3892 // Changes file to image for backwards compatibility
3893 if ( $namespaceKey == 'file' ) {
3894 $namespaceKey = 'image';
3896 return $prepend . $namespaceKey;
3900 * Returns true if this is a special page.
3904 public function isSpecialPage( ) {
3905 return $this->getNamespace() == NS_SPECIAL
;
3909 * Returns true if this title resolves to the named special page
3911 * @param $name \type{\string} The special page name
3914 public function isSpecial( $name ) {
3915 if ( $this->getNamespace() == NS_SPECIAL
) {
3916 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3917 if ( $name == $thisName ) {
3925 * If the Title refers to a special page alias which is not the local default,
3927 * @return \type{Title} A new Title which points to the local default.
3928 * Otherwise, returns $this.
3930 public function fixSpecialName() {
3931 if ( $this->getNamespace() == NS_SPECIAL
) {
3932 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3933 if ( $canonicalName ) {
3934 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3935 if ( $localName != $this->mDbkeyform
) {
3936 return Title
::makeTitle( NS_SPECIAL
, $localName );
3944 * Is this Title in a namespace which contains content?
3945 * In other words, is this a content page, for the purposes of calculating
3948 * @return \type{\bool}
3950 public function isContentPage() {
3951 return MWNamespace
::isContent( $this->getNamespace() );
3955 * Get all extant redirects to this Title
3957 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3958 * NULL to consider all namespaces
3959 * @return \type{\arrayof{Title}} Redirects to this title
3961 public function getRedirectsHere( $ns = null ) {
3964 $dbr = wfGetDB( DB_SLAVE
);
3966 'rd_namespace' => $this->getNamespace(),
3967 'rd_title' => $this->getDBkey(),
3970 if ( !is_null( $ns ) ) $where['page_namespace'] = $ns;
3972 $res = $dbr->select(
3973 array( 'redirect', 'page' ),
3974 array( 'page_namespace', 'page_title' ),
3980 foreach ( $res as $row ) {
3981 $redirs[] = self
::newFromRow( $row );
3987 * Check if this Title is a valid redirect target
3989 * @return \type{\bool}
3991 public function isValidRedirectTarget() {
3992 global $wgInvalidRedirectTargets;
3994 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3995 if ( $this->isSpecial( 'Userlogout' ) ) {
3999 foreach ( $wgInvalidRedirectTargets as $target ) {
4000 if ( $this->isSpecial( $target ) ) {
4009 * Get a backlink cache object
4011 * @return object BacklinkCache
4013 function getBacklinkCache() {
4014 if ( is_null( $this->mBacklinkCache
) ) {
4015 $this->mBacklinkCache
= new BacklinkCache( $this );
4017 return $this->mBacklinkCache
;
4021 * Whether the magic words __INDEX__ and __NOINDEX__ function for
4026 public function canUseNoindex() {
4027 global $wgArticleRobotPolicies, $wgContentNamespaces,
4028 $wgExemptFromUserRobotsControl;
4030 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4031 ?
$wgContentNamespaces
4032 : $wgExemptFromUserRobotsControl;
4034 return !in_array( $this->mNamespace
, $bannedNamespaces );
4039 * Returns restriction types for the current Title
4041 * @return array applicable restriction types
4043 public function getRestrictionTypes() {
4044 global $wgRestrictionTypes;
4045 $types = $this->exists() ?
$wgRestrictionTypes : array( 'create' );
4047 if ( $this->getNamespace() == NS_FILE
) {
4048 $types[] = 'upload';
4051 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );