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();
33 * Title::newFromText maintains a cache to avoid expensive re-normalization of
34 * commonly used titles. On a batch operation this can become a memory leak
35 * if not bounded. After hitting this many titles reset the cache.
37 const CACHE_MAX
= 1000;
41 * @name Private member variables
42 * Please use the accessor functions instead.
47 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
48 var $mUrlform = ''; // /< URL-encoded form of the main part
49 var $mDbkeyform = ''; // /< Main part with underscores
50 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
51 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
53 var $mFragment; // /< Title fragment (i.e. the bit after the #)
54 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
55 var $mLatestID = false; // /< ID of most recent revision
56 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
59 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
60 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
61 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
62 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
63 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
64 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
65 var $mTitleProtection; ///< Cached value of getTitleProtection
66 # Don't change the following default, NS_MAIN is hardcoded in several
67 # places. See bug 696.
68 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
69 # Zero except in {{transclusion}} tags
70 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
71 var $mLength = -1; // /< The page length, 0 for special pages
72 var $mRedirect = null; // /< Is the article at this title a redirect?
73 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
74 var $mBacklinkCache = null; // /< Cache of links to this title
82 /* private */ function __construct() { }
85 * Create a new Title from a prefixed DB key
87 * @param $key \type{\string} The database key, which has underscores
88 * instead of spaces, possibly including namespace and
90 * @return \type{Title} the new object, or NULL on an error
92 public static function newFromDBkey( $key ) {
94 $t->mDbkeyform
= $key;
95 if ( $t->secureAndSplit() ) {
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
);
225 'page_namespace', 'page_title', 'page_id',
226 'page_len', 'page_is_redirect', 'page_latest',
228 array( 'page_id' => $ids ),
233 foreach ( $res as $row ) {
234 $titles[] = Title
::newFromRow( $row );
240 * Make a Title object from a DB row
242 * @param $row \type{Row} (needs at least page_title,page_namespace)
243 * @return \type{Title} corresponding Title
245 public static function newFromRow( $row ) {
246 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
248 $t->mArticleID
= isset( $row->page_id
) ?
intval( $row->page_id
) : -1;
249 $t->mLength
= isset( $row->page_len
) ?
intval( $row->page_len
) : -1;
250 $t->mRedirect
= isset( $row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
251 $t->mLatestID
= isset( $row->page_latest
) ?
intval( $row->page_latest
) : false;
257 * Create a new Title from a namespace index and a DB key.
258 * It's assumed that $ns and $title are *valid*, for instance when
259 * they came directly from the database or a special page name.
260 * For convenience, spaces are converted to underscores so that
261 * eg user_text fields can be used directly.
263 * @param $ns \type{\int} the namespace of the article
264 * @param $title \type{\string} the unprefixed database key form
265 * @param $fragment \type{\string} The link fragment (after the "#")
266 * @param $interwiki \type{\string} The interwiki prefix
267 * @return \type{Title} the new object
269 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
271 $t->mInterwiki
= $interwiki;
272 $t->mFragment
= $fragment;
273 $t->mNamespace
= $ns = intval( $ns );
274 $t->mDbkeyform
= str_replace( ' ', '_', $title );
275 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
276 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
277 $t->mTextform
= str_replace( '_', ' ', $title );
282 * Create a new Title from a namespace index and a DB key.
283 * The parameters will be checked for validity, which is a bit slower
284 * than makeTitle() but safer for user-provided data.
286 * @param $ns \type{\int} the namespace of the article
287 * @param $title \type{\string} the database key form
288 * @param $fragment \type{\string} The link fragment (after the "#")
289 * @param $interwiki \type{\string} The interwiki prefix
290 * @return \type{Title} the new object, or NULL on an error
292 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
294 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
295 if ( $t->secureAndSplit() ) {
303 * Create a new Title for the Main Page
305 * @return \type{Title} the new object
307 public static function newMainPage() {
308 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
309 // Don't give fatal errors if the message is broken
311 $title = Title
::newFromText( 'Main Page' );
317 * Extract a redirect destination from a string and return the
318 * Title, or null if the text doesn't contain a valid redirect
319 * This will only return the very next target, useful for
320 * the redirect table and other checks that don't need full recursion
322 * @param $text \type{\string} Text with possible redirect
323 * @return \type{Title} The corresponding Title
325 public static function newFromRedirect( $text ) {
326 return self
::newFromRedirectInternal( $text );
330 * Extract a redirect destination from a string and return the
331 * Title, or null if the text doesn't contain a valid redirect
332 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
333 * in order to provide (hopefully) the Title of the final destination instead of another redirect
335 * @param $text \type{\string} Text with possible redirect
336 * @return \type{Title} The corresponding Title
338 public static function newFromRedirectRecurse( $text ) {
339 $titles = self
::newFromRedirectArray( $text );
340 return $titles ?
array_pop( $titles ) : null;
344 * Extract a redirect destination from a string and return an
345 * array of Titles, or null if the text doesn't contain a valid redirect
346 * The last element in the array is the final destination after all redirects
347 * have been resolved (up to $wgMaxRedirects times)
349 * @param $text \type{\string} Text with possible redirect
350 * @return \type{\array} Array of Titles, with the destination last
352 public static function newFromRedirectArray( $text ) {
353 global $wgMaxRedirects;
354 // are redirects disabled?
355 if ( $wgMaxRedirects < 1 ) {
358 $title = self
::newFromRedirectInternal( $text );
359 if ( is_null( $title ) ) {
362 // recursive check to follow double redirects
363 $recurse = $wgMaxRedirects;
364 $titles = array( $title );
365 while ( --$recurse > 0 ) {
366 if ( $title->isRedirect() ) {
367 $article = new Article( $title, 0 );
368 $newtitle = $article->getRedirectTarget();
372 // Redirects to some special pages are not permitted
373 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
374 // the new title passes the checks, so make that our current title so that further recursion can be checked
376 $titles[] = $newtitle;
385 * Really extract the redirect destination
386 * Do not call this function directly, use one of the newFromRedirect* functions above
388 * @param $text \type{\string} Text with possible redirect
389 * @return \type{Title} The corresponding Title
391 protected static function newFromRedirectInternal( $text ) {
392 $redir = MagicWord
::get( 'redirect' );
393 $text = trim( $text );
394 if ( $redir->matchStartAndRemove( $text ) ) {
395 // Extract the first link and see if it's usable
396 // Ensure that it really does come directly after #REDIRECT
397 // Some older redirects included a colon, so don't freak about that!
399 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
400 // Strip preceding colon used to "escape" categories, etc.
401 // and URL-decode links
402 if ( strpos( $m[1], '%' ) !== false ) {
403 // Match behavior of inline link parsing here;
404 // don't interpret + as " " most of the time!
405 // It might be safe to just use rawurldecode instead, though.
406 $m[1] = urldecode( ltrim( $m[1], ':' ) );
408 $title = Title
::newFromText( $m[1] );
409 // If the title is a redirect to bad special pages or is invalid, return null
410 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
419 # ----------------------------------------------------------------------------
421 # ----------------------------------------------------------------------------
424 * Get the prefixed DB key associated with an ID
426 * @param $id \type{\int} the page_id of the article
427 * @return \type{Title} an object representing the article, or NULL
428 * if no such article was found
430 public static function nameOf( $id ) {
431 $dbr = wfGetDB( DB_SLAVE
);
433 $s = $dbr->selectRow(
435 array( 'page_namespace', 'page_title' ),
436 array( 'page_id' => $id ),
439 if ( $s === false ) {
443 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
448 * Get a regex character class describing the legal characters in a link
450 * @return \type{\string} the list of characters, not delimited
452 public static function legalChars() {
453 global $wgLegalTitleChars;
454 return $wgLegalTitleChars;
458 * Get a string representation of a title suitable for
459 * including in a search index
461 * @param $ns \type{\int} a namespace index
462 * @param $title \type{\string} text-form main part
463 * @return \type{\string} a stripped-down title string ready for the
466 public static function indexTitle( $ns, $title ) {
469 $lc = SearchEngine
::legalSearchChars() . '&#;';
470 $t = $wgContLang->normalizeForSearch( $title );
471 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
472 $t = $wgContLang->lc( $t );
475 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
476 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
478 $t = preg_replace( "/\\s+/", ' ', $t );
480 if ( $ns == NS_FILE
) {
481 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
487 * Make a prefixed DB key from a DB key and a namespace index
489 * @param $ns \type{\int} numerical representation of the namespace
490 * @param $title \type{\string} the DB key form the title
491 * @param $fragment \type{\string} The link fragment (after the "#")
492 * @param $interwiki \type{\string} The interwiki prefix
493 * @return \type{\string} the prefixed form of the title
495 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
498 $namespace = $wgContLang->getNsText( $ns );
499 $name = $namespace == '' ?
$title : "$namespace:$title";
500 if ( strval( $interwiki ) != '' ) {
501 $name = "$interwiki:$name";
503 if ( strval( $fragment ) != '' ) {
504 $name .= '#' . $fragment;
510 * Determine whether the object refers to a page within
513 * @return \type{\bool} TRUE if this is an in-project interwiki link
514 * or a wikilink, FALSE otherwise
516 public function isLocal() {
517 if ( $this->mInterwiki
!= '' ) {
518 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
525 * Determine whether the object refers to a page within
526 * this project and is transcludable.
528 * @return \type{\bool} TRUE if this is transcludable
530 public function isTrans() {
531 if ( $this->mInterwiki
== '' ) {
535 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
539 * Returns the DB name of the distant wiki
540 * which owns the object.
542 * @return \type{\string} the DB name
544 public function getTransWikiID() {
545 if ( $this->mInterwiki
== '' ) {
549 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
553 * Escape a text fragment, say from a link, for a URL
555 * @param $fragment string containing a URL or link fragment (after the "#")
556 * @return String: escaped string
558 static function escapeFragmentForURL( $fragment ) {
559 # Note that we don't urlencode the fragment. urlencoded Unicode
560 # fragments appear not to work in IE (at least up to 7) or in at least
561 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
562 # to care if they aren't encoded.
563 return Sanitizer
::escapeId( $fragment, 'noninitial' );
566 # ----------------------------------------------------------------------------
568 # ----------------------------------------------------------------------------
570 /** Simple accessors */
572 * Get the text form (spaces not underscores) of the main part
574 * @return \type{\string} Main part of the title
576 public function getText() { return $this->mTextform
; }
579 * Get the URL-encoded form of the main part
581 * @return \type{\string} Main part of the title, URL-encoded
583 public function getPartialURL() { return $this->mUrlform
; }
586 * Get the main part with underscores
588 * @return \type{\string} Main part of the title, with underscores
590 public function getDBkey() { return $this->mDbkeyform
; }
593 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
595 * @return \type{\int} Namespace index
597 public function getNamespace() { return $this->mNamespace
; }
600 * Get the namespace text
602 * @return \type{\string} Namespace text
604 public function getNsText() {
607 if ( $this->mInterwiki
!= '' ) {
608 // This probably shouldn't even happen. ohh man, oh yuck.
609 // But for interwiki transclusion it sometimes does.
610 // Shit. Shit shit shit.
612 // Use the canonical namespaces if possible to try to
613 // resolve a foreign namespace.
614 if ( MWNamespace
::exists( $this->mNamespace
) ) {
615 return MWNamespace
::getCanonicalName( $this->mNamespace
);
618 return $wgContLang->getNsText( $this->mNamespace
);
622 * Get the DB key with the initial letter case as specified by the user
624 * @return \type{\string} DB key
626 function getUserCaseDBKey() {
627 return $this->mUserCaseDBKey
;
631 * Get the namespace text of the subject (rather than talk) page
633 * @return \type{\string} Namespace text
635 public function getSubjectNsText() {
637 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
641 * Get the namespace text of the talk page
643 * @return \type{\string} Namespace text
645 public function getTalkNsText() {
647 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
651 * Could this title have a corresponding talk page?
653 * @return \type{\bool} TRUE or FALSE
655 public function canTalk() {
656 return( MWNamespace
::canTalk( $this->mNamespace
) );
660 * Get the interwiki prefix (or null string)
662 * @return \type{\string} Interwiki prefix
664 public function getInterwiki() { return $this->mInterwiki
; }
667 * Get the Title fragment (i.e.\ the bit after the #) in text form
669 * @return \type{\string} Title fragment
671 public function getFragment() { return $this->mFragment
; }
674 * Get the fragment in URL form, including the "#" character if there is one
675 * @return \type{\string} Fragment in URL form
677 public function getFragmentForURL() {
678 if ( $this->mFragment
== '' ) {
681 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
686 * Get the default namespace index, for when there is no namespace
688 * @return \type{\int} Default namespace index
690 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
693 * Get title for search index
695 * @return \type{\string} a stripped-down title string ready for the
698 public function getIndexTitle() {
699 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
703 * Get the prefixed database key form
705 * @return \type{\string} the prefixed title, with underscores and
706 * any interwiki and namespace prefixes
708 public function getPrefixedDBkey() {
709 $s = $this->prefix( $this->mDbkeyform
);
710 $s = str_replace( ' ', '_', $s );
715 * Get the prefixed title with spaces.
716 * This is the form usually used for display
718 * @return \type{\string} the prefixed title, with spaces
720 public function getPrefixedText() {
721 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
722 $s = $this->prefix( $this->mTextform
);
723 $s = str_replace( '_', ' ', $s );
724 $this->mPrefixedText
= $s;
726 return $this->mPrefixedText
;
730 * Get the prefixed title with spaces, plus any fragment
731 * (part beginning with '#')
733 * @return \type{\string} the prefixed title, with spaces and
734 * the fragment, including '#'
736 public function getFullText() {
737 $text = $this->getPrefixedText();
738 if ( $this->mFragment
!= '' ) {
739 $text .= '#' . $this->mFragment
;
745 * Get the base name, i.e. the leftmost parts before the /
747 * @return \type{\string} Base name
749 public function getBaseText() {
750 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
751 return $this->getText();
754 $parts = explode( '/', $this->getText() );
755 # Don't discard the real title if there's no subpage involved
756 if ( count( $parts ) > 1 ) {
757 unset( $parts[count( $parts ) - 1] );
759 return implode( '/', $parts );
763 * Get the lowest-level subpage name, i.e. the rightmost part after /
765 * @return \type{\string} Subpage name
767 public function getSubpageText() {
768 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
769 return( $this->mTextform
);
771 $parts = explode( '/', $this->mTextform
);
772 return( $parts[count( $parts ) - 1] );
776 * Get a URL-encoded form of the subpage text
778 * @return \type{\string} URL-encoded subpage name
780 public function getSubpageUrlForm() {
781 $text = $this->getSubpageText();
782 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
787 * Get a URL-encoded title (not an actual URL) including interwiki
789 * @return \type{\string} the URL-encoded form
791 public function getPrefixedURL() {
792 $s = $this->prefix( $this->mDbkeyform
);
793 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
798 * Get a real URL referring to this title, with interwiki link and
801 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
802 * links. Can be specified as an associative array as well, e.g.,
803 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
804 * @param $variant \type{\string} language variant of url (for sr, zh..)
805 * @return \type{\string} the URL
807 public function getFullURL( $query = '', $variant = false ) {
808 global $wgServer, $wgRequest;
810 if ( is_array( $query ) ) {
811 $query = wfArrayToCGI( $query );
814 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
816 $url = $this->getLocalURL( $query, $variant );
818 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
819 // Correct fix would be to move the prepending elsewhere.
820 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
821 $url = $wgServer . $url;
824 $baseUrl = $interwiki->getURL();
826 $namespace = wfUrlencode( $this->getNsText() );
827 if ( $namespace != '' ) {
828 # Can this actually happen? Interwikis shouldn't be parsed.
829 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
832 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
833 $url = wfAppendQuery( $url, $query );
836 # Finally, add the fragment.
837 $url .= $this->getFragmentForURL();
839 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
844 * Get a URL with no fragment or server name. If this page is generated
845 * with action=render, $wgServer is prepended.
847 * @param $query Mixed: an optional query string; if not specified,
848 * $wgArticlePath will be used. Can be specified as an associative array
849 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
851 * @param $variant \type{\string} language variant of url (for sr, zh..)
852 * @return \type{\string} the URL
854 public function getLocalURL( $query = '', $variant = false ) {
855 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
856 global $wgVariantArticlePath, $wgContLang, $wgUser;
858 if ( is_array( $query ) ) {
859 $query = wfArrayToCGI( $query );
862 // internal links should point to same variant as current page (only anonymous users)
863 if ( !$variant && $wgContLang->hasVariants() && !$wgUser->isLoggedIn() ) {
864 $pref = $wgContLang->getPreferredVariant( false );
865 if ( $pref != $wgContLang->getCode() ) {
870 if ( $this->isExternal() ) {
871 $url = $this->getFullURL();
873 // This is currently only used for edit section links in the
874 // context of interwiki transclusion. In theory we should
875 // append the query to the end of any existing query string,
876 // but interwiki transclusion is already broken in that case.
880 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
881 if ( $query == '' ) {
882 if ( $variant != false && $wgContLang->hasVariants() ) {
883 if ( !$wgVariantArticlePath ) {
884 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
886 $variantArticlePath = $wgVariantArticlePath;
888 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
889 $url = str_replace( '$1', $dbkey, $url );
891 $url = str_replace( '$1', $dbkey, $wgArticlePath );
894 global $wgActionPaths;
897 if ( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
900 $action = urldecode( $matches[2] );
901 if ( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if ( isset( $matches[4] ) ) {
904 $query .= $matches[4];
906 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
907 if ( $query != '' ) {
908 $url = wfAppendQuery( $url, $query );
912 if ( $url === false ) {
913 if ( $query == '-' ) {
916 $url = "{$wgScript}?title={$dbkey}&{$query}";
920 // FIXME: this causes breakage in various places when we
921 // actually expected a local URL and end up with dupe prefixes.
922 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
923 $url = $wgServer . $url;
926 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
931 * Get a URL that's the simplest URL that will be valid to link, locally,
932 * to the current Title. It includes the fragment, but does not include
933 * the server unless action=render is used (or the link is external). If
934 * there's a fragment but the prefixed text is empty, we just return a link
937 * The result obviously should not be URL-escaped, but does need to be
938 * HTML-escaped if it's being output in HTML.
940 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
941 * query string. Keys and values will be escaped.
942 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
943 * for external links. Default is "false" (same variant as current page,
944 * for anonymous users).
945 * @return \type{\string} the URL
947 public function getLinkUrl( $query = array(), $variant = false ) {
948 wfProfileIn( __METHOD__
);
949 if ( $this->isExternal() ) {
950 $ret = $this->getFullURL( $query );
951 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
952 $ret = $this->getFragmentForURL();
954 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
956 wfProfileOut( __METHOD__
);
961 * Get an HTML-escaped version of the URL form, suitable for
962 * using in a link, without a server name or fragment
964 * @param $query \type{\string} an optional query string
965 * @return \type{\string} the URL
967 public function escapeLocalURL( $query = '' ) {
968 return htmlspecialchars( $this->getLocalURL( $query ) );
972 * Get an HTML-escaped version of the URL form, suitable for
973 * using in a link, including the server name and fragment
975 * @param $query \type{\string} an optional query string
976 * @return \type{\string} the URL
978 public function escapeFullURL( $query = '' ) {
979 return htmlspecialchars( $this->getFullURL( $query ) );
983 * Get the URL form for an internal link.
984 * - Used in various Squid-related code, in case we have a different
985 * internal hostname for the server from the exposed one.
987 * @param $query \type{\string} an optional query string
988 * @param $variant \type{\string} language variant of url (for sr, zh..)
989 * @return \type{\string} the URL
991 public function getInternalURL( $query = '', $variant = false ) {
992 global $wgInternalServer;
993 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
994 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
999 * Get the edit URL for this Title
1001 * @return \type{\string} the URL, or a null string if this is an
1004 public function getEditURL() {
1005 if ( $this->mInterwiki
!= '' ) {
1008 $s = $this->getLocalURL( 'action=edit' );
1014 * Get the HTML-escaped displayable text form.
1015 * Used for the title field in <a> tags.
1017 * @return \type{\string} the text, including any prefixes
1019 public function getEscapedText() {
1020 return htmlspecialchars( $this->getPrefixedText() );
1024 * Is this Title interwiki?
1026 * @return \type{\bool}
1028 public function isExternal() {
1029 return ( $this->mInterwiki
!= '' );
1033 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1035 * @param $action \type{\string} Action to check (default: edit)
1036 * @return \type{\bool}
1038 public function isSemiProtected( $action = 'edit' ) {
1039 if ( $this->exists() ) {
1040 $restrictions = $this->getRestrictions( $action );
1041 if ( count( $restrictions ) > 0 ) {
1042 foreach ( $restrictions as $restriction ) {
1043 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1053 # If it doesn't exist, it can't be protected
1059 * Does the title correspond to a protected article?
1061 * @param $action \type{\string} the action the page is protected from,
1062 * by default checks all actions.
1063 * @return \type{\bool}
1065 public function isProtected( $action = '' ) {
1066 global $wgRestrictionLevels;
1068 $restrictionTypes = $this->getRestrictionTypes();
1070 # Special pages have inherent protection
1071 if( $this->getNamespace() == NS_SPECIAL
) {
1075 # Check regular protection levels
1076 foreach ( $restrictionTypes as $type ) {
1077 if ( $action == $type ||
$action == '' ) {
1078 $r = $this->getRestrictions( $type );
1079 foreach ( $wgRestrictionLevels as $level ) {
1080 if ( in_array( $level, $r ) && $level != '' ) {
1091 * Is this a conversion table for the LanguageConverter?
1093 * @return \type{\bool}
1095 public function isConversionTable() {
1097 $this->getNamespace() == NS_MEDIAWIKI
&&
1098 strpos( $this->getText(), 'Conversiontable' ) !== false
1108 * Is $wgUser watching this page?
1110 * @return \type{\bool}
1112 public function userIsWatching() {
1115 if ( is_null( $this->mWatched
) ) {
1116 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1117 $this->mWatched
= false;
1119 $this->mWatched
= $wgUser->isWatched( $this );
1122 return $this->mWatched
;
1126 * Can $wgUser perform $action on this page?
1127 * This skips potentially expensive cascading permission checks
1128 * as well as avoids expensive error formatting
1130 * Suitable for use for nonessential UI controls in common cases, but
1131 * _not_ for functional access control.
1133 * May provide false positives, but should never provide a false negative.
1135 * @param $action \type{\string} action that permission needs to be checked for
1136 * @return \type{\bool}
1138 public function quickUserCan( $action ) {
1139 return $this->userCan( $action, false );
1143 * Determines if $wgUser is unable to edit this page because it has been protected
1144 * by $wgNamespaceProtection.
1146 * @return \type{\bool}
1148 public function isNamespaceProtected() {
1149 global $wgNamespaceProtection, $wgUser;
1150 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1151 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1152 if ( $right != '' && !$wgUser->isAllowed( $right ) ) {
1161 * Can $wgUser perform $action on this page?
1163 * @param $action \type{\string} action that permission needs to be checked for
1164 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1165 * @return \type{\bool}
1167 public function userCan( $action, $doExpensiveQueries = true ) {
1169 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1173 * Can $user perform $action on this page?
1175 * FIXME: This *does not* check throttles (User::pingLimiter()).
1177 * @param $action \type{\string}action that permission needs to be checked for
1178 * @param $user \type{User} user to check
1179 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1180 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1181 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1183 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1184 if ( !StubObject
::isRealObject( $user ) ) {
1185 // Since StubObject is always used on globals, we can
1186 // unstub $wgUser here and set $user = $wgUser
1188 $wgUser->_unstub( '', 5 );
1192 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1194 // Remove the errors being ignored.
1195 foreach ( $errors as $index => $error ) {
1196 $error_key = is_array( $error ) ?
$error[0] : $error;
1198 if ( in_array( $error_key, $ignoreErrors ) ) {
1199 unset( $errors[$index] );
1207 * Permissions checks that fail most often, and which are easiest to test.
1209 * @param $action String the action to check
1210 * @param $user User user to check
1211 * @param $errors Array list of current errors
1212 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1213 * @param $short Boolean short circuit on first error
1215 * @return Array list of errors
1217 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1218 if ( $action == 'create' ) {
1219 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1220 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1221 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1223 } elseif ( $action == 'move' ) {
1224 if ( !$user->isAllowed( 'move-rootuserpages' )
1225 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1226 // Show user page-specific message only if the user can move other pages
1227 $errors[] = array( 'cant-move-user-page' );
1230 // Check if user is allowed to move files if it's a file
1231 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1232 $errors[] = array( 'movenotallowedfile' );
1235 if ( !$user->isAllowed( 'move' ) ) {
1236 // User can't move anything
1237 global $wgGroupPermissions;
1238 $userCanMove = false;
1239 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1240 $userCanMove = $wgGroupPermissions['user']['move'];
1242 $autoconfirmedCanMove = false;
1243 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1244 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1246 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1247 // custom message if logged-in users without any special rights can move
1248 $errors[] = array( 'movenologintext' );
1250 $errors[] = array( 'movenotallowed' );
1253 } elseif ( $action == 'move-target' ) {
1254 if ( !$user->isAllowed( 'move' ) ) {
1255 // User can't move anything
1256 $errors[] = array( 'movenotallowed' );
1257 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1258 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1259 // Show user page-specific message only if the user can move other pages
1260 $errors[] = array( 'cant-move-to-user-page' );
1262 } elseif ( !$user->isAllowed( $action ) ) {
1265 // We avoid expensive display logic for quickUserCan's and such
1268 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1269 User
::getGroupsWithPermission( $action ) );
1276 $wgLang->commaList( $groups ),
1280 $return = array( 'badaccess-group0' );
1282 $errors[] = $return;
1289 * Add the resulting error code to the errors array
1291 * @param $errors Array list of current errors
1292 * @param $result Mixed result of errors
1294 * @return Array list of errors
1296 private function resultToError( $errors, $result ) {
1297 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1298 // A single array representing an error
1299 $errors[] = $result;
1300 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1301 // A nested array representing multiple errors
1302 $errors = array_merge( $errors, $result );
1303 } else if ( $result !== '' && is_string( $result ) ) {
1304 // A string representing a message-id
1305 $errors[] = array( $result );
1306 } else if ( $result === false ) {
1307 // a generic "We don't want them to do that"
1308 $errors[] = array( 'badaccess-group0' );
1314 * Check various permission hooks
1315 * @see checkQuickPermissions for parameter information
1317 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1318 // Use getUserPermissionsErrors instead
1320 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1321 return $result ?
array() : array( array( 'badaccess-group0' ) );
1323 // Check getUserPermissionsErrors hook
1324 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1325 $errors = $this->resultToError( $errors, $result );
1327 // Check getUserPermissionsErrorsExpensive hook
1328 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1329 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1330 $errors = $this->resultToError( $errors, $result );
1337 * Check permissions on special pages & namespaces
1338 * @see checkQuickPermissions for parameter information
1340 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1341 # Only 'createaccount' and 'execute' can be performed on
1342 # special pages, which don't actually exist in the DB.
1343 $specialOKActions = array( 'createaccount', 'execute' );
1344 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1345 $errors[] = array( 'ns-specialprotected' );
1348 # Check $wgNamespaceProtection for restricted namespaces
1349 if ( $this->isNamespaceProtected() ) {
1350 $ns = $this->mNamespace
== NS_MAIN ?
1351 wfMsg( 'nstab-main' ) : $this->getNsText();
1352 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1353 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1360 * Check CSS/JS sub-page permissions
1361 * @see checkQuickPermissions for parameter information
1363 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1364 # Protect css/js subpages of user pages
1365 # XXX: this might be better using restrictions
1366 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1367 # and $this->userCanEditJsSubpage() from working
1368 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1369 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1370 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1371 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1372 $errors[] = array( 'customcssjsprotected' );
1373 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1374 $errors[] = array( 'customcssjsprotected' );
1382 * Check against page_restrictions table requirements on this
1383 * page. The user must possess all required rights for this
1385 * @see checkQuickPermissions for parameter information
1387 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1388 foreach ( $this->getRestrictions( $action ) as $right ) {
1389 // Backwards compatibility, rewrite sysop -> protect
1390 if ( $right == 'sysop' ) {
1393 if ( $right != '' && !$user->isAllowed( $right ) ) {
1394 // Users with 'editprotected' permission can edit protected pages
1395 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1396 // Users with 'editprotected' permission cannot edit protected pages
1397 // with cascading option turned on.
1398 if ( $this->mCascadeRestriction
) {
1399 $errors[] = array( 'protectedpagetext', $right );
1402 $errors[] = array( 'protectedpagetext', $right );
1411 * Check restrictions on cascading pages.
1412 * @see checkQuickPermissions for parameter information
1414 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1415 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1416 # We /could/ use the protection level on the source page, but it's
1417 # fairly ugly as we have to establish a precedence hierarchy for pages
1418 # included by multiple cascade-protected pages. So just restrict
1419 # it to people with 'protect' permission, as they could remove the
1420 # protection anyway.
1421 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1422 # Cascading protection depends on more than this page...
1423 # Several cascading protected pages may include this page...
1424 # Check each cascading level
1425 # This is only for protection restrictions, not for all actions
1426 if ( isset( $restrictions[$action] ) ) {
1427 foreach ( $restrictions[$action] as $right ) {
1428 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1429 if ( $right != '' && !$user->isAllowed( $right ) ) {
1431 foreach ( $cascadingSources as $page )
1432 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1433 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1443 * Check action permissions not already checked in checkQuickPermissions
1444 * @see checkQuickPermissions for parameter information
1446 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1447 if ( $action == 'protect' ) {
1448 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1449 // If they can't edit, they shouldn't protect.
1450 $errors[] = array( 'protect-cantedit' );
1452 } elseif ( $action == 'create' ) {
1453 $title_protection = $this->getTitleProtection();
1454 if( $title_protection ) {
1455 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1456 $title_protection['pt_create_perm'] = 'protect'; // B/C
1458 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1459 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1462 } elseif ( $action == 'move' ) {
1463 // Check for immobile pages
1464 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1465 // Specific message for this case
1466 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1467 } elseif ( !$this->isMovable() ) {
1468 // Less specific message for rarer cases
1469 $errors[] = array( 'immobile-page' );
1471 } elseif ( $action == 'move-target' ) {
1472 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1473 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1474 } elseif ( !$this->isMovable() ) {
1475 $errors[] = array( 'immobile-target-page' );
1482 * Check that the user isn't blocked from editting.
1483 * @see checkQuickPermissions for parameter information
1485 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1490 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1492 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1493 $errors[] = array( 'confirmedittext' );
1496 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1497 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1498 $block = $user->mBlock
;
1500 // This is from OutputPage::blockedPage
1501 // Copied at r23888 by werdna
1503 $id = $user->blockedBy();
1504 $reason = $user->blockedFor();
1505 if ( $reason == '' ) {
1506 $reason = wfMsg( 'blockednoreason' );
1510 if ( is_numeric( $id ) ) {
1511 $name = User
::whoIs( $id );
1516 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1517 $blockid = $block->mId
;
1518 $blockExpiry = $user->mBlock
->mExpiry
;
1519 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1520 if ( $blockExpiry == 'infinity' ) {
1521 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1522 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1524 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1525 if ( !strpos( $option, ':' ) )
1528 list( $show, $value ) = explode( ':', $option );
1530 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1531 $blockExpiry = $show;
1536 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1539 $intended = $user->mBlock
->mAddress
;
1541 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1542 $blockid, $blockExpiry, $intended, $blockTimestamp );
1549 * Can $user perform $action on this page? This is an internal function,
1550 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1551 * checks on wfReadOnly() and blocks)
1553 * @param $action \type{\string} action that permission needs to be checked for
1554 * @param $user \type{User} user to check
1555 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1556 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1557 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1559 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1560 wfProfileIn( __METHOD__
);
1564 'checkQuickPermissions',
1565 'checkPermissionHooks',
1566 'checkSpecialsAndNSPermissions',
1567 'checkCSSandJSPermissions',
1568 'checkPageRestrictions',
1569 'checkCascadingSourcesRestrictions',
1570 'checkActionPermissions',
1574 while( count( $checks ) > 0 &&
1575 !( $short && count( $errors ) > 0 ) ) {
1576 $method = array_shift( $checks );
1577 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1580 wfProfileOut( __METHOD__
);
1585 * Is this title subject to title protection?
1587 * @return \type{\mixed} An associative array representing any existent title
1588 * protection, or false if there's none.
1590 private function getTitleProtection() {
1591 // Can't protect pages in special namespaces
1592 if ( $this->getNamespace() < 0 ) {
1596 // Can't protect pages that exist.
1597 if ( $this->exists() ) {
1601 if ( !isset( $this->mTitleProtection
) ) {
1602 $dbr = wfGetDB( DB_SLAVE
);
1603 $res = $dbr->select( 'protected_titles', '*',
1604 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1607 // fetchRow returns false if there are no rows.
1608 $this->mTitleProtection
= $dbr->fetchRow( $res );
1610 return $this->mTitleProtection
;
1614 * Update the title protection status
1616 * @param $create_perm \type{\string} Permission required for creation
1617 * @param $reason \type{\string} Reason for protection
1618 * @param $expiry \type{\string} Expiry timestamp
1619 * @return boolean true
1621 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1622 global $wgUser, $wgContLang;
1624 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1625 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1630 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1632 $dbw = wfGetDB( DB_MASTER
);
1634 $encodedExpiry = Block
::encodeExpiry( $expiry, $dbw );
1636 $expiry_description = '';
1637 if ( $encodedExpiry != 'infinity' ) {
1638 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1639 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1641 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1644 # Update protection table
1645 if ( $create_perm != '' ) {
1646 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1648 'pt_namespace' => $namespace,
1649 'pt_title' => $title,
1650 'pt_create_perm' => $create_perm,
1651 'pt_timestamp' => Block
::encodeExpiry( wfTimestampNow(), $dbw ),
1652 'pt_expiry' => $encodedExpiry,
1653 'pt_user' => $wgUser->getId(),
1654 'pt_reason' => $reason,
1658 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1659 'pt_title' => $title ), __METHOD__
);
1661 # Update the protection log
1662 if ( $dbw->affectedRows() ) {
1663 $log = new LogPage( 'protect' );
1665 if ( $create_perm ) {
1666 $params = array( "[create=$create_perm] $expiry_description", '' );
1667 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1669 $log->addEntry( 'unprotect', $this, $reason );
1677 * Remove any title protection due to page existing
1679 public function deleteTitleProtection() {
1680 $dbw = wfGetDB( DB_MASTER
);
1684 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1690 * Would anybody with sufficient privileges be able to move this page?
1691 * Some pages just aren't movable.
1693 * @return \type{\bool} TRUE or FALSE
1695 public function isMovable() {
1696 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1700 * Can $wgUser read this page?
1702 * @return \type{\bool}
1703 * @todo fold these checks into userCan()
1705 public function userCanRead() {
1706 global $wgUser, $wgGroupPermissions;
1708 static $useShortcut = null;
1710 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1711 if ( is_null( $useShortcut ) ) {
1712 global $wgRevokePermissions;
1713 $useShortcut = true;
1714 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1715 # Not a public wiki, so no shortcut
1716 $useShortcut = false;
1717 } elseif ( !empty( $wgRevokePermissions ) ) {
1719 * Iterate through each group with permissions being revoked (key not included since we don't care
1720 * what the group name is), then check if the read permission is being revoked. If it is, then
1721 * we don't use the shortcut below since the user might not be able to read, even though anon
1722 * reading is allowed.
1724 foreach ( $wgRevokePermissions as $perms ) {
1725 if ( !empty( $perms['read'] ) ) {
1726 # We might be removing the read right from the user, so no shortcut
1727 $useShortcut = false;
1735 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1736 if ( $result !== null ) {
1740 # Shortcut for public wikis, allows skipping quite a bit of code
1741 if ( $useShortcut ) {
1745 if ( $wgUser->isAllowed( 'read' ) ) {
1748 global $wgWhitelistRead;
1751 * Always grant access to the login page.
1752 * Even anons need to be able to log in.
1754 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1759 * Bail out if there isn't whitelist
1761 if ( !is_array( $wgWhitelistRead ) ) {
1766 * Check for explicit whitelisting
1768 $name = $this->getPrefixedText();
1769 $dbName = $this->getPrefixedDBKey();
1770 // Check with and without underscores
1771 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1775 * Old settings might have the title prefixed with
1776 * a colon for main-namespace pages
1778 if ( $this->getNamespace() == NS_MAIN
) {
1779 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1785 * If it's a special page, ditch the subpage bit
1788 if ( $this->getNamespace() == NS_SPECIAL
) {
1789 $name = $this->getDBkey();
1790 list( $name, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $name );
1791 if ( $name === false ) {
1792 # Invalid special page, but we show standard login required message
1796 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1797 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1807 * Is this a talk page of some sort?
1809 * @return \type{\bool}
1811 public function isTalkPage() {
1812 return MWNamespace
::isTalk( $this->getNamespace() );
1816 * Is this a subpage?
1818 * @return \type{\bool}
1820 public function isSubpage() {
1821 return MWNamespace
::hasSubpages( $this->mNamespace
)
1822 ?
strpos( $this->getText(), '/' ) !== false
1827 * Does this have subpages? (Warning, usually requires an extra DB query.)
1829 * @return \type{\bool}
1831 public function hasSubpages() {
1832 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1837 # We dynamically add a member variable for the purpose of this method
1838 # alone to cache the result. There's no point in having it hanging
1839 # around uninitialized in every Title object; therefore we only add it
1840 # if needed and don't declare it statically.
1841 if ( isset( $this->mHasSubpages
) ) {
1842 return $this->mHasSubpages
;
1845 $subpages = $this->getSubpages( 1 );
1846 if ( $subpages instanceof TitleArray
) {
1847 return $this->mHasSubpages
= (bool)$subpages->count();
1849 return $this->mHasSubpages
= false;
1853 * Get all subpages of this page.
1855 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1856 * @return mixed TitleArray, or empty array if this page's namespace
1857 * doesn't allow subpages
1859 public function getSubpages( $limit = -1 ) {
1860 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1864 $dbr = wfGetDB( DB_SLAVE
);
1865 $conds['page_namespace'] = $this->getNamespace();
1866 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1868 if ( $limit > -1 ) {
1869 $options['LIMIT'] = $limit;
1871 return $this->mSubpages
= TitleArray
::newFromResult(
1872 $dbr->select( 'page',
1873 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1882 * Could this page contain custom CSS or JavaScript, based
1885 * @return \type{\bool}
1887 public function isCssOrJsPage() {
1888 return $this->mNamespace
== NS_MEDIAWIKI
1889 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1893 * Is this a .css or .js subpage of a user page?
1894 * @return \type{\bool}
1896 public function isCssJsSubpage() {
1897 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1901 * Is this a *valid* .css or .js subpage of a user page?
1902 * Check that the corresponding skin exists
1904 * @return \type{\bool}
1906 public function isValidCssJsSubpage() {
1907 if ( $this->isCssJsSubpage() ) {
1908 $name = $this->getSkinFromCssJsSubpage();
1909 if ( $name == 'common' ) {
1912 $skinNames = Skin
::getSkinNames();
1913 return array_key_exists( $name, $skinNames );
1920 * Trim down a .css or .js subpage title to get the corresponding skin name
1922 * @return string containing skin name from .css or .js subpage title
1924 public function getSkinFromCssJsSubpage() {
1925 $subpage = explode( '/', $this->mTextform
);
1926 $subpage = $subpage[ count( $subpage ) - 1 ];
1927 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1931 * Is this a .css subpage of a user page?
1933 * @return \type{\bool}
1935 public function isCssSubpage() {
1936 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1940 * Is this a .js subpage of a user page?
1942 * @return \type{\bool}
1944 public function isJsSubpage() {
1945 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1949 * Protect css subpages of user pages: can $wgUser edit
1952 * @return \type{\bool}
1953 * @todo XXX: this might be better using restrictions
1955 public function userCanEditCssSubpage() {
1957 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
1958 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1962 * Protect js subpages of user pages: can $wgUser edit
1965 * @return \type{\bool}
1966 * @todo XXX: this might be better using restrictions
1968 public function userCanEditJsSubpage() {
1970 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
1971 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1975 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1977 * @return \type{\bool} If the page is subject to cascading restrictions.
1979 public function isCascadeProtected() {
1980 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1981 return ( $sources > 0 );
1985 * Cascading protection: Get the source of any cascading restrictions on this page.
1987 * @param $getPages \type{\bool} Whether or not to retrieve the actual pages
1988 * that the restrictions have come from.
1989 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1990 * objects of the pages from which cascading restrictions have come,
1991 * false for none, or true if such restrictions exist, but $getPages was not set.
1992 * The restriction array is an array of each type, each of which contains a
1993 * array of unique groups.
1995 public function getCascadeProtectionSources( $getPages = true ) {
1996 $pagerestrictions = array();
1998 if ( isset( $this->mCascadeSources
) && $getPages ) {
1999 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2000 } else if ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2001 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2004 wfProfileIn( __METHOD__
);
2006 $dbr = wfGetDB( DB_SLAVE
);
2008 if ( $this->getNamespace() == NS_FILE
) {
2009 $tables = array( 'imagelinks', 'page_restrictions' );
2010 $where_clauses = array(
2011 'il_to' => $this->getDBkey(),
2016 $tables = array( 'templatelinks', 'page_restrictions' );
2017 $where_clauses = array(
2018 'tl_namespace' => $this->getNamespace(),
2019 'tl_title' => $this->getDBkey(),
2026 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2027 'pr_expiry', 'pr_type', 'pr_level' );
2028 $where_clauses[] = 'page_id=pr_page';
2031 $cols = array( 'pr_expiry' );
2034 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2036 $sources = $getPages ?
array() : false;
2037 $now = wfTimestampNow();
2038 $purgeExpired = false;
2040 foreach ( $res as $row ) {
2041 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2042 if ( $expiry > $now ) {
2044 $page_id = $row->pr_page
;
2045 $page_ns = $row->page_namespace
;
2046 $page_title = $row->page_title
;
2047 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2048 # Add groups needed for each restriction type if its not already there
2049 # Make sure this restriction type still exists
2051 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2052 $pagerestrictions[$row->pr_type
] = array();
2055 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2056 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2057 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2063 // Trigger lazy purge of expired restrictions from the db
2064 $purgeExpired = true;
2067 if ( $purgeExpired ) {
2068 Title
::purgeExpiredRestrictions();
2071 wfProfileOut( __METHOD__
);
2074 $this->mCascadeSources
= $sources;
2075 $this->mCascadingRestrictions
= $pagerestrictions;
2077 $this->mHasCascadingRestrictions
= $sources;
2080 return array( $sources, $pagerestrictions );
2084 * Returns cascading restrictions for the current article
2088 function areRestrictionsCascading() {
2089 if ( !$this->mRestrictionsLoaded
) {
2090 $this->loadRestrictions();
2093 return $this->mCascadeRestriction
;
2097 * Loads a string into mRestrictions array
2099 * @param $res \type{Resource} restrictions as an SQL result.
2100 * @param $oldFashionedRestrictions string comma-separated list of page
2101 * restrictions from page table (pre 1.10)
2103 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2105 $dbr = wfGetDB( DB_SLAVE
);
2107 while ( $row = $dbr->fetchObject( $res ) ) {
2111 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2115 * Compiles list of active page restrictions from both page table (pre 1.10)
2116 * and page_restrictions table
2118 * @param $rows array of db result objects
2119 * @param $oldFashionedRestrictions string comma-separated list of page
2120 * restrictions from page table (pre 1.10)
2122 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2123 $dbr = wfGetDB( DB_SLAVE
);
2125 $restrictionTypes = $this->getRestrictionTypes();
2127 foreach ( $restrictionTypes as $type ) {
2128 $this->mRestrictions
[$type] = array();
2129 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry( '' );
2132 $this->mCascadeRestriction
= false;
2134 # Backwards-compatibility: also load the restrictions from the page record (old format).
2136 if ( $oldFashionedRestrictions === null ) {
2137 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2138 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2141 if ( $oldFashionedRestrictions != '' ) {
2143 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2144 $temp = explode( '=', trim( $restrict ) );
2145 if ( count( $temp ) == 1 ) {
2146 // old old format should be treated as edit/move restriction
2147 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2148 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2150 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2154 $this->mOldRestrictions
= true;
2158 if ( count( $rows ) ) {
2159 # Current system - load second to make them override.
2160 $now = wfTimestampNow();
2161 $purgeExpired = false;
2163 foreach ( $rows as $row ) {
2164 # Cycle through all the restrictions.
2166 // Don't take care of restrictions types that aren't allowed
2168 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2171 // This code should be refactored, now that it's being used more generally,
2172 // But I don't really see any harm in leaving it in Block for now -werdna
2173 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2175 // Only apply the restrictions if they haven't expired!
2176 if ( !$expiry ||
$expiry > $now ) {
2177 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2178 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2180 $this->mCascadeRestriction |
= $row->pr_cascade
;
2182 // Trigger a lazy purge of expired restrictions
2183 $purgeExpired = true;
2187 if ( $purgeExpired ) {
2188 Title
::purgeExpiredRestrictions();
2192 $this->mRestrictionsLoaded
= true;
2196 * Load restrictions from the page_restrictions table
2198 * @param $oldFashionedRestrictions string comma-separated list of page
2199 * restrictions from page table (pre 1.10)
2201 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2202 if ( !$this->mRestrictionsLoaded
) {
2203 if ( $this->exists() ) {
2204 $dbr = wfGetDB( DB_SLAVE
);
2206 $res = $dbr->select( 'page_restrictions', '*',
2207 array( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2209 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2211 $title_protection = $this->getTitleProtection();
2213 if ( $title_protection ) {
2214 $now = wfTimestampNow();
2215 $expiry = Block
::decodeExpiry( $title_protection['pt_expiry'] );
2217 if ( !$expiry ||
$expiry > $now ) {
2218 // Apply the restrictions
2219 $this->mRestrictionsExpiry
['create'] = $expiry;
2220 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2221 } else { // Get rid of the old restrictions
2222 Title
::purgeExpiredRestrictions();
2225 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry( '' );
2227 $this->mRestrictionsLoaded
= true;
2233 * Purge expired restrictions from the page_restrictions table
2235 static function purgeExpiredRestrictions() {
2236 $dbw = wfGetDB( DB_MASTER
);
2238 'page_restrictions',
2239 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2245 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2251 * Accessor/initialisation for mRestrictions
2253 * @param $action \type{\string} action that permission needs to be checked for
2254 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2256 public function getRestrictions( $action ) {
2257 if ( !$this->mRestrictionsLoaded
) {
2258 $this->loadRestrictions();
2260 return isset( $this->mRestrictions
[$action] )
2261 ?
$this->mRestrictions
[$action]
2266 * Get the expiry time for the restriction against a given action
2268 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2269 * or not protected at all, or false if the action is not recognised.
2271 public function getRestrictionExpiry( $action ) {
2272 if ( !$this->mRestrictionsLoaded
) {
2273 $this->loadRestrictions();
2275 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2279 * Is there a version of this page in the deletion archive?
2281 * @return \type{\int} the number of archived revisions
2283 public function isDeleted() {
2284 if ( $this->getNamespace() < 0 ) {
2287 $dbr = wfGetDB( DB_SLAVE
);
2288 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2289 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2292 if ( $this->getNamespace() == NS_FILE
) {
2293 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2294 array( 'fa_name' => $this->getDBkey() ),
2303 * Is there a version of this page in the deletion archive?
2307 public function isDeletedQuick() {
2308 if ( $this->getNamespace() < 0 ) {
2311 $dbr = wfGetDB( DB_SLAVE
);
2312 $deleted = (bool)$dbr->selectField( 'archive', '1',
2313 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2316 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2317 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2318 array( 'fa_name' => $this->getDBkey() ),
2326 * Get the article ID for this Title from the link cache,
2327 * adding it if necessary
2329 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2331 * @return \type{\int} the ID
2333 public function getArticleID( $flags = 0 ) {
2334 if ( $this->getNamespace() < 0 ) {
2335 return $this->mArticleID
= 0;
2337 $linkCache = LinkCache
::singleton();
2338 if ( $flags & GAID_FOR_UPDATE
) {
2339 $oldUpdate = $linkCache->forUpdate( true );
2340 $linkCache->clearLink( $this );
2341 $this->mArticleID
= $linkCache->addLinkObj( $this );
2342 $linkCache->forUpdate( $oldUpdate );
2344 if ( -1 == $this->mArticleID
) {
2345 $this->mArticleID
= $linkCache->addLinkObj( $this );
2348 return $this->mArticleID
;
2352 * Is this an article that is a redirect page?
2353 * Uses link cache, adding it if necessary
2355 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2356 * @return \type{\bool}
2358 public function isRedirect( $flags = 0 ) {
2359 if ( !is_null( $this->mRedirect
) ) {
2360 return $this->mRedirect
;
2362 # Calling getArticleID() loads the field from cache as needed
2363 if ( !$this->getArticleID( $flags ) ) {
2364 return $this->mRedirect
= false;
2366 $linkCache = LinkCache
::singleton();
2367 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2369 return $this->mRedirect
;
2373 * What is the length of this page?
2374 * Uses link cache, adding it if necessary
2376 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2377 * @return \type{\bool}
2379 public function getLength( $flags = 0 ) {
2380 if ( $this->mLength
!= -1 ) {
2381 return $this->mLength
;
2383 # Calling getArticleID() loads the field from cache as needed
2384 if ( !$this->getArticleID( $flags ) ) {
2385 return $this->mLength
= 0;
2387 $linkCache = LinkCache
::singleton();
2388 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2390 return $this->mLength
;
2394 * What is the page_latest field for this page?
2396 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2397 * @return \type{\int} or 0 if the page doesn't exist
2399 public function getLatestRevID( $flags = 0 ) {
2400 if ( $this->mLatestID
!== false ) {
2401 return intval( $this->mLatestID
);
2403 # Calling getArticleID() loads the field from cache as needed
2404 if ( !$this->getArticleID( $flags ) ) {
2405 return $this->mLatestID
= 0;
2407 $linkCache = LinkCache
::singleton();
2408 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2410 return $this->mLatestID
;
2414 * This clears some fields in this object, and clears any associated
2415 * keys in the "bad links" section of the link cache.
2417 * - This is called from Article::insertNewArticle() to allow
2418 * loading of the new page_id. It's also called from
2419 * Article::doDeleteArticle()
2421 * @param $newid \type{\int} the new Article ID
2423 public function resetArticleID( $newid ) {
2424 $linkCache = LinkCache
::singleton();
2425 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2427 if ( $newid === false ) {
2428 $this->mArticleID
= -1;
2430 $this->mArticleID
= intval( $newid );
2432 $this->mRestrictionsLoaded
= false;
2433 $this->mRestrictions
= array();
2434 $this->mRedirect
= null;
2435 $this->mLength
= -1;
2436 $this->mLatestID
= false;
2440 * Updates page_touched for this page; called from LinksUpdate.php
2442 * @return \type{\bool} true if the update succeded
2444 public function invalidateCache() {
2445 if ( wfReadOnly() ) {
2448 $dbw = wfGetDB( DB_MASTER
);
2449 $success = $dbw->update(
2451 array( 'page_touched' => $dbw->timestamp() ),
2455 HTMLFileCache
::clearFileCache( $this );
2460 * Prefix some arbitrary text with the namespace or interwiki prefix
2463 * @param $name \type{\string} the text
2464 * @return \type{\string} the prefixed text
2467 /* private */ function prefix( $name ) {
2469 if ( $this->mInterwiki
!= '' ) {
2470 $p = $this->mInterwiki
. ':';
2472 if ( 0 != $this->mNamespace
) {
2473 $p .= $this->getNsText() . ':';
2479 * Returns a simple regex that will match on characters and sequences invalid in titles.
2480 * Note that this doesn't pick up many things that could be wrong with titles, but that
2481 * replacing this regex with something valid will make many titles valid.
2483 * @return string regex string
2485 static function getTitleInvalidRegex() {
2486 static $rxTc = false;
2488 # Matching titles will be held as illegal.
2490 # Any character not allowed is forbidden...
2491 '[^' . Title
::legalChars() . ']' .
2492 # URL percent encoding sequences interfere with the ability
2493 # to round-trip titles -- you can't link to them consistently.
2494 '|%[0-9A-Fa-f]{2}' .
2495 # XML/HTML character references produce similar issues.
2496 '|&[A-Za-z0-9\x80-\xff]+;' .
2498 '|&#x[0-9A-Fa-f]+;' .
2506 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2508 * @param $text string containing title to capitalize
2509 * @param $ns int namespace index, defaults to NS_MAIN
2510 * @return String containing capitalized title
2512 public static function capitalize( $text, $ns = NS_MAIN
) {
2515 if ( MWNamespace
::isCapitalized( $ns ) ) {
2516 return $wgContLang->ucfirst( $text );
2523 * Secure and split - main initialisation function for this object
2525 * Assumes that mDbkeyform has been set, and is urldecoded
2526 * and uses underscores, but not otherwise munged. This function
2527 * removes illegal characters, splits off the interwiki and
2528 * namespace prefixes, sets the other forms, and canonicalizes
2531 * @return \type{\bool} true on success
2533 private function secureAndSplit() {
2534 global $wgContLang, $wgLocalInterwiki;
2537 $rxTc = self
::getTitleInvalidRegex();
2539 $this->mInterwiki
= $this->mFragment
= '';
2540 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2542 $dbkey = $this->mDbkeyform
;
2544 # Strip Unicode bidi override characters.
2545 # Sometimes they slip into cut-n-pasted page titles, where the
2546 # override chars get included in list displays.
2547 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2549 # Clean up whitespace
2550 # Note: use of the /u option on preg_replace here will cause
2551 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2552 # conveniently disabling them.
2554 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2555 $dbkey = trim( $dbkey, '_' );
2557 if ( $dbkey == '' ) {
2561 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2562 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2566 $this->mDbkeyform
= $dbkey;
2568 # Initial colon indicates main namespace rather than specified default
2569 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2570 if ( ':' == $dbkey { 0 } ) {
2571 $this->mNamespace
= NS_MAIN
;
2572 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2573 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2576 # Namespace or interwiki prefix
2578 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2581 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2583 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2584 # Ordinary namespace
2586 $this->mNamespace
= $ns;
2587 # For Talk:X pages, check if X has a "namespace" prefix
2588 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2589 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2590 return false; # Disallow Talk:File:x type titles...
2591 } else if ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2592 return false; # Disallow Talk:Interwiki:x type titles...
2595 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2596 if ( !$firstPass ) {
2597 # Can't make a local interwiki link to an interwiki link.
2598 # That's just crazy!
2604 $this->mInterwiki
= $wgContLang->lc( $p );
2606 # Redundant interwiki prefix to the local wiki
2607 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2608 if ( $dbkey == '' ) {
2609 # Can't have an empty self-link
2612 $this->mInterwiki
= '';
2614 # Do another namespace split...
2618 # If there's an initial colon after the interwiki, that also
2619 # resets the default namespace
2620 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2621 $this->mNamespace
= NS_MAIN
;
2622 $dbkey = substr( $dbkey, 1 );
2625 # If there's no recognized interwiki or namespace,
2626 # then let the colon expression be part of the title.
2631 # We already know that some pages won't be in the database!
2633 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2634 $this->mArticleID
= 0;
2636 $fragment = strstr( $dbkey, '#' );
2637 if ( false !== $fragment ) {
2638 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2639 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2640 # remove whitespace again: prevents "Foo_bar_#"
2641 # becoming "Foo_bar_"
2642 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2645 # Reject illegal characters.
2647 if ( preg_match( $rxTc, $dbkey ) ) {
2652 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2653 * reachable due to the way web browsers deal with 'relative' URLs.
2654 * Also, they conflict with subpage syntax. Forbid them explicitly.
2656 if ( strpos( $dbkey, '.' ) !== false &&
2657 ( $dbkey === '.' ||
$dbkey === '..' ||
2658 strpos( $dbkey, './' ) === 0 ||
2659 strpos( $dbkey, '../' ) === 0 ||
2660 strpos( $dbkey, '/./' ) !== false ||
2661 strpos( $dbkey, '/../' ) !== false ||
2662 substr( $dbkey, -2 ) == '/.' ||
2663 substr( $dbkey, -3 ) == '/..' ) )
2669 * Magic tilde sequences? Nu-uh!
2671 if ( strpos( $dbkey, '~~~' ) !== false ) {
2676 * Limit the size of titles to 255 bytes.
2677 * This is typically the size of the underlying database field.
2678 * We make an exception for special pages, which don't need to be stored
2679 * in the database, and may edge over 255 bytes due to subpage syntax
2680 * for long titles, e.g. [[Special:Block/Long name]]
2682 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2683 strlen( $dbkey ) > 512 )
2689 * Normally, all wiki links are forced to have
2690 * an initial capital letter so [[foo]] and [[Foo]]
2691 * point to the same place.
2693 * Don't force it for interwikis, since the other
2694 * site might be case-sensitive.
2696 $this->mUserCaseDBKey
= $dbkey;
2697 if ( $this->mInterwiki
== '' ) {
2698 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2702 * Can't make a link to a namespace alone...
2703 * "empty" local links can only be self-links
2704 * with a fragment identifier.
2706 if ( $dbkey == '' &&
2707 $this->mInterwiki
== '' &&
2708 $this->mNamespace
!= NS_MAIN
) {
2711 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2712 // IP names are not allowed for accounts, and can only be referring to
2713 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2714 // there are numerous ways to present the same IP. Having sp:contribs scan
2715 // them all is silly and having some show the edits and others not is
2716 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2717 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2718 IP
::sanitizeIP( $dbkey ) : $dbkey;
2719 // Any remaining initial :s are illegal.
2720 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2725 $this->mDbkeyform
= $dbkey;
2726 $this->mUrlform
= wfUrlencode( $dbkey );
2728 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2734 * Set the fragment for this title. Removes the first character from the
2735 * specified fragment before setting, so it assumes you're passing it with
2738 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2739 * Still in active use privately.
2741 * @param $fragment \type{\string} text
2743 public function setFragment( $fragment ) {
2744 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2748 * Get a Title object associated with the talk page of this article
2750 * @return \type{Title} the object for the talk page
2752 public function getTalkPage() {
2753 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2757 * Get a title object associated with the subject page of this
2760 * @return \type{Title} the object for the subject page
2762 public function getSubjectPage() {
2763 // Is this the same title?
2764 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2765 if ( $this->getNamespace() == $subjectNS ) {
2768 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2772 * Get an array of Title objects linking to this Title
2773 * Also stores the IDs in the link cache.
2775 * WARNING: do not use this function on arbitrary user-supplied titles!
2776 * On heavily-used templates it will max out the memory.
2778 * @param $options Array: may be FOR UPDATE
2779 * @param $table String: table name
2780 * @param $prefix String: fields prefix
2781 * @return \type{\arrayof{Title}} the Title objects linking here
2783 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2784 $linkCache = LinkCache
::singleton();
2786 if ( count( $options ) > 0 ) {
2787 $db = wfGetDB( DB_MASTER
);
2789 $db = wfGetDB( DB_SLAVE
);
2793 array( 'page', $table ),
2794 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2796 "{$prefix}_from=page_id",
2797 "{$prefix}_namespace" => $this->getNamespace(),
2798 "{$prefix}_title" => $this->getDBkey() ),
2804 if ( $db->numRows( $res ) ) {
2805 foreach ( $res as $row ) {
2806 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2807 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
2808 $retVal[] = $titleObj;
2816 * Get an array of Title objects using this Title as a template
2817 * Also stores the IDs in the link cache.
2819 * WARNING: do not use this function on arbitrary user-supplied titles!
2820 * On heavily-used templates it will max out the memory.
2822 * @param $options Array: may be FOR UPDATE
2823 * @return \type{\arrayof{Title}} the Title objects linking here
2825 public function getTemplateLinksTo( $options = array() ) {
2826 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2830 * Get an array of Title objects referring to non-existent articles linked from this page
2832 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2833 * @return \type{\arrayof{Title}} the Title objects
2835 public function getBrokenLinksFrom() {
2836 if ( $this->getArticleId() == 0 ) {
2837 # All links from article ID 0 are false positives
2841 $dbr = wfGetDB( DB_SLAVE
);
2842 $res = $dbr->select(
2843 array( 'page', 'pagelinks' ),
2844 array( 'pl_namespace', 'pl_title' ),
2846 'pl_from' => $this->getArticleId(),
2847 'page_namespace IS NULL'
2849 __METHOD__
, array(),
2853 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2859 foreach ( $res as $row ) {
2860 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2867 * Get a list of URLs to purge from the Squid cache when this
2870 * @return \type{\arrayof{\string}} the URLs
2872 public function getSquidURLs() {
2876 $this->getInternalURL(),
2877 $this->getInternalURL( 'action=history' )
2880 // purge variant urls as well
2881 if ( $wgContLang->hasVariants() ) {
2882 $variants = $wgContLang->getVariants();
2883 foreach ( $variants as $vCode ) {
2884 $urls[] = $this->getInternalURL( '', $vCode );
2892 * Purge all applicable Squid URLs
2894 public function purgeSquid() {
2896 if ( $wgUseSquid ) {
2897 $urls = $this->getSquidURLs();
2898 $u = new SquidUpdate( $urls );
2904 * Move this page without authentication
2906 * @param $nt \type{Title} the new page Title
2907 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2909 public function moveNoAuth( &$nt ) {
2910 return $this->moveTo( $nt, false );
2914 * Check whether a given move operation would be valid.
2915 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2917 * @param $nt \type{Title} the new title
2918 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2920 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2921 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2923 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2928 // Normally we'd add this to $errors, but we'll get
2929 // lots of syntax errors if $nt is not an object
2930 return array( array( 'badtitletext' ) );
2932 if ( $this->equals( $nt ) ) {
2933 $errors[] = array( 'selfmove' );
2935 if ( !$this->isMovable() ) {
2936 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2938 if ( $nt->getInterwiki() != '' ) {
2939 $errors[] = array( 'immobile-target-namespace-iw' );
2941 if ( !$nt->isMovable() ) {
2942 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2945 $oldid = $this->getArticleID();
2946 $newid = $nt->getArticleID();
2948 if ( strlen( $nt->getDBkey() ) < 1 ) {
2949 $errors[] = array( 'articleexists' );
2951 if ( ( $this->getDBkey() == '' ) ||
2953 ( $nt->getDBkey() == '' ) ) {
2954 $errors[] = array( 'badarticleerror' );
2957 // Image-specific checks
2958 if ( $this->getNamespace() == NS_FILE
) {
2959 if ( $nt->getNamespace() != NS_FILE
) {
2960 $errors[] = array( 'imagenocrossnamespace' );
2962 $file = wfLocalFile( $this );
2963 if ( $file->exists() ) {
2964 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2965 $errors[] = array( 'imageinvalidfilename' );
2967 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2968 $errors[] = array( 'imagetypemismatch' );
2971 $destfile = wfLocalFile( $nt );
2972 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2973 $errors[] = array( 'file-exists-sharedrepo' );
2977 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
2978 $errors[] = array( 'nonfile-cannot-move-to-file' );
2982 $errors = wfMergeErrorArrays( $errors,
2983 $this->getUserPermissionsErrors( 'move', $wgUser ),
2984 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2985 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2986 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2989 $match = EditPage
::matchSummarySpamRegex( $reason );
2990 if ( $match !== false ) {
2991 // This is kind of lame, won't display nice
2992 $errors[] = array( 'spamprotectiontext' );
2996 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2997 $errors[] = array( 'hookaborted', $err );
3000 # The move is allowed only if (1) the target doesn't exist, or
3001 # (2) the target is a redirect to the source, and has no history
3002 # (so we can undo bad moves right after they're done).
3004 if ( 0 != $newid ) { # Target exists; check for validity
3005 if ( !$this->isValidMoveTarget( $nt ) ) {
3006 $errors[] = array( 'articleexists' );
3009 $tp = $nt->getTitleProtection();
3010 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3011 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3012 $errors[] = array( 'cantmove-titleprotected' );
3015 if ( empty( $errors ) ) {
3022 * Move a title to a new location
3024 * @param $nt \type{Title} the new title
3025 * @param $auth \type{\bool} indicates whether $wgUser's permissions
3027 * @param $reason \type{\string} The reason for the move
3028 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
3029 * Ignored if the user doesn't have the suppressredirect right.
3030 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
3032 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3035 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3036 if ( is_array( $err ) ) {
3040 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
3041 $dbw = wfGetDB( DB_MASTER
);
3042 if ( $this->getNamespace() == NS_FILE
) {
3043 $file = wfLocalFile( $this );
3044 if ( $file->exists() ) {
3045 $status = $file->move( $nt );
3046 if ( !$status->isOk() ) {
3047 return $status->getErrorsArray();
3052 $pageid = $this->getArticleID();
3053 $protected = $this->isProtected();
3054 if ( $nt->exists() ) {
3055 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
3056 $pageCountChange = ( $createRedirect ?
0 : -1 );
3057 } else { # Target didn't exist, do normal move.
3058 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
3059 $pageCountChange = ( $createRedirect ?
1 : 0 );
3062 if ( is_array( $err ) ) {
3065 $redirid = $this->getArticleID();
3067 // Refresh the sortkey for this row. Be careful to avoid resetting
3068 // cl_timestamp, which may disturb time-based lists on some sites.
3069 $prefix = $dbw->selectField(
3071 'cl_sortkey_prefix',
3072 array( 'cl_from' => $pageid ),
3075 $dbw->update( 'categorylinks',
3077 'cl_sortkey' => $wgContLang->convertToSortkey( $nt->getCategorySortkey( $prefix ) ),
3078 'cl_timestamp=cl_timestamp' ),
3079 array( 'cl_from' => $pageid ),
3083 # Protect the redirect title as the title used to be...
3084 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3086 'pr_page' => $redirid,
3087 'pr_type' => 'pr_type',
3088 'pr_level' => 'pr_level',
3089 'pr_cascade' => 'pr_cascade',
3090 'pr_user' => 'pr_user',
3091 'pr_expiry' => 'pr_expiry'
3093 array( 'pr_page' => $pageid ),
3097 # Update the protection log
3098 $log = new LogPage( 'protect' );
3099 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3101 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3103 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3107 $oldnamespace = $this->getNamespace() & ~
1;
3108 $newnamespace = $nt->getNamespace() & ~
1;
3109 $oldtitle = $this->getDBkey();
3110 $newtitle = $nt->getDBkey();
3112 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3113 WatchedItem
::duplicateEntries( $this, $nt );
3116 # Update search engine
3117 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3119 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3123 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3124 # No longer a content page
3125 # Not viewed, edited, removing
3126 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3127 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3128 # Now a content page
3129 # Not viewed, edited, adding
3130 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3131 } elseif ( $pageCountChange ) {
3133 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3141 # Update message cache for interface messages
3142 global $wgMessageCache;
3143 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3144 # @bug 17860: old article can be deleted, if this the case,
3145 # delete it from message cache
3146 if ( $this->getArticleID() === 0 ) {
3147 $wgMessageCache->replace( $this->getDBkey(), false );
3149 $oldarticle = new Article( $this );
3150 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3153 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3154 $newarticle = new Article( $nt );
3155 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3159 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3164 * Move page to a title which is at present a redirect to the
3167 * @param $nt \type{Title} the page to move to, which should currently
3169 * @param $reason \type{\string} The reason for the move
3170 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3171 * Ignored if the user doesn't have the suppressredirect right
3173 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3174 global $wgUseSquid, $wgUser, $wgContLang;
3176 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3179 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3181 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3182 $comment = $wgContLang->truncate( $comment, 250 );
3184 $now = wfTimestampNow();
3185 $newid = $nt->getArticleID();
3186 $oldid = $this->getArticleID();
3187 $latest = $this->getLatestRevID();
3189 $dbw = wfGetDB( DB_MASTER
);
3191 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3192 $newns = $nt->getNamespace();
3193 $newdbk = $nt->getDBkey();
3195 # Delete the old redirect. We don't save it to history since
3196 # by definition if we've got here it's rather uninteresting.
3197 # We have to remove it so that the next step doesn't trigger
3198 # a conflict on the unique namespace+title index...
3199 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3200 if ( !$dbw->cascadingDeletes() ) {
3201 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3202 global $wgUseTrackbacks;
3203 if ( $wgUseTrackbacks ) {
3204 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3206 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3207 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3208 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3209 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3210 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3211 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3212 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3214 // If the redirect was recently created, it may have an entry in recentchanges still
3215 $dbw->delete( 'recentchanges',
3216 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3220 # Save a null revision in the page's history notifying of the move
3221 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3222 $nullRevId = $nullRevision->insertOn( $dbw );
3224 $article = new Article( $this );
3225 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3227 # Change the name of the target page:
3228 $dbw->update( 'page',
3230 'page_touched' => $dbw->timestamp( $now ),
3231 'page_namespace' => $nt->getNamespace(),
3232 'page_title' => $nt->getDBkey(),
3233 'page_latest' => $nullRevId,
3235 /* WHERE */ array( 'page_id' => $oldid ),
3238 $nt->resetArticleID( $oldid );
3240 # Recreate the redirect, this time in the other direction.
3241 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3242 $mwRedir = MagicWord
::get( 'redirect' );
3243 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3244 $redirectArticle = new Article( $this );
3245 $newid = $redirectArticle->insertOn( $dbw );
3246 $redirectRevision = new Revision( array(
3248 'comment' => $comment,
3249 'text' => $redirectText ) );
3250 $redirectRevision->insertOn( $dbw );
3251 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3253 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3255 # Now, we record the link from the redirect to the new title.
3256 # It should have no other outgoing links...
3257 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3258 $dbw->insert( 'pagelinks',
3260 'pl_from' => $newid,
3261 'pl_namespace' => $nt->getNamespace(),
3262 'pl_title' => $nt->getDBkey() ),
3264 $redirectSuppressed = false;
3266 $this->resetArticleID( 0 );
3267 $redirectSuppressed = true;
3271 $log = new LogPage( 'move' );
3272 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3275 if ( $wgUseSquid ) {
3276 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3277 $u = new SquidUpdate( $urls );
3284 * Move page to non-existing title.
3286 * @param $nt \type{Title} the new Title
3287 * @param $reason \type{\string} The reason for the move
3288 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3289 * Ignored if the user doesn't have the suppressredirect right
3291 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3292 global $wgUser, $wgContLang;
3294 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3296 $comment .= wfMsgExt( 'colon-separator',
3297 array( 'escapenoentities', 'content' ) );
3298 $comment .= $reason;
3300 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3301 $comment = $wgContLang->truncate( $comment, 250 );
3303 $newid = $nt->getArticleID();
3304 $oldid = $this->getArticleID();
3305 $latest = $this->getLatestRevId();
3307 $dbw = wfGetDB( DB_MASTER
);
3308 $now = $dbw->timestamp();
3310 # Save a null revision in the page's history notifying of the move
3311 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3312 if ( !is_object( $nullRevision ) ) {
3313 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3315 $nullRevId = $nullRevision->insertOn( $dbw );
3317 $article = new Article( $this );
3318 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3321 $dbw->update( 'page',
3323 'page_touched' => $now,
3324 'page_namespace' => $nt->getNamespace(),
3325 'page_title' => $nt->getDBkey(),
3326 'page_latest' => $nullRevId,
3328 /* WHERE */ array( 'page_id' => $oldid ),
3331 $nt->resetArticleID( $oldid );
3333 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3335 $mwRedir = MagicWord
::get( 'redirect' );
3336 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3337 $redirectArticle = new Article( $this );
3338 $newid = $redirectArticle->insertOn( $dbw );
3339 $redirectRevision = new Revision( array(
3341 'comment' => $comment,
3342 'text' => $redirectText ) );
3343 $redirectRevision->insertOn( $dbw );
3344 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3346 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3348 # Record the just-created redirect's linking to the page
3349 $dbw->insert( 'pagelinks',
3351 'pl_from' => $newid,
3352 'pl_namespace' => $nt->getNamespace(),
3353 'pl_title' => $nt->getDBkey() ),
3355 $redirectSuppressed = false;
3357 $this->resetArticleID( 0 );
3358 $redirectSuppressed = true;
3362 $log = new LogPage( 'move' );
3363 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3365 # Purge caches as per article creation
3366 Article
::onArticleCreate( $nt );
3368 # Purge old title from squid
3369 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3370 $this->purgeSquid();
3374 * Move this page's subpages to be subpages of $nt
3376 * @param $nt Title Move target
3377 * @param $auth bool Whether $wgUser's permissions should be checked
3378 * @param $reason string The reason for the move
3379 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3380 * Ignored if the user doesn't have the 'suppressredirect' right
3381 * @return mixed array with old page titles as keys, and strings (new page titles) or
3382 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3384 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3385 global $wgMaximumMovedPages;
3386 // Check permissions
3387 if ( !$this->userCan( 'move-subpages' ) ) {
3388 return array( 'cant-move-subpages' );
3390 // Do the source and target namespaces support subpages?
3391 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3392 return array( 'namespace-nosubpages',
3393 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3395 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3396 return array( 'namespace-nosubpages',
3397 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3400 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3403 foreach ( $subpages as $oldSubpage ) {
3405 if ( $count > $wgMaximumMovedPages ) {
3406 $retval[$oldSubpage->getPrefixedTitle()] =
3407 array( 'movepage-max-pages',
3408 $wgMaximumMovedPages );
3412 // We don't know whether this function was called before
3413 // or after moving the root page, so check both
3415 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3416 $oldSubpage->getArticleID() == $nt->getArticleId() )
3418 // When moving a page to a subpage of itself,
3419 // don't move it twice
3422 $newPageName = preg_replace(
3423 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3424 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3425 $oldSubpage->getDBkey() );
3426 if ( $oldSubpage->isTalkPage() ) {
3427 $newNs = $nt->getTalkPage()->getNamespace();
3429 $newNs = $nt->getSubjectPage()->getNamespace();
3431 # Bug 14385: we need makeTitleSafe because the new page names may
3432 # be longer than 255 characters.
3433 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3435 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3436 if ( $success === true ) {
3437 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3439 $retval[$oldSubpage->getPrefixedText()] = $success;
3446 * Checks if this page is just a one-rev redirect.
3447 * Adds lock, so don't use just for light purposes.
3449 * @return \type{\bool}
3451 public function isSingleRevRedirect() {
3452 $dbw = wfGetDB( DB_MASTER
);
3454 $row = $dbw->selectRow( 'page',
3455 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3458 array( 'FOR UPDATE' )
3460 # Cache some fields we may want
3461 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3462 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3463 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3464 if ( !$this->mRedirect
) {
3467 # Does the article have a history?
3468 $row = $dbw->selectField( array( 'page', 'revision' ),
3470 array( 'page_namespace' => $this->getNamespace(),
3471 'page_title' => $this->getDBkey(),
3473 'page_latest != rev_id'
3476 array( 'FOR UPDATE' )
3478 # Return true if there was no history
3479 return ( $row === false );
3483 * Checks if $this can be moved to a given Title
3484 * - Selects for update, so don't call it unless you mean business
3486 * @param $nt \type{Title} the new title to check
3487 * @return \type{\bool} TRUE or FALSE
3489 public function isValidMoveTarget( $nt ) {
3490 # Is it an existing file?
3491 if ( $nt->getNamespace() == NS_FILE
) {
3492 $file = wfLocalFile( $nt );
3493 if ( $file->exists() ) {
3494 wfDebug( __METHOD__
. ": file exists\n" );
3498 # Is it a redirect with no history?
3499 if ( !$nt->isSingleRevRedirect() ) {
3500 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3503 # Get the article text
3504 $rev = Revision
::newFromTitle( $nt );
3505 $text = $rev->getText();
3506 # Does the redirect point to the source?
3507 # Or is it a broken self-redirect, usually caused by namespace collisions?
3509 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3510 $redirTitle = Title
::newFromText( $m[1] );
3511 if ( !is_object( $redirTitle ) ||
3512 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3513 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3514 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3519 wfDebug( __METHOD__
. ": failsafe\n" );
3526 * Can this title be added to a user's watchlist?
3528 * @return \type{\bool} TRUE or FALSE
3530 public function isWatchable() {
3531 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3535 * Get categories to which this Title belongs and return an array of
3536 * categories' names.
3538 * @return \type{\array} array an array of parents in the form:
3539 * $parent => $currentarticle
3541 public function getParentCategories() {
3544 $titlekey = $this->getArticleId();
3545 $dbr = wfGetDB( DB_SLAVE
);
3546 $categorylinks = $dbr->tableName( 'categorylinks' );
3549 $sql = "SELECT * FROM $categorylinks"
3550 . " WHERE cl_from='$titlekey'"
3551 . " AND cl_from <> '0'"
3552 . " ORDER BY cl_sortkey";
3554 $res = $dbr->query( $sql );
3557 if ( $dbr->numRows( $res ) > 0 ) {
3558 foreach ( $res as $row ) {
3559 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3560 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3567 * Get a tree of parent categories
3569 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3570 * @return \type{\array} Tree of parent categories
3572 public function getParentCategoryTree( $children = array() ) {
3574 $parents = $this->getParentCategories();
3577 foreach ( $parents as $parent => $current ) {
3578 if ( array_key_exists( $parent, $children ) ) {
3579 # Circular reference
3580 $stack[$parent] = array();
3582 $nt = Title
::newFromText( $parent );
3584 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3595 * Get an associative array for selecting this title from
3598 * @return \type{\array} Selection array
3600 public function pageCond() {
3601 if ( $this->mArticleID
> 0 ) {
3602 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3603 return array( 'page_id' => $this->mArticleID
);
3605 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3610 * Get the revision ID of the previous revision
3612 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3613 * @param $flags \type{\int} GAID_FOR_UPDATE
3614 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3616 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3617 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3618 return $db->selectField( 'revision', 'rev_id',
3620 'rev_page' => $this->getArticleId( $flags ),
3621 'rev_id < ' . intval( $revId )
3624 array( 'ORDER BY' => 'rev_id DESC' )
3629 * Get the revision ID of the next revision
3631 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3632 * @param $flags \type{\int} GAID_FOR_UPDATE
3633 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3635 public function getNextRevisionID( $revId, $flags = 0 ) {
3636 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3637 return $db->selectField( 'revision', 'rev_id',
3639 'rev_page' => $this->getArticleId( $flags ),
3640 'rev_id > ' . intval( $revId )
3643 array( 'ORDER BY' => 'rev_id' )
3648 * Get the first revision of the page
3650 * @param $flags \type{\int} GAID_FOR_UPDATE
3651 * @return Revision (or NULL if page doesn't exist)
3653 public function getFirstRevision( $flags = 0 ) {
3654 $db = ( $flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3655 $pageId = $this->getArticleId( $flags );
3659 $row = $db->selectRow( 'revision', '*',
3660 array( 'rev_page' => $pageId ),
3662 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3667 return new Revision( $row );
3672 * Check if this is a new page
3676 public function isNewPage() {
3677 $dbr = wfGetDB( DB_SLAVE
);
3678 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3682 * Get the oldest revision timestamp of this page
3684 * @return String: MW timestamp
3686 public function getEarliestRevTime() {
3687 $dbr = wfGetDB( DB_SLAVE
);
3688 if ( $this->exists() ) {
3689 $min = $dbr->selectField( 'revision',
3690 'MIN(rev_timestamp)',
3691 array( 'rev_page' => $this->getArticleId() ),
3693 return wfTimestampOrNull( TS_MW
, $min );
3699 * Get the number of revisions between the given revision IDs.
3700 * Used for diffs and other things that really need it.
3702 * @param $old \type{\int} Revision ID.
3703 * @param $new \type{\int} Revision ID.
3704 * @return \type{\int} Number of revisions between these IDs.
3706 public function countRevisionsBetween( $old, $new ) {
3707 $dbr = wfGetDB( DB_SLAVE
);
3708 return (int)$dbr->selectField( 'revision', 'count(*)',
3709 'rev_page = ' . intval( $this->getArticleId() ) .
3710 ' AND rev_id > ' . intval( $old ) .
3711 ' AND rev_id < ' . intval( $new ),
3717 * Compare with another title.
3719 * @param $title \type{Title}
3720 * @return \type{\bool} TRUE or FALSE
3722 public function equals( Title
$title ) {
3723 // Note: === is necessary for proper matching of number-like titles.
3724 return $this->getInterwiki() === $title->getInterwiki()
3725 && $this->getNamespace() == $title->getNamespace()
3726 && $this->getDBkey() === $title->getDBkey();
3730 * Callback for usort() to do title sorts by (namespace, title)
3732 * @return Integer: result of string comparison, or namespace comparison
3734 public static function compare( $a, $b ) {
3735 if ( $a->getNamespace() == $b->getNamespace() ) {
3736 return strcmp( $a->getText(), $b->getText() );
3738 return $a->getNamespace() - $b->getNamespace();
3743 * Return a string representation of this title
3745 * @return \type{\string} String representation of this title
3747 public function __toString() {
3748 return $this->getPrefixedText();
3752 * Check if page exists. For historical reasons, this function simply
3753 * checks for the existence of the title in the page table, and will
3754 * thus return false for interwiki links, special pages and the like.
3755 * If you want to know if a title can be meaningfully viewed, you should
3756 * probably call the isKnown() method instead.
3758 * @return \type{\bool}
3760 public function exists() {
3761 return $this->getArticleId() != 0;
3765 * Should links to this title be shown as potentially viewable (i.e. as
3766 * "bluelinks"), even if there's no record by this title in the page
3769 * This function is semi-deprecated for public use, as well as somewhat
3770 * misleadingly named. You probably just want to call isKnown(), which
3771 * calls this function internally.
3773 * (ISSUE: Most of these checks are cheap, but the file existence check
3774 * can potentially be quite expensive. Including it here fixes a lot of
3775 * existing code, but we might want to add an optional parameter to skip
3776 * it and any other expensive checks.)
3778 * @return \type{\bool}
3780 public function isAlwaysKnown() {
3781 if ( $this->mInterwiki
!= '' ) {
3782 return true; // any interwiki link might be viewable, for all we know
3784 switch( $this->mNamespace
) {
3787 return (bool)wfFindFile( $this ); // file exists, possibly in a foreign repo
3789 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3791 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3793 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3794 // the full l10n of that language to be loaded. That takes much memory and
3795 // isn't needed. So we strip the language part away.
3796 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3797 return (bool)wfMsgWeirdKey( $basename ); // known system message
3804 * Does this title refer to a page that can (or might) be meaningfully
3805 * viewed? In particular, this function may be used to determine if
3806 * links to the title should be rendered as "bluelinks" (as opposed to
3807 * "redlinks" to non-existent pages).
3809 * @return \type{\bool}
3811 public function isKnown() {
3812 return $this->isAlwaysKnown() ||
$this->exists();
3816 * Does this page have source text?
3820 public function hasSourceText() {
3821 if ( $this->exists() ) {
3825 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3826 // If the page doesn't exist but is a known system message, default
3827 // message content will be displayed, same for language subpages
3828 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3829 // causes the full l10n of that language to be loaded. That takes much
3830 // memory and isn't needed. So we strip the language part away.
3831 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3832 return (bool)wfMsgWeirdKey( $basename );
3839 * Is this in a namespace that allows actual pages?
3841 * @return \type{\bool}
3842 * @internal note -- uses hardcoded namespace index instead of constants
3844 public function canExist() {
3845 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3849 * Update page_touched timestamps and send squid purge messages for
3850 * pages linking to this title. May be sent to the job queue depending
3851 * on the number of links. Typically called on create and delete.
3853 public function touchLinks() {
3854 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3857 if ( $this->getNamespace() == NS_CATEGORY
) {
3858 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3864 * Get the last touched timestamp
3866 * @param $db DatabaseBase: optional db
3867 * @return \type{\string} Last touched timestamp
3869 public function getTouched( $db = null ) {
3870 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
3871 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3876 * Get the timestamp when this page was updated since the user last saw it.
3879 * @return Mixed: string/null
3881 public function getNotificationTimestamp( $user = null ) {
3882 global $wgUser, $wgShowUpdatedMarker;
3883 // Assume current user if none given
3887 // Check cache first
3888 $uid = $user->getId();
3889 if ( isset( $this->mNotificationTimestamp
[$uid] ) ) {
3890 return $this->mNotificationTimestamp
[$uid];
3892 if ( !$uid ||
!$wgShowUpdatedMarker ) {
3893 return $this->mNotificationTimestamp
[$uid] = false;
3895 // Don't cache too much!
3896 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3897 $this->mNotificationTimestamp
= array();
3899 $dbr = wfGetDB( DB_SLAVE
);
3900 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3901 'wl_notificationtimestamp',
3902 array( 'wl_namespace' => $this->getNamespace(),
3903 'wl_title' => $this->getDBkey(),
3904 'wl_user' => $user->getId()
3908 return $this->mNotificationTimestamp
[$uid];
3912 * Get the trackback URL for this page
3914 * @return \type{\string} Trackback URL
3916 public function trackbackURL() {
3917 global $wgScriptPath, $wgServer, $wgScriptExtension;
3919 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3920 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3924 * Get the trackback RDF for this page
3926 * @return \type{\string} Trackback RDF
3928 public function trackbackRDF() {
3929 $url = htmlspecialchars( $this->getFullURL() );
3930 $title = htmlspecialchars( $this->getText() );
3931 $tburl = $this->trackbackURL();
3933 // Autodiscovery RDF is placed in comments so HTML validator
3934 // won't barf. This is a rather icky workaround, but seems
3935 // frequently used by this kind of RDF thingy.
3937 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3939 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3940 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3941 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3944 dc:identifier=\"$url\"
3946 trackback:ping=\"$tburl\" />
3952 * Generate strings used for xml 'id' names in monobook tabs
3954 * @param $prepend string defaults to 'nstab-'
3955 * @return \type{\string} XML 'id' name
3957 public function getNamespaceKey( $prepend = 'nstab-' ) {
3959 // Gets the subject namespace if this title
3960 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3961 // Checks if cononical namespace name exists for namespace
3962 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3963 // Uses canonical namespace name
3964 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3966 // Uses text of namespace
3967 $namespaceKey = $this->getSubjectNsText();
3969 // Makes namespace key lowercase
3970 $namespaceKey = $wgContLang->lc( $namespaceKey );
3972 if ( $namespaceKey == '' ) {
3973 $namespaceKey = 'main';
3975 // Changes file to image for backwards compatibility
3976 if ( $namespaceKey == 'file' ) {
3977 $namespaceKey = 'image';
3979 return $prepend . $namespaceKey;
3983 * Returns true if this is a special page.
3987 public function isSpecialPage() {
3988 return $this->getNamespace() == NS_SPECIAL
;
3992 * Returns true if this title resolves to the named special page
3994 * @param $name \type{\string} The special page name
3997 public function isSpecial( $name ) {
3998 if ( $this->getNamespace() == NS_SPECIAL
) {
3999 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
4000 if ( $name == $thisName ) {
4008 * If the Title refers to a special page alias which is not the local default,
4010 * @return \type{Title} A new Title which points to the local default.
4011 * Otherwise, returns $this.
4013 public function fixSpecialName() {
4014 if ( $this->getNamespace() == NS_SPECIAL
) {
4015 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
4016 if ( $canonicalName ) {
4017 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
4018 if ( $localName != $this->mDbkeyform
) {
4019 return Title
::makeTitle( NS_SPECIAL
, $localName );
4027 * Is this Title in a namespace which contains content?
4028 * In other words, is this a content page, for the purposes of calculating
4031 * @return \type{\bool}
4033 public function isContentPage() {
4034 return MWNamespace
::isContent( $this->getNamespace() );
4038 * Get all extant redirects to this Title
4040 * @param $ns \twotypes{\int,\null} Single namespace to consider;
4041 * NULL to consider all namespaces
4042 * @return \type{\arrayof{Title}} Redirects to this title
4044 public function getRedirectsHere( $ns = null ) {
4047 $dbr = wfGetDB( DB_SLAVE
);
4049 'rd_namespace' => $this->getNamespace(),
4050 'rd_title' => $this->getDBkey(),
4053 if ( !is_null( $ns ) ) {
4054 $where['page_namespace'] = $ns;
4057 $res = $dbr->select(
4058 array( 'redirect', 'page' ),
4059 array( 'page_namespace', 'page_title' ),
4064 foreach ( $res as $row ) {
4065 $redirs[] = self
::newFromRow( $row );
4071 * Check if this Title is a valid redirect target
4073 * @return \type{\bool}
4075 public function isValidRedirectTarget() {
4076 global $wgInvalidRedirectTargets;
4078 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4079 if ( $this->isSpecial( 'Userlogout' ) ) {
4083 foreach ( $wgInvalidRedirectTargets as $target ) {
4084 if ( $this->isSpecial( $target ) ) {
4093 * Get a backlink cache object
4095 * @return object BacklinkCache
4097 function getBacklinkCache() {
4098 if ( is_null( $this->mBacklinkCache
) ) {
4099 $this->mBacklinkCache
= new BacklinkCache( $this );
4101 return $this->mBacklinkCache
;
4105 * Whether the magic words __INDEX__ and __NOINDEX__ function for
4110 public function canUseNoindex() {
4111 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4113 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4114 ?
$wgContentNamespaces
4115 : $wgExemptFromUserRobotsControl;
4117 return !in_array( $this->mNamespace
, $bannedNamespaces );
4122 * Returns restriction types for the current Title
4124 * @return array applicable restriction types
4126 public function getRestrictionTypes() {
4127 global $wgRestrictionTypes;
4128 $types = $this->exists() ?
$wgRestrictionTypes : array( 'create' );
4130 if ( $this->getNamespace() == NS_FILE
) {
4131 $types[] = 'upload';
4134 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4140 * Returns the raw sort key to be used for categories, with the specified
4141 * prefix. This will be fed to Language::convertToSortkey() to get a
4142 * binary sortkey that can be used for actual sorting.
4144 * @param $prefix string The prefix to be used, specified using
4145 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4149 public function getCategorySortkey( $prefix = '' ) {
4150 $unprefixed = $this->getText();
4151 if ( $prefix !== '' ) {
4152 # Separate with a null byte, so the unprefixed part is only used as
4153 # a tiebreaker when two pages have the exact same prefix -- null
4154 # sorts before everything else (hopefully).
4155 return "$prefix\0$unprefixed";