7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
14 * Title::newFromText maintains a cache to avoid expensive re-normalization of
15 * commonly used titles. On a batch operation this can become a memory leak
16 * if not bounded. After hitting this many titles reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
21 * Constants for pr_cascade bitfield
23 define( 'CASCADE', 1 );
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
32 /** @name Static cache variables */
34 static private $titleCache=array();
35 static private $interwikiCache=array();
39 * @name Private member variables
40 * Please use the accessor functions instead.
45 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
46 var $mUrlform = ''; ///< URL-encoded form of the main part
47 var $mDbkeyform = ''; ///< Main part with underscores
48 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
49 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
50 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
51 var $mFragment; ///< Title fragment (i.e. the bit after the #)
52 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
53 var $mLatestID = false; ///< ID of most recent revision
54 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
55 var $mOldRestrictions = false;
56 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
57 var $mRestrictionsExpiry; ///< When do the restrictions on this page expire?
58 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
59 var $mCascadeRestrictionSources; ///< Where are the cascading restrictions coming from on this page?
60 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
61 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
62 # Don't change the following default, NS_MAIN is hardcoded in several
63 # places. See bug 696.
64 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
65 # Zero except in {{transclusion}} tags
66 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
67 var $mLength = -1; ///< The page length, 0 for special pages
68 var $mRedirect = null; ///< Is the article at this title a redirect?
76 /* private */ function __construct() {}
79 * Create a new Title from a prefixed DB key
80 * @param $key \type{\string} The database key, which has underscores
81 * instead of spaces, possibly including namespace and
83 * @return \type{Title} the new object, or NULL on an error
85 public static function newFromDBkey( $key ) {
87 $t->mDbkeyform
= $key;
88 if( $t->secureAndSplit() )
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
98 * @param $text \type{\string} the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
101 * @param $defaultNamespace \type{\int} the namespace to use if
102 * none is specified by a prefix
103 * @return \type{Title} the new object, or NULL on an error
105 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
106 if( is_object( $text ) ) {
107 throw new MWException( 'Title::newFromText given an object' );
111 * Wiki pages often contain multiple links to the same page.
112 * Title normalization and parsing can become expensive on
113 * pages with many links, so we can save a little time by
116 * In theory these are value objects and won't get changed...
118 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
119 return Title
::$titleCache[$text];
123 * Convert things like é ā or 〗 into real text...
125 $filteredText = Sanitizer
::decodeCharReferences( $text );
128 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
129 $t->mDefaultNamespace
= $defaultNamespace;
131 static $cachedcount = 0 ;
132 if( $t->secureAndSplit() ) {
133 if( $defaultNamespace == NS_MAIN
) {
134 if( $cachedcount >= MW_TITLECACHE_MAX
) {
135 # Avoid memory leaks on mass operations...
136 Title
::$titleCache = array();
140 Title
::$titleCache[$text] =& $t;
150 * Create a new Title from URL-encoded text. Ensures that
151 * the given title's length does not exceed the maximum.
152 * @param $url \type{\string} the title, as might be taken from a URL
153 * @return \type{Title} the new object, or NULL on an error
155 public static function newFromURL( $url ) {
156 global $wgLegalTitleChars;
159 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
160 # but some URLs used it as a space replacement and they still come
161 # from some external search tools.
162 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
163 $url = str_replace( '+', ' ', $url );
166 $t->mDbkeyform
= str_replace( ' ', '_', $url );
167 if( $t->secureAndSplit() ) {
175 * Create a new Title from an article ID
177 * @todo This is inefficiently implemented, the page row is requested
178 * but not used for anything else
180 * @param $id \type{\int} the page_id corresponding to the Title to create
181 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
182 * @return \type{Title} the new object, or NULL on an error
184 public static function newFromID( $id, $flags = 0 ) {
185 $fname = 'Title::newFromID';
186 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
187 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
188 array( 'page_id' => $id ), $fname );
189 if ( $row !== false ) {
190 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
198 * Make an array of titles from an array of IDs
199 * @param $ids \arrayof{\int} Array of IDs
200 * @return \arrayof{Title} Array of Titles
202 public static function newFromIDs( $ids ) {
203 if ( !count( $ids ) ) {
206 $dbr = wfGetDB( DB_SLAVE
);
207 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
208 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
211 foreach( $res as $row ) {
212 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
218 * Make a Title object from a DB row
219 * @param $row \type{Row} (needs at least page_title,page_namespace)
220 * @return \type{Title} corresponding Title
222 public static function newFromRow( $row ) {
223 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
225 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
226 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
227 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
228 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
234 * Create a new Title from a namespace index and a DB key.
235 * It's assumed that $ns and $title are *valid*, for instance when
236 * they came directly from the database or a special page name.
237 * For convenience, spaces are converted to underscores so that
238 * eg user_text fields can be used directly.
240 * @param $ns \type{\int} the namespace of the article
241 * @param $title \type{\string} the unprefixed database key form
242 * @param $fragment \type{\string} The link fragment (after the "#")
243 * @return \type{Title} the new object
245 public static function &makeTitle( $ns, $title, $fragment = '' ) {
248 $t->mFragment
= $fragment;
249 $t->mNamespace
= $ns = intval( $ns );
250 $t->mDbkeyform
= str_replace( ' ', '_', $title );
251 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
252 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
253 $t->mTextform
= str_replace( '_', ' ', $title );
258 * Create a new Title from a namespace index and a DB key.
259 * The parameters will be checked for validity, which is a bit slower
260 * than makeTitle() but safer for user-provided data.
262 * @param $ns \type{\int} the namespace of the article
263 * @param $title \type{\string} the database key form
264 * @param $fragment \type{\string} The link fragment (after the "#")
265 * @return \type{Title} the new object, or NULL on an error
267 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
269 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
270 if( $t->secureAndSplit() ) {
278 * Create a new Title for the Main Page
279 * @return \type{Title} the new object
281 public static function newMainPage() {
282 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
283 // Don't give fatal errors if the message is broken
285 $title = Title
::newFromText( 'Main Page' );
291 * Extract a redirect destination from a string and return the
292 * Title, or null if the text doesn't contain a valid redirect
294 * @param $text \type{String} Text with possible redirect
295 * @return \type{Title} The corresponding Title
297 public static function newFromRedirect( $text ) {
298 $redir = MagicWord
::get( 'redirect' );
300 if( $redir->matchStartAndRemove( $text ) ) {
301 // Extract the first link and see if it's usable
302 // Ensure that it really does come directly after #REDIRECT
303 // Some older redirects included a colon, so don't freak about that!
305 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
306 // Strip preceding colon used to "escape" categories, etc.
307 // and URL-decode links
308 if( strpos( $m[1], '%' ) !== false ) {
309 // Match behavior of inline link parsing here;
310 // don't interpret + as " " most of the time!
311 // It might be safe to just use rawurldecode instead, though.
312 $m[1] = urldecode( ltrim( $m[1], ':' ) );
314 $title = Title
::newFromText( $m[1] );
315 // Redirects to Special:Userlogout are not permitted
316 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
323 #----------------------------------------------------------------------------
325 #----------------------------------------------------------------------------
328 * Get the prefixed DB key associated with an ID
329 * @param $id \type{\int} the page_id of the article
330 * @return \type{Title} an object representing the article, or NULL
331 * if no such article was found
333 public static function nameOf( $id ) {
334 $dbr = wfGetDB( DB_SLAVE
);
336 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
337 if ( $s === false ) { return NULL; }
339 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
344 * Get a regex character class describing the legal characters in a link
345 * @return \type{\string} the list of characters, not delimited
347 public static function legalChars() {
348 global $wgLegalTitleChars;
349 return $wgLegalTitleChars;
353 * Get a string representation of a title suitable for
354 * including in a search index
356 * @param $ns \type{\int} a namespace index
357 * @param $title \type{\string} text-form main part
358 * @return \type{\string} a stripped-down title string ready for the
361 public static function indexTitle( $ns, $title ) {
364 $lc = SearchEngine
::legalSearchChars() . '&#;';
365 $t = $wgContLang->stripForSearch( $title );
366 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
367 $t = $wgContLang->lc( $t );
370 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
371 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
373 $t = preg_replace( "/\\s+/", ' ', $t );
375 if ( $ns == NS_IMAGE
) {
376 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
382 * Make a prefixed DB key from a DB key and a namespace index
383 * @param $ns \type{\int} numerical representation of the namespace
384 * @param $title \type{\string} the DB key form the title
385 * @param $fragment \type{\string} The link fragment (after the "#")
386 * @return \type{\string} the prefixed form of the title
388 public static function makeName( $ns, $title, $fragment = '' ) {
391 $namespace = $wgContLang->getNsText( $ns );
392 $name = $namespace == '' ?
$title : "$namespace:$title";
393 if ( strval( $fragment ) != '' ) {
394 $name .= '#' . $fragment;
400 * Returns the URL associated with an interwiki prefix
401 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
402 * @return \type{\string} the associated URL, containing "$1",
403 * which should be replaced by an article title
406 public function getInterwikiLink( $key ) {
407 global $wgMemc, $wgInterwikiExpiry;
408 global $wgInterwikiCache, $wgContLang;
409 $fname = 'Title::getInterwikiLink';
411 $key = $wgContLang->lc( $key );
413 $k = wfMemcKey( 'interwiki', $key );
414 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
415 return Title
::$interwikiCache[$k]->iw_url
;
418 if ($wgInterwikiCache) {
419 return Title
::getInterwikiCached( $key );
422 $s = $wgMemc->get( $k );
423 # Ignore old keys with no iw_local
424 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
425 Title
::$interwikiCache[$k] = $s;
429 $dbr = wfGetDB( DB_SLAVE
);
430 $res = $dbr->select( 'interwiki',
431 array( 'iw_url', 'iw_local', 'iw_trans' ),
432 array( 'iw_prefix' => $key ), $fname );
437 $s = $dbr->fetchObject( $res );
439 # Cache non-existence: create a blank object and save it to memcached
445 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
446 Title
::$interwikiCache[$k] = $s;
452 * Fetch interwiki prefix data from local cache in constant database.
454 * @note More logic is explained in DefaultSettings.
456 * @param $key \type{\string} Database key
457 * @return \type{\string} URL of interwiki site
459 public static function getInterwikiCached( $key ) {
460 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
464 $db=dba_open($wgInterwikiCache,'r','cdb');
465 /* Resolve site name */
466 if ($wgInterwikiScopes>=3 and !$site) {
467 $site = dba_fetch('__sites:' . wfWikiID(), $db);
469 $site = $wgInterwikiFallbackSite;
471 $value = dba_fetch( wfMemcKey( $key ), $db);
472 if ($value=='' and $wgInterwikiScopes>=3) {
474 $value = dba_fetch("_{$site}:{$key}", $db);
476 if ($value=='' and $wgInterwikiScopes>=2) {
478 $value = dba_fetch("__global:{$key}", $db);
487 list($local,$url)=explode(' ',$value,2);
489 $s->iw_local
=(int)$local;
491 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
496 * Determine whether the object refers to a page within
499 * @return \type{\bool} TRUE if this is an in-project interwiki link
500 * or a wikilink, FALSE otherwise
502 public function isLocal() {
503 if ( $this->mInterwiki
!= '' ) {
504 # Make sure key is loaded into cache
505 $this->getInterwikiLink( $this->mInterwiki
);
506 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
507 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
514 * Determine whether the object refers to a page within
515 * this project and is transcludable.
517 * @return \type{\bool} TRUE if this is transcludable
519 public function isTrans() {
520 if ($this->mInterwiki
== '')
522 # Make sure key is loaded into cache
523 $this->getInterwikiLink( $this->mInterwiki
);
524 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
525 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
529 * Escape a text fragment, say from a link, for a URL
531 static function escapeFragmentForURL( $fragment ) {
532 $fragment = str_replace( ' ', '_', $fragment );
533 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
534 $replaceArray = array(
538 return strtr( $fragment, $replaceArray );
541 #----------------------------------------------------------------------------
543 #----------------------------------------------------------------------------
545 /** Simple accessors */
547 * Get the text form (spaces not underscores) of the main part
548 * @return \type{\string} Main part of the title
550 public function getText() { return $this->mTextform
; }
552 * Get the URL-encoded form of the main part
553 * @return \type{\string} Main part of the title, URL-encoded
555 public function getPartialURL() { return $this->mUrlform
; }
557 * Get the main part with underscores
558 * @return \type{\string} Main part of the title, with underscores
560 public function getDBkey() { return $this->mDbkeyform
; }
562 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
563 * @return \type{\int} Namespace index
565 public function getNamespace() { return $this->mNamespace
; }
567 * Get the namespace text
568 * @return \type{\string} Namespace text
570 public function getNsText() {
571 global $wgContLang, $wgCanonicalNamespaceNames;
573 if ( '' != $this->mInterwiki
) {
574 // This probably shouldn't even happen. ohh man, oh yuck.
575 // But for interwiki transclusion it sometimes does.
576 // Shit. Shit shit shit.
578 // Use the canonical namespaces if possible to try to
579 // resolve a foreign namespace.
580 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
581 return $wgCanonicalNamespaceNames[$this->mNamespace
];
584 return $wgContLang->getNsText( $this->mNamespace
);
587 * Get the DB key with the initial letter case as specified by the user
588 * @return \type{\string} DB key
590 function getUserCaseDBKey() {
591 return $this->mUserCaseDBKey
;
594 * Get the namespace text of the subject (rather than talk) page
595 * @return \type{\string} Namespace text
597 public function getSubjectNsText() {
599 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
602 * Get the namespace text of the talk page
603 * @return \type{\string} Namespace text
605 public function getTalkNsText() {
607 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
610 * Could this title have a corresponding talk page?
611 * @return \type{\bool} TRUE or FALSE
613 public function canTalk() {
614 return( MWNamespace
::canTalk( $this->mNamespace
) );
617 * Get the interwiki prefix (or null string)
618 * @return \type{\string} Interwiki prefix
620 public function getInterwiki() { return $this->mInterwiki
; }
622 * Get the Title fragment (i.e.\ the bit after the #) in text form
623 * @return \type{\string} Title fragment
625 public function getFragment() { return $this->mFragment
; }
627 * Get the fragment in URL form, including the "#" character if there is one
628 * @return \type{\string} Fragment in URL form
630 public function getFragmentForURL() {
631 if ( $this->mFragment
== '' ) {
634 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
638 * Get the default namespace index, for when there is no namespace
639 * @return \type{\int} Default namespace index
641 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
644 * Get title for search index
645 * @return \type{\string} a stripped-down title string ready for the
648 public function getIndexTitle() {
649 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
653 * Get the prefixed database key form
654 * @return \type{\string} the prefixed title, with underscores and
655 * any interwiki and namespace prefixes
657 public function getPrefixedDBkey() {
658 $s = $this->prefix( $this->mDbkeyform
);
659 $s = str_replace( ' ', '_', $s );
664 * Get the prefixed title with spaces.
665 * This is the form usually used for display
666 * @return \type{\string} the prefixed title, with spaces
668 public function getPrefixedText() {
669 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
670 $s = $this->prefix( $this->mTextform
);
671 $s = str_replace( '_', ' ', $s );
672 $this->mPrefixedText
= $s;
674 return $this->mPrefixedText
;
678 * Get the prefixed title with spaces, plus any fragment
679 * (part beginning with '#')
680 * @return \type{\string} the prefixed title, with spaces and
681 * the fragment, including '#'
683 public function getFullText() {
684 $text = $this->getPrefixedText();
685 if( '' != $this->mFragment
) {
686 $text .= '#' . $this->mFragment
;
692 * Get the base name, i.e. the leftmost parts before the /
693 * @return \type{\string} Base name
695 public function getBaseText() {
696 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
697 return $this->getText();
700 $parts = explode( '/', $this->getText() );
701 # Don't discard the real title if there's no subpage involved
702 if( count( $parts ) > 1 )
703 unset( $parts[ count( $parts ) - 1 ] );
704 return implode( '/', $parts );
708 * Get the lowest-level subpage name, i.e. the rightmost part after /
709 * @return \type{\string} Subpage name
711 public function getSubpageText() {
712 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
713 return( $this->mTextform
);
715 $parts = explode( '/', $this->mTextform
);
716 return( $parts[ count( $parts ) - 1 ] );
720 * Get a URL-encoded form of the subpage text
721 * @return \type{\string} URL-encoded subpage name
723 public function getSubpageUrlForm() {
724 $text = $this->getSubpageText();
725 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
726 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
731 * Get a URL-encoded title (not an actual URL) including interwiki
732 * @return \type{\string} the URL-encoded form
734 public function getPrefixedURL() {
735 $s = $this->prefix( $this->mDbkeyform
);
736 $s = str_replace( ' ', '_', $s );
738 $s = wfUrlencode ( $s ) ;
740 # Cleaning up URL to make it look nice -- is this safe?
741 $s = str_replace( '%28', '(', $s );
742 $s = str_replace( '%29', ')', $s );
748 * Get a real URL referring to this title, with interwiki link and
751 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
752 * links. Can be specified as an associative array as well, e.g.,
753 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
754 * @param $variant \type{\string} language variant of url (for sr, zh..)
755 * @return \type{\string} the URL
757 public function getFullURL( $query = '', $variant = false ) {
758 global $wgContLang, $wgServer, $wgRequest;
760 if( is_array( $query ) ) {
761 $query = wfArrayToCGI( $query );
764 if ( '' == $this->mInterwiki
) {
765 $url = $this->getLocalUrl( $query, $variant );
767 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
768 // Correct fix would be to move the prepending elsewhere.
769 if ($wgRequest->getVal('action') != 'render') {
770 $url = $wgServer . $url;
773 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
775 $namespace = wfUrlencode( $this->getNsText() );
776 if ( '' != $namespace ) {
777 # Can this actually happen? Interwikis shouldn't be parsed.
778 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
781 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
782 $url = wfAppendQuery( $url, $query );
785 # Finally, add the fragment.
786 $url .= $this->getFragmentForURL();
788 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
793 * Get a URL with no fragment or server name. If this page is generated
794 * with action=render, $wgServer is prepended.
795 * @param mixed $query an optional query string; if not specified,
796 * $wgArticlePath will be used. Can be specified as an associative array
797 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
799 * @param $variant \type{\string} language variant of url (for sr, zh..)
800 * @return \type{\string} the URL
802 public function getLocalURL( $query = '', $variant = false ) {
803 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
804 global $wgVariantArticlePath, $wgContLang, $wgUser;
806 if( is_array( $query ) ) {
807 $query = wfArrayToCGI( $query );
810 // internal links should point to same variant as current page (only anonymous users)
811 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
812 $pref = $wgContLang->getPreferredVariant(false);
813 if($pref != $wgContLang->getCode())
817 if ( $this->isExternal() ) {
818 $url = $this->getFullURL();
820 // This is currently only used for edit section links in the
821 // context of interwiki transclusion. In theory we should
822 // append the query to the end of any existing query string,
823 // but interwiki transclusion is already broken in that case.
827 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
828 if ( $query == '' ) {
829 if( $variant != false && $wgContLang->hasVariants() ) {
830 if( $wgVariantArticlePath == false ) {
831 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
833 $variantArticlePath = $wgVariantArticlePath;
835 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
836 $url = str_replace( '$1', $dbkey, $url );
838 $url = str_replace( '$1', $dbkey, $wgArticlePath );
841 global $wgActionPaths;
844 if( !empty( $wgActionPaths ) &&
845 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
847 $action = urldecode( $matches[2] );
848 if( isset( $wgActionPaths[$action] ) ) {
849 $query = $matches[1];
850 if( isset( $matches[4] ) ) $query .= $matches[4];
851 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
852 if( $query != '' ) $url .= '?' . $query;
855 if ( $url === false ) {
856 if ( $query == '-' ) {
859 $url = "{$wgScript}?title={$dbkey}&{$query}";
863 // FIXME: this causes breakage in various places when we
864 // actually expected a local URL and end up with dupe prefixes.
865 if ($wgRequest->getVal('action') == 'render') {
866 $url = $wgServer . $url;
869 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
874 * Get a URL that's the simplest URL that will be valid to link, locally,
875 * to the current Title. It includes the fragment, but does not include
876 * the server unless action=render is used (or the link is external). If
877 * there's a fragment but the prefixed text is empty, we just return a link
880 * @param $query \arrayof{\string} An associative array of key => value pairs for the
881 * query string. Keys and values will be escaped.
882 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
883 * for external links. Default is "false" (same variant as current page,
884 * for anonymous users).
885 * @return \type{\string} the URL
887 public function getLinkUrl( $query = array(), $variant = false ) {
888 if( !is_array( $query ) ) {
889 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
892 if( $this->isExternal() ) {
893 return $this->getFullURL( $query );
894 } elseif( $this->getPrefixedText() === ''
895 and $this->getFragment() !== '' ) {
896 return $this->getFragmentForURL();
898 return $this->getLocalURL( $query, $variant )
899 . $this->getFragmentForURL();
904 * Get an HTML-escaped version of the URL form, suitable for
905 * using in a link, without a server name or fragment
906 * @param $query \type{\string} an optional query string
907 * @return \type{\string} the URL
909 public function escapeLocalURL( $query = '' ) {
910 return htmlspecialchars( $this->getLocalURL( $query ) );
914 * Get an HTML-escaped version of the URL form, suitable for
915 * using in a link, including the server name and fragment
917 * @param $query \type{\string} an optional query string
918 * @return \type{\string} the URL
920 public function escapeFullURL( $query = '' ) {
921 return htmlspecialchars( $this->getFullURL( $query ) );
925 * Get the URL form for an internal link.
926 * - Used in various Squid-related code, in case we have a different
927 * internal hostname for the server from the exposed one.
929 * @param $query \type{\string} an optional query string
930 * @param $variant \type{\string} language variant of url (for sr, zh..)
931 * @return \type{\string} the URL
933 public function getInternalURL( $query = '', $variant = false ) {
934 global $wgInternalServer;
935 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
936 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
941 * Get the edit URL for this Title
942 * @return \type{\string} the URL, or a null string if this is an
945 public function getEditURL() {
946 if ( '' != $this->mInterwiki
) { return ''; }
947 $s = $this->getLocalURL( 'action=edit' );
953 * Get the HTML-escaped displayable text form.
954 * Used for the title field in <a> tags.
955 * @return \type{\string} the text, including any prefixes
957 public function getEscapedText() {
958 return htmlspecialchars( $this->getPrefixedText() );
962 * Is this Title interwiki?
963 * @return \type{\bool}
965 public function isExternal() { return ( '' != $this->mInterwiki
); }
968 * Is this page "semi-protected" - the *only* protection is autoconfirm?
970 * @param @action \type{\string} Action to check (default: edit)
971 * @return \type{\bool}
973 public function isSemiProtected( $action = 'edit' ) {
974 if( $this->exists() ) {
975 $restrictions = $this->getRestrictions( $action );
976 if( count( $restrictions ) > 0 ) {
977 foreach( $restrictions as $restriction ) {
978 if( strtolower( $restriction ) != 'autoconfirmed' )
987 # If it doesn't exist, it can't be protected
993 * Does the title correspond to a protected article?
994 * @param $what \type{\string} the action the page is protected from,
995 * by default checks move and edit
996 * @return \type{\bool}
998 public function isProtected( $action = '' ) {
999 global $wgRestrictionLevels, $wgRestrictionTypes;
1001 # Special pages have inherent protection
1002 if( $this->getNamespace() == NS_SPECIAL
)
1005 # Check regular protection levels
1006 foreach( $wgRestrictionTypes as $type ){
1007 if( $action == $type ||
$action == '' ) {
1008 $r = $this->getRestrictions( $type );
1009 foreach( $wgRestrictionLevels as $level ) {
1010 if( in_array( $level, $r ) && $level != '' ) {
1021 * Is $wgUser watching this page?
1022 * @return \type{\bool}
1024 public function userIsWatching() {
1027 if ( is_null( $this->mWatched
) ) {
1028 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1029 $this->mWatched
= false;
1031 $this->mWatched
= $wgUser->isWatched( $this );
1034 return $this->mWatched
;
1038 * Can $wgUser perform $action on this page?
1039 * This skips potentially expensive cascading permission checks.
1041 * Suitable for use for nonessential UI controls in common cases, but
1042 * _not_ for functional access control.
1044 * May provide false positives, but should never provide a false negative.
1046 * @param $action \type{\string} action that permission needs to be checked for
1047 * @return \type{\bool}
1049 public function quickUserCan( $action ) {
1050 return $this->userCan( $action, false );
1054 * Determines if $wgUser is unable to edit this page because it has been protected
1055 * by $wgNamespaceProtection.
1057 * @return \type{\bool}
1059 public function isNamespaceProtected() {
1060 global $wgNamespaceProtection, $wgUser;
1061 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1062 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1063 if( $right != '' && !$wgUser->isAllowed( $right ) )
1071 * Can $wgUser perform $action on this page?
1072 * @param \type{\string} $action action that permission needs to be checked for
1073 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1074 * @return \type{\bool}
1076 public function userCan( $action, $doExpensiveQueries = true ) {
1078 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1082 * Can $user perform $action on this page?
1084 * FIXME: This *does not* check throttles (User::pingLimiter()).
1086 * @param $action \type{\string}action that permission needs to be checked for
1087 * @param $user \type{User} user to check
1088 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1089 * @param $ignoreErrors \arrayof{\string} Set this to a list of message keys whose corresponding errors may be ignored.
1090 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1092 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1093 if( !StubObject
::isRealObject( $user ) ) {
1094 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1096 $wgUser->_unstub( '', 5 );
1099 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1103 global $wgEmailConfirmToEdit;
1105 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1106 $errors[] = array( 'confirmedittext' );
1109 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1110 $block = $user->mBlock
;
1112 // This is from OutputPage::blockedPage
1113 // Copied at r23888 by werdna
1115 $id = $user->blockedBy();
1116 $reason = $user->blockedFor();
1117 if( $reason == '' ) {
1118 $reason = wfMsg( 'blockednoreason' );
1122 if ( is_numeric( $id ) ) {
1123 $name = User
::whoIs( $id );
1128 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1129 $blockid = $block->mId
;
1130 $blockExpiry = $user->mBlock
->mExpiry
;
1131 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1133 if ( $blockExpiry == 'infinity' ) {
1134 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1135 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1137 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1138 if ( strpos( $option, ':' ) == false )
1141 list ($show, $value) = explode( ":", $option );
1143 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1144 $blockExpiry = $show;
1149 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1152 $intended = $user->mBlock
->mAddress
;
1154 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1155 $blockid, $blockExpiry, $intended, $blockTimestamp );
1158 // Remove the errors being ignored.
1160 foreach( $errors as $index => $error ) {
1161 $error_key = is_array($error) ?
$error[0] : $error;
1163 if (in_array( $error_key, $ignoreErrors )) {
1164 unset($errors[$index]);
1172 * Can $user perform $action on this page? This is an internal function,
1173 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1174 * checks on wfReadOnly() and blocks)
1176 * @param $action \type{\string} action that permission needs to be checked for
1177 * @param $user \type{User} user to check
1178 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1179 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1181 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1182 wfProfileIn( __METHOD__
);
1186 // Use getUserPermissionsErrors instead
1187 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1188 wfProfileOut( __METHOD__
);
1189 return $result ?
array() : array( array( 'badaccess-group0' ) );
1192 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1193 if ($result != array() && is_array($result) && !is_array($result[0]))
1194 $errors[] = $result; # A single array representing an error
1195 else if (is_array($result) && is_array($result[0]))
1196 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1197 else if ($result != '' && $result != null && $result !== true && $result !== false)
1198 $errors[] = array($result); # A string representing a message-id
1199 else if ($result === false )
1200 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1202 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1203 if ($result != array() && is_array($result) && !is_array($result[0]))
1204 $errors[] = $result; # A single array representing an error
1205 else if (is_array($result) && is_array($result[0]))
1206 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1207 else if ($result != '' && $result != null && $result !== true && $result !== false)
1208 $errors[] = array($result); # A string representing a message-id
1209 else if ($result === false )
1210 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1213 $specialOKActions = array( 'createaccount', 'execute' );
1214 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1215 $errors[] = array('ns-specialprotected');
1218 if ( $this->isNamespaceProtected() ) {
1219 $ns = $this->getNamespace() == NS_MAIN
1220 ?
wfMsg( 'nstab-main' )
1221 : $this->getNsText();
1222 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1223 ?
array('protectedinterface')
1224 : array( 'namespaceprotected', $ns ) );
1227 if( $this->mDbkeyform
== '_' ) {
1228 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1229 $errors[] = array('badaccess-group0');
1232 # protect css/js subpages of user pages
1233 # XXX: this might be better using restrictions
1234 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1235 if( $this->isCssJsSubpage()
1236 && !$user->isAllowed('editusercssjs')
1237 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1238 $errors[] = array('customcssjsprotected');
1241 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1242 # We /could/ use the protection level on the source page, but it's fairly ugly
1243 # as we have to establish a precedence hierarchy for pages included by multiple
1244 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1245 # as they could remove the protection anyway.
1246 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1247 # Cascading protection depends on more than this page...
1248 # Several cascading protected pages may include this page...
1249 # Check each cascading level
1250 # This is only for protection restrictions, not for all actions
1251 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1252 foreach( $restrictions[$action] as $right ) {
1253 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1254 if( '' != $right && !$user->isAllowed( $right ) ) {
1256 foreach( $cascadingSources as $page )
1257 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1258 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1264 foreach( $this->getRestrictions($action) as $right ) {
1265 // Backwards compatibility, rewrite sysop -> protect
1266 if ( $right == 'sysop' ) {
1269 if( '' != $right && !$user->isAllowed( $right ) ) {
1270 //Users with 'editprotected' permission can edit protected pages
1271 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1272 //Users with 'editprotected' permission cannot edit protected pages
1273 //with cascading option turned on.
1274 if($this->mCascadeRestriction
) {
1275 $errors[] = array( 'protectedpagetext', $right );
1277 //Nothing, user can edit!
1280 $errors[] = array( 'protectedpagetext', $right );
1285 if ($action == 'protect') {
1286 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1287 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1291 if ($action == 'create') {
1292 $title_protection = $this->getTitleProtection();
1294 if (is_array($title_protection)) {
1295 extract($title_protection);
1297 if ($pt_create_perm == 'sysop')
1298 $pt_create_perm = 'protect';
1300 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1301 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1305 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1306 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1307 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1309 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1310 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1311 } elseif ( !$user->isAllowed( $action ) ) {
1313 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1314 User
::getGroupsWithPermission( $action ) );
1316 $return = array( 'badaccess-groups',
1318 implode( ', ', $groups ),
1319 count( $groups ) ) );
1322 $return = array( "badaccess-group0" );
1324 $errors[] = $return;
1327 wfProfileOut( __METHOD__
);
1332 * Is this title subject to title protection?
1333 * @return \type{\mixed} An associative array representing any existent title
1334 * protection, or false if there's none.
1336 private function getTitleProtection() {
1337 // Can't protect pages in special namespaces
1338 if ( $this->getNamespace() < 0 ) {
1342 $dbr = wfGetDB( DB_SLAVE
);
1343 $res = $dbr->select( 'protected_titles', '*',
1344 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1346 if ($row = $dbr->fetchRow( $res )) {
1354 * Update the title protection status
1355 * @param $create_perm \type{\string} Permission required for creation
1356 * @param $reason \type{\string} Reason for protection
1357 * @param $expiry \type{\string} Expiry timestamp
1359 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1360 global $wgUser,$wgContLang;
1362 if ($create_perm == implode(',',$this->getRestrictions('create'))
1363 && $expiry == $this->mRestrictionsExpiry
) {
1368 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1370 $dbw = wfGetDB( DB_MASTER
);
1372 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1374 $expiry_description = '';
1375 if ( $encodedExpiry != 'infinity' ) {
1376 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1379 # Update protection table
1380 if ($create_perm != '' ) {
1381 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1382 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1383 , 'pt_create_perm' => $create_perm
1384 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1385 , 'pt_expiry' => $encodedExpiry
1386 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1388 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1389 'pt_title' => $title ), __METHOD__
);
1391 # Update the protection log
1392 $log = new LogPage( 'protect' );
1394 if( $create_perm ) {
1395 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1397 $log->addEntry( 'unprotect', $this, $reason );
1404 * Remove any title protection due to page existing
1406 public function deleteTitleProtection() {
1407 $dbw = wfGetDB( DB_MASTER
);
1409 $dbw->delete( 'protected_titles',
1410 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1414 * Can $wgUser edit this page?
1415 * @return \type{\bool} TRUE or FALSE
1416 * @deprecated use userCan('edit')
1418 public function userCanEdit( $doExpensiveQueries = true ) {
1419 return $this->userCan( 'edit', $doExpensiveQueries );
1423 * Can $wgUser create this page?
1424 * @return \type{\bool} TRUE or FALSE
1425 * @deprecated use userCan('create')
1427 public function userCanCreate( $doExpensiveQueries = true ) {
1428 return $this->userCan( 'create', $doExpensiveQueries );
1432 * Can $wgUser move this page?
1433 * @return \type{\bool} TRUE or FALSE
1434 * @deprecated use userCan('move')
1436 public function userCanMove( $doExpensiveQueries = true ) {
1437 return $this->userCan( 'move', $doExpensiveQueries );
1441 * Would anybody with sufficient privileges be able to move this page?
1442 * Some pages just aren't movable.
1444 * @return \type{\bool} TRUE or FALSE
1446 public function isMovable() {
1447 return MWNamespace
::isMovable( $this->getNamespace() )
1448 && $this->getInterwiki() == '';
1452 * Can $wgUser read this page?
1453 * @return \type{\bool} TRUE or FALSE
1454 * @todo fold these checks into userCan()
1456 public function userCanRead() {
1457 global $wgUser, $wgGroupPermissions;
1460 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1461 if ( $result !== null ) {
1465 # Shortcut for public wikis, allows skipping quite a bit of code
1466 if ($wgGroupPermissions['*']['read'])
1469 if( $wgUser->isAllowed( 'read' ) ) {
1472 global $wgWhitelistRead;
1475 * Always grant access to the login page.
1476 * Even anons need to be able to log in.
1478 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1483 * Bail out if there isn't whitelist
1485 if( !is_array($wgWhitelistRead) ) {
1490 * Check for explicit whitelisting
1492 $name = $this->getPrefixedText();
1493 $dbName = $this->getPrefixedDBKey();
1494 // Check with and without underscores
1495 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1499 * Old settings might have the title prefixed with
1500 * a colon for main-namespace pages
1502 if( $this->getNamespace() == NS_MAIN
) {
1503 if( in_array( ':' . $name, $wgWhitelistRead ) )
1508 * If it's a special page, ditch the subpage bit
1511 if( $this->getNamespace() == NS_SPECIAL
) {
1512 $name = $this->getDBkey();
1513 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1514 if ( $name === false ) {
1515 # Invalid special page, but we show standard login required message
1519 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1520 if( in_array( $pure, $wgWhitelistRead, true ) )
1529 * Is this a talk page of some sort?
1530 * @return \type{\bool} TRUE or FALSE
1532 public function isTalkPage() {
1533 return MWNamespace
::isTalk( $this->getNamespace() );
1537 * Is this a subpage?
1538 * @return \type{\bool} TRUE or FALSE
1540 public function isSubpage() {
1541 return MWNamespace
::hasSubpages( $this->mNamespace
)
1542 ?
strpos( $this->getText(), '/' ) !== false
1547 * Does this have subpages? (Warning, usually requires an extra DB query.)
1548 * @return \type{\bool} TRUE or FALSE
1550 public function hasSubpages() {
1551 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1556 # We dynamically add a member variable for the purpose of this method
1557 # alone to cache the result. There's no point in having it hanging
1558 # around uninitialized in every Title object; therefore we only add it
1559 # if needed and don't declare it statically.
1560 if( isset( $this->mHasSubpages
) ) {
1561 return $this->mHasSubpages
;
1564 $db = wfGetDB( DB_SLAVE
);
1565 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1566 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1567 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1573 * Could this page contain custom CSS or JavaScript, based
1576 * @return \type{\bool} TRUE or FALSE
1578 public function isCssOrJsPage() {
1579 return $this->mNamespace
== NS_MEDIAWIKI
1580 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1584 * Is this a .css or .js subpage of a user page?
1585 * @return \type{\bool} TRUE or FALSE
1587 public function isCssJsSubpage() {
1588 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1591 * Is this a *valid* .css or .js subpage of a user page?
1592 * Check that the corresponding skin exists
1593 * @return \type{\bool} TRUE or FALSE
1595 public function isValidCssJsSubpage() {
1596 if ( $this->isCssJsSubpage() ) {
1597 $skinNames = Skin
::getSkinNames();
1598 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1604 * Trim down a .css or .js subpage title to get the corresponding skin name
1606 public function getSkinFromCssJsSubpage() {
1607 $subpage = explode( '/', $this->mTextform
);
1608 $subpage = $subpage[ count( $subpage ) - 1 ];
1609 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1612 * Is this a .css subpage of a user page?
1613 * @return \type{\bool} TRUE or FALSE
1615 public function isCssSubpage() {
1616 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1619 * Is this a .js subpage of a user page?
1620 * @return \type{\bool} TRUE or FALSE
1622 public function isJsSubpage() {
1623 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1626 * Protect css/js subpages of user pages: can $wgUser edit
1629 * @return \type{\bool} TRUE or FALSE
1630 * @todo XXX: this might be better using restrictions
1632 public function userCanEditCssJsSubpage() {
1634 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1638 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1640 * @return \type{\bool} If the page is subject to cascading restrictions.
1642 public function isCascadeProtected() {
1643 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1644 return ( $sources > 0 );
1648 * Cascading protection: Get the source of any cascading restrictions on this page.
1650 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1651 * @return \arrayof{mixed title array, restriction array} Array of the Title objects of the pages from
1652 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1653 * The restriction array is an array of each type, each of which contains an array of unique groups.
1655 public function getCascadeProtectionSources( $get_pages = true ) {
1656 global $wgRestrictionTypes;
1658 # Define our dimension of restrictions types
1659 $pagerestrictions = array();
1660 foreach( $wgRestrictionTypes as $action )
1661 $pagerestrictions[$action] = array();
1663 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1664 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1665 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1666 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1669 wfProfileIn( __METHOD__
);
1671 $dbr = wfGetDb( DB_SLAVE
);
1673 if ( $this->getNamespace() == NS_IMAGE
) {
1674 $tables = array ('imagelinks', 'page_restrictions');
1675 $where_clauses = array(
1676 'il_to' => $this->getDBkey(),
1678 'pr_cascade' => 1 );
1680 $tables = array ('templatelinks', 'page_restrictions');
1681 $where_clauses = array(
1682 'tl_namespace' => $this->getNamespace(),
1683 'tl_title' => $this->getDBkey(),
1685 'pr_cascade' => 1 );
1689 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1690 $where_clauses[] = 'page_id=pr_page';
1693 $cols = array( 'pr_expiry' );
1696 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1698 $sources = $get_pages ?
array() : false;
1699 $now = wfTimestampNow();
1700 $purgeExpired = false;
1702 foreach( $res as $row ) {
1703 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1704 if( $expiry > $now ) {
1706 $page_id = $row->pr_page
;
1707 $page_ns = $row->page_namespace
;
1708 $page_title = $row->page_title
;
1709 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1710 # Add groups needed for each restriction type if its not already there
1711 # Make sure this restriction type still exists
1712 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1713 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1719 // Trigger lazy purge of expired restrictions from the db
1720 $purgeExpired = true;
1723 if( $purgeExpired ) {
1724 Title
::purgeExpiredRestrictions();
1727 wfProfileOut( __METHOD__
);
1730 $this->mCascadeSources
= $sources;
1731 $this->mCascadingRestrictions
= $pagerestrictions;
1733 $this->mHasCascadingRestrictions
= $sources;
1736 return array( $sources, $pagerestrictions );
1739 function areRestrictionsCascading() {
1740 if (!$this->mRestrictionsLoaded
) {
1741 $this->loadRestrictions();
1744 return $this->mCascadeRestriction
;
1748 * Loads a string into mRestrictions array
1749 * @param $res \type{Resource} restrictions as an SQL result.
1751 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1752 global $wgRestrictionTypes;
1753 $dbr = wfGetDB( DB_SLAVE
);
1755 foreach( $wgRestrictionTypes as $type ){
1756 $this->mRestrictions
[$type] = array();
1759 $this->mCascadeRestriction
= false;
1760 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1762 # Backwards-compatibility: also load the restrictions from the page record (old format).
1764 if ( $oldFashionedRestrictions === NULL ) {
1765 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1766 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1769 if ($oldFashionedRestrictions != '') {
1771 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1772 $temp = explode( '=', trim( $restrict ) );
1773 if(count($temp) == 1) {
1774 // old old format should be treated as edit/move restriction
1775 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1776 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1778 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1782 $this->mOldRestrictions
= true;
1786 if( $dbr->numRows( $res ) ) {
1787 # Current system - load second to make them override.
1788 $now = wfTimestampNow();
1789 $purgeExpired = false;
1791 foreach( $res as $row ) {
1792 # Cycle through all the restrictions.
1794 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1795 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1798 // This code should be refactored, now that it's being used more generally,
1799 // But I don't really see any harm in leaving it in Block for now -werdna
1800 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1802 // Only apply the restrictions if they haven't expired!
1803 if ( !$expiry ||
$expiry > $now ) {
1804 $this->mRestrictionsExpiry
= $expiry;
1805 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1807 $this->mCascadeRestriction |
= $row->pr_cascade
;
1809 // Trigger a lazy purge of expired restrictions
1810 $purgeExpired = true;
1814 if( $purgeExpired ) {
1815 Title
::purgeExpiredRestrictions();
1819 $this->mRestrictionsLoaded
= true;
1823 * Load restrictions from the page_restrictions table
1825 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1826 if( !$this->mRestrictionsLoaded
) {
1827 if ($this->exists()) {
1828 $dbr = wfGetDB( DB_SLAVE
);
1830 $res = $dbr->select( 'page_restrictions', '*',
1831 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1833 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1835 $title_protection = $this->getTitleProtection();
1837 if (is_array($title_protection)) {
1838 extract($title_protection);
1840 $now = wfTimestampNow();
1841 $expiry = Block
::decodeExpiry($pt_expiry);
1843 if (!$expiry ||
$expiry > $now) {
1844 // Apply the restrictions
1845 $this->mRestrictionsExpiry
= $expiry;
1846 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1847 } else { // Get rid of the old restrictions
1848 Title
::purgeExpiredRestrictions();
1851 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1853 $this->mRestrictionsLoaded
= true;
1859 * Purge expired restrictions from the page_restrictions table
1861 static function purgeExpiredRestrictions() {
1862 $dbw = wfGetDB( DB_MASTER
);
1863 $dbw->delete( 'page_restrictions',
1864 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1867 $dbw->delete( 'protected_titles',
1868 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1873 * Accessor/initialisation for mRestrictions
1875 * @param $action \type{\string} action that permission needs to be checked for
1876 * @return \arrayof{\string} the array of groups allowed to edit this article
1878 public function getRestrictions( $action ) {
1879 if( !$this->mRestrictionsLoaded
) {
1880 $this->loadRestrictions();
1882 return isset( $this->mRestrictions
[$action] )
1883 ?
$this->mRestrictions
[$action]
1888 * Is there a version of this page in the deletion archive?
1889 * @return \type{\int} the number of archived revisions
1891 public function isDeleted() {
1892 $fname = 'Title::isDeleted';
1893 if ( $this->getNamespace() < 0 ) {
1896 $dbr = wfGetDB( DB_SLAVE
);
1897 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1898 'ar_title' => $this->getDBkey() ), $fname );
1899 if( $this->getNamespace() == NS_IMAGE
) {
1900 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1901 array( 'fa_name' => $this->getDBkey() ), $fname );
1908 * Get the article ID for this Title from the link cache,
1909 * adding it if necessary
1910 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1912 * @return \type{\int} the ID
1914 public function getArticleID( $flags = 0 ) {
1915 $linkCache = LinkCache
::singleton();
1916 if ( $flags & GAID_FOR_UPDATE
) {
1917 $oldUpdate = $linkCache->forUpdate( true );
1918 $this->mArticleID
= $linkCache->addLinkObj( $this );
1919 $linkCache->forUpdate( $oldUpdate );
1921 if ( -1 == $this->mArticleID
) {
1922 $this->mArticleID
= $linkCache->addLinkObj( $this );
1925 return $this->mArticleID
;
1929 * Is this an article that is a redirect page?
1930 * Uses link cache, adding it if necessary
1931 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1932 * @return \type{\bool}
1934 public function isRedirect( $flags = 0 ) {
1935 if( !is_null($this->mRedirect
) )
1936 return $this->mRedirect
;
1937 # Zero for special pages.
1938 # Also, calling getArticleID() loads the field from cache!
1939 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1942 $linkCache = LinkCache
::singleton();
1943 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1945 return $this->mRedirect
;
1949 * What is the length of this page?
1950 * Uses link cache, adding it if necessary
1951 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1952 * @return \type{\bool}
1954 public function getLength( $flags = 0 ) {
1955 if( $this->mLength
!= -1 )
1956 return $this->mLength
;
1957 # Zero for special pages.
1958 # Also, calling getArticleID() loads the field from cache!
1959 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1962 $linkCache = LinkCache
::singleton();
1963 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1965 return $this->mLength
;
1969 * What is the page_latest field for this page?
1970 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1971 * @return \type{\int}
1973 public function getLatestRevID( $flags = 0 ) {
1974 if ($this->mLatestID
!== false)
1975 return $this->mLatestID
;
1977 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1978 return $this->mLatestID
= $db->selectField( 'revision',
1980 array('rev_page' => $this->getArticleID($flags)),
1981 'Title::getLatestRevID' );
1985 * This clears some fields in this object, and clears any associated
1986 * keys in the "bad links" section of the link cache.
1988 * - This is called from Article::insertNewArticle() to allow
1989 * loading of the new page_id. It's also called from
1990 * Article::doDeleteArticle()
1992 * @param $newid \type{\int} the new Article ID
1994 public function resetArticleID( $newid ) {
1995 $linkCache = LinkCache
::singleton();
1996 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1998 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1999 else { $this->mArticleID
= $newid; }
2000 $this->mRestrictionsLoaded
= false;
2001 $this->mRestrictions
= array();
2005 * Updates page_touched for this page; called from LinksUpdate.php
2006 * @return \type{\bool} true if the update succeded
2008 public function invalidateCache() {
2009 global $wgUseFileCache;
2011 if ( wfReadOnly() ) {
2015 $dbw = wfGetDB( DB_MASTER
);
2016 $success = $dbw->update( 'page',
2018 'page_touched' => $dbw->timestamp()
2019 ), array( /* WHERE */
2020 'page_namespace' => $this->getNamespace() ,
2021 'page_title' => $this->getDBkey()
2022 ), 'Title::invalidateCache'
2025 if ($wgUseFileCache) {
2026 $cache = new HTMLFileCache($this);
2027 @unlink
($cache->fileCacheName());
2034 * Prefix some arbitrary text with the namespace or interwiki prefix
2037 * @param $name \type{\string} the text
2038 * @return \type{\string} the prefixed text
2041 /* private */ function prefix( $name ) {
2043 if ( '' != $this->mInterwiki
) {
2044 $p = $this->mInterwiki
. ':';
2046 if ( 0 != $this->mNamespace
) {
2047 $p .= $this->getNsText() . ':';
2053 * Secure and split - main initialisation function for this object
2055 * Assumes that mDbkeyform has been set, and is urldecoded
2056 * and uses underscores, but not otherwise munged. This function
2057 * removes illegal characters, splits off the interwiki and
2058 * namespace prefixes, sets the other forms, and canonicalizes
2060 * @return \type{\bool} true on success
2062 private function secureAndSplit() {
2063 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2066 static $rxTc = false;
2068 # Matching titles will be held as illegal.
2070 # Any character not allowed is forbidden...
2071 '[^' . Title
::legalChars() . ']' .
2072 # URL percent encoding sequences interfere with the ability
2073 # to round-trip titles -- you can't link to them consistently.
2074 '|%[0-9A-Fa-f]{2}' .
2075 # XML/HTML character references produce similar issues.
2076 '|&[A-Za-z0-9\x80-\xff]+;' .
2078 '|&#x[0-9A-Fa-f]+;' .
2082 $this->mInterwiki
= $this->mFragment
= '';
2083 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2085 $dbkey = $this->mDbkeyform
;
2087 # Strip Unicode bidi override characters.
2088 # Sometimes they slip into cut-n-pasted page titles, where the
2089 # override chars get included in list displays.
2090 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2091 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2093 # Clean up whitespace
2095 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2096 $dbkey = trim( $dbkey, '_' );
2098 if ( '' == $dbkey ) {
2102 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2103 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2107 $this->mDbkeyform
= $dbkey;
2109 # Initial colon indicates main namespace rather than specified default
2110 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2111 if ( ':' == $dbkey{0} ) {
2112 $this->mNamespace
= NS_MAIN
;
2113 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2114 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2117 # Namespace or interwiki prefix
2121 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2123 if ( $ns = $wgContLang->getNsIndex( $p )) {
2124 # Ordinary namespace
2126 $this->mNamespace
= $ns;
2127 } elseif( $this->getInterwikiLink( $p ) ) {
2129 # Can't make a local interwiki link to an interwiki link.
2130 # That's just crazy!
2136 $this->mInterwiki
= $wgContLang->lc( $p );
2138 # Redundant interwiki prefix to the local wiki
2139 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2140 if( $dbkey == '' ) {
2141 # Can't have an empty self-link
2144 $this->mInterwiki
= '';
2146 # Do another namespace split...
2150 # If there's an initial colon after the interwiki, that also
2151 # resets the default namespace
2152 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2153 $this->mNamespace
= NS_MAIN
;
2154 $dbkey = substr( $dbkey, 1 );
2157 # If there's no recognized interwiki or namespace,
2158 # then let the colon expression be part of the title.
2163 # We already know that some pages won't be in the database!
2165 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2166 $this->mArticleID
= 0;
2168 $fragment = strstr( $dbkey, '#' );
2169 if ( false !== $fragment ) {
2170 $this->setFragment( $fragment );
2171 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2172 # remove whitespace again: prevents "Foo_bar_#"
2173 # becoming "Foo_bar_"
2174 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2177 # Reject illegal characters.
2179 if( preg_match( $rxTc, $dbkey ) ) {
2184 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2185 * reachable due to the way web browsers deal with 'relative' URLs.
2186 * Also, they conflict with subpage syntax. Forbid them explicitly.
2188 if ( strpos( $dbkey, '.' ) !== false &&
2189 ( $dbkey === '.' ||
$dbkey === '..' ||
2190 strpos( $dbkey, './' ) === 0 ||
2191 strpos( $dbkey, '../' ) === 0 ||
2192 strpos( $dbkey, '/./' ) !== false ||
2193 strpos( $dbkey, '/../' ) !== false ||
2194 substr( $dbkey, -2 ) == '/.' ||
2195 substr( $dbkey, -3 ) == '/..' ) )
2201 * Magic tilde sequences? Nu-uh!
2203 if( strpos( $dbkey, '~~~' ) !== false ) {
2208 * Limit the size of titles to 255 bytes.
2209 * This is typically the size of the underlying database field.
2210 * We make an exception for special pages, which don't need to be stored
2211 * in the database, and may edge over 255 bytes due to subpage syntax
2212 * for long titles, e.g. [[Special:Block/Long name]]
2214 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2215 strlen( $dbkey ) > 512 )
2221 * Normally, all wiki links are forced to have
2222 * an initial capital letter so [[foo]] and [[Foo]]
2223 * point to the same place.
2225 * Don't force it for interwikis, since the other
2226 * site might be case-sensitive.
2228 $this->mUserCaseDBKey
= $dbkey;
2229 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2230 $dbkey = $wgContLang->ucfirst( $dbkey );
2234 * Can't make a link to a namespace alone...
2235 * "empty" local links can only be self-links
2236 * with a fragment identifier.
2239 $this->mInterwiki
== '' &&
2240 $this->mNamespace
!= NS_MAIN
) {
2243 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2244 // IP names are not allowed for accounts, and can only be referring to
2245 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2246 // there are numerous ways to present the same IP. Having sp:contribs scan
2247 // them all is silly and having some show the edits and others not is
2248 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2249 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2250 IP
::sanitizeIP( $dbkey ) : $dbkey;
2251 // Any remaining initial :s are illegal.
2252 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2257 $this->mDbkeyform
= $dbkey;
2258 $this->mUrlform
= wfUrlencode( $dbkey );
2260 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2266 * Set the fragment for this title
2267 * This is kind of bad, since except for this rarely-used function, Title objects
2268 * are immutable. The reason this is here is because it's better than setting the
2269 * members directly, which is what Linker::formatComment was doing previously.
2271 * @param $fragment \type{\string} text
2272 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2274 public function setFragment( $fragment ) {
2275 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2279 * Get a Title object associated with the talk page of this article
2280 * @return \type{Title} the object for the talk page
2282 public function getTalkPage() {
2283 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2287 * Get a title object associated with the subject page of this
2290 * @return \type{Title} the object for the subject page
2292 public function getSubjectPage() {
2293 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2297 * Get an array of Title objects linking to this Title
2298 * Also stores the IDs in the link cache.
2300 * WARNING: do not use this function on arbitrary user-supplied titles!
2301 * On heavily-used templates it will max out the memory.
2303 * @param $options \type{\string} may be FOR UPDATE
2304 * @return \arrayof{Title} the Title objects linking here
2306 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2307 $linkCache = LinkCache
::singleton();
2310 $db = wfGetDB( DB_MASTER
);
2312 $db = wfGetDB( DB_SLAVE
);
2315 $res = $db->select( array( 'page', $table ),
2316 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2318 "{$prefix}_from=page_id",
2319 "{$prefix}_namespace" => $this->getNamespace(),
2320 "{$prefix}_title" => $this->getDBkey() ),
2325 if ( $db->numRows( $res ) ) {
2326 foreach( $res as $row ) {
2327 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2328 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2329 $retVal[] = $titleObj;
2333 $db->freeResult( $res );
2338 * Get an array of Title objects using this Title as a template
2339 * Also stores the IDs in the link cache.
2341 * WARNING: do not use this function on arbitrary user-supplied titles!
2342 * On heavily-used templates it will max out the memory.
2344 * @param $options \type{\string} may be FOR UPDATE
2345 * @return \arrayof{Title} the Title objects linking here
2347 public function getTemplateLinksTo( $options = '' ) {
2348 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2352 * Get an array of Title objects referring to non-existent articles linked from this page
2354 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2355 * @param $options \type{\string} may be FOR UPDATE
2356 * @return \arrayof{Title} the Title objects
2358 public function getBrokenLinksFrom( $options = '' ) {
2359 if ( $this->getArticleId() == 0 ) {
2360 # All links from article ID 0 are false positives
2365 $db = wfGetDB( DB_MASTER
);
2367 $db = wfGetDB( DB_SLAVE
);
2370 $res = $db->safeQuery(
2371 "SELECT pl_namespace, pl_title
2374 ON pl_namespace=page_namespace
2375 AND pl_title=page_title
2377 AND page_namespace IS NULL
2379 $db->tableName( 'pagelinks' ),
2380 $db->tableName( 'page' ),
2381 $this->getArticleId(),
2385 if ( $db->numRows( $res ) ) {
2386 foreach( $res as $row ) {
2387 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2390 $db->freeResult( $res );
2396 * Get a list of URLs to purge from the Squid cache when this
2399 * @return \arrayof{\string} the URLs
2401 public function getSquidURLs() {
2405 $this->getInternalURL(),
2406 $this->getInternalURL( 'action=history' )
2409 // purge variant urls as well
2410 if($wgContLang->hasVariants()){
2411 $variants = $wgContLang->getVariants();
2412 foreach($variants as $vCode){
2413 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2414 $urls[] = $this->getInternalURL('',$vCode);
2422 * Purge all applicable Squid URLs
2424 public function purgeSquid() {
2426 if ( $wgUseSquid ) {
2427 $urls = $this->getSquidURLs();
2428 $u = new SquidUpdate( $urls );
2434 * Move this page without authentication
2435 * @param &$nt \type{Title} the new page Title
2437 public function moveNoAuth( &$nt ) {
2438 return $this->moveTo( $nt, false );
2442 * Check whether a given move operation would be valid.
2443 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2444 * @param &$nt \type{Title} the new title
2445 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2447 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2448 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2450 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2453 // Normally we'd add this to $errors, but we'll get
2454 // lots of syntax errors if $nt is not an object
2455 return array(array('badtitletext'));
2457 if( $this->equals( $nt ) ) {
2458 $errors[] = array('selfmove');
2460 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2461 $errors[] = array('immobile_namespace');
2464 $oldid = $this->getArticleID();
2465 $newid = $nt->getArticleID();
2467 if ( strlen( $nt->getDBkey() ) < 1 ) {
2468 $errors[] = array('articleexists');
2470 if ( ( '' == $this->getDBkey() ) ||
2472 ( '' == $nt->getDBkey() ) ) {
2473 $errors[] = array('badarticleerror');
2476 // Image-specific checks
2477 if( $this->getNamespace() == NS_IMAGE
) {
2478 $file = wfLocalFile( $this );
2479 if( $file->exists() ) {
2480 if( $nt->getNamespace() != NS_IMAGE
) {
2481 $errors[] = array('imagenocrossnamespace');
2483 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2484 $errors[] = array('imageinvalidfilename');
2486 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2487 $errors[] = array('imagetypemismatch');
2494 $errors = array_merge($errors,
2495 $this->getUserPermissionsErrors('move', $wgUser),
2496 $this->getUserPermissionsErrors('edit', $wgUser),
2497 $nt->getUserPermissionsErrors('move', $wgUser),
2498 $nt->getUserPermissionsErrors('edit', $wgUser));
2503 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2504 $errors[] = array('hookaborted', $err);
2507 # The move is allowed only if (1) the target doesn't exist, or
2508 # (2) the target is a redirect to the source, and has no history
2509 # (so we can undo bad moves right after they're done).
2511 if ( 0 != $newid ) { # Target exists; check for validity
2512 if ( ! $this->isValidMoveTarget( $nt ) ) {
2513 $errors[] = array('articleexists');
2516 $tp = $nt->getTitleProtection();
2517 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2518 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2519 $errors[] = array('cantmove-titleprotected');
2528 * Move a title to a new location
2529 * @param &$nt \type{Title} the new title
2530 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2532 * @param $reason \type{\string} The reason for the move
2533 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2534 * Ignored if the user doesn't have the suppressredirect right.
2535 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2537 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2538 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2539 if( is_array( $err ) ) {
2543 $pageid = $this->getArticleID();
2544 if( $nt->exists() ) {
2545 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2546 $pageCountChange = ($createRedirect ?
0 : -1);
2547 } else { # Target didn't exist, do normal move.
2548 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2549 $pageCountChange = ($createRedirect ?
1 : 0);
2552 if( is_array( $err ) ) {
2555 $redirid = $this->getArticleID();
2557 // Category memberships include a sort key which may be customized.
2558 // If it's left as the default (the page title), we need to update
2559 // the sort key to match the new title.
2561 // Be careful to avoid resetting cl_timestamp, which may disturb
2562 // time-based lists on some sites.
2564 // Warning -- if the sort key is *explicitly* set to the old title,
2565 // we can't actually distinguish it from a default here, and it'll
2566 // be set to the new title even though it really shouldn't.
2567 // It'll get corrected on the next edit, but resetting cl_timestamp.
2568 $dbw = wfGetDB( DB_MASTER
);
2569 $dbw->update( 'categorylinks',
2571 'cl_sortkey' => $nt->getPrefixedText(),
2572 'cl_timestamp=cl_timestamp' ),
2574 'cl_from' => $pageid,
2575 'cl_sortkey' => $this->getPrefixedText() ),
2580 $oldnamespace = $this->getNamespace() & ~
1;
2581 $newnamespace = $nt->getNamespace() & ~
1;
2582 $oldtitle = $this->getDBkey();
2583 $newtitle = $nt->getDBkey();
2585 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2586 WatchedItem
::duplicateEntries( $this, $nt );
2589 # Update search engine
2590 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2592 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2596 if( $this->isContentPage() && !$nt->isContentPage() ) {
2597 # No longer a content page
2598 # Not viewed, edited, removing
2599 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2600 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2601 # Now a content page
2602 # Not viewed, edited, adding
2603 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2604 } elseif( $pageCountChange ) {
2606 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2613 # Update message cache for interface messages
2614 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2615 global $wgMessageCache;
2616 $oldarticle = new Article( $this );
2617 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2618 $newarticle = new Article( $nt );
2619 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2623 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2628 * Move page to a title which is at present a redirect to the
2631 * @param &$nt \type{Title} the page to move to, which should currently
2633 * @param $reason \type{\string} The reason for the move
2634 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2635 * Ignored if the user doesn't have the suppressredirect right
2637 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2638 global $wgUseSquid, $wgUser;
2639 $fname = 'Title::moveOverExistingRedirect';
2640 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2643 $comment .= ": $reason";
2646 $now = wfTimestampNow();
2647 $newid = $nt->getArticleID();
2648 $oldid = $this->getArticleID();
2649 $latest = $this->getLatestRevID();
2651 $dbw = wfGetDB( DB_MASTER
);
2654 # Delete the old redirect. We don't save it to history since
2655 # by definition if we've got here it's rather uninteresting.
2656 # We have to remove it so that the next step doesn't trigger
2657 # a conflict on the unique namespace+title index...
2658 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2659 if ( !$dbw->cascadingDeletes() ) {
2660 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2661 global $wgUseTrackbacks;
2662 if ($wgUseTrackbacks)
2663 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2664 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2665 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2666 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2667 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2668 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2669 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2670 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2673 # Save a null revision in the page's history notifying of the move
2674 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2675 $nullRevId = $nullRevision->insertOn( $dbw );
2677 $article = new Article( $this );
2678 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2680 # Change the name of the target page:
2681 $dbw->update( 'page',
2683 'page_touched' => $dbw->timestamp($now),
2684 'page_namespace' => $nt->getNamespace(),
2685 'page_title' => $nt->getDBkey(),
2686 'page_latest' => $nullRevId,
2688 /* WHERE */ array( 'page_id' => $oldid ),
2691 $nt->resetArticleID( $oldid );
2693 # Recreate the redirect, this time in the other direction.
2694 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2695 $mwRedir = MagicWord
::get( 'redirect' );
2696 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2697 $redirectArticle = new Article( $this );
2698 $newid = $redirectArticle->insertOn( $dbw );
2699 $redirectRevision = new Revision( array(
2701 'comment' => $comment,
2702 'text' => $redirectText ) );
2703 $redirectRevision->insertOn( $dbw );
2704 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2706 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2708 # Now, we record the link from the redirect to the new title.
2709 # It should have no other outgoing links...
2710 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2711 $dbw->insert( 'pagelinks',
2713 'pl_from' => $newid,
2714 'pl_namespace' => $nt->getNamespace(),
2715 'pl_title' => $nt->getDBkey() ),
2718 $this->resetArticleID( 0 );
2721 # Move an image if this is a file
2722 if( $this->getNamespace() == NS_IMAGE
) {
2723 $file = wfLocalFile( $this );
2724 if( $file->exists() ) {
2725 $status = $file->move( $nt );
2726 if( !$status->isOk() ) {
2728 return $status->getErrorsArray();
2735 $log = new LogPage( 'move' );
2736 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2739 if ( $wgUseSquid ) {
2740 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2741 $u = new SquidUpdate( $urls );
2748 * Move page to non-existing title.
2749 * @param &$nt \type{Title} the new Title
2750 * @param $reason \type{\string} The reason for the move
2751 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2752 * Ignored if the user doesn't have the suppressredirect right
2754 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2755 global $wgUseSquid, $wgUser;
2756 $fname = 'MovePageForm::moveToNewTitle';
2757 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2759 $comment .= ": $reason";
2762 $newid = $nt->getArticleID();
2763 $oldid = $this->getArticleID();
2764 $latest = $this->getLatestRevId();
2766 $dbw = wfGetDB( DB_MASTER
);
2768 $now = $dbw->timestamp();
2770 # Save a null revision in the page's history notifying of the move
2771 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2772 $nullRevId = $nullRevision->insertOn( $dbw );
2774 $article = new Article( $this );
2775 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2778 $dbw->update( 'page',
2780 'page_touched' => $now,
2781 'page_namespace' => $nt->getNamespace(),
2782 'page_title' => $nt->getDBkey(),
2783 'page_latest' => $nullRevId,
2785 /* WHERE */ array( 'page_id' => $oldid ),
2788 $nt->resetArticleID( $oldid );
2790 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2792 $mwRedir = MagicWord
::get( 'redirect' );
2793 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2794 $redirectArticle = new Article( $this );
2795 $newid = $redirectArticle->insertOn( $dbw );
2796 $redirectRevision = new Revision( array(
2798 'comment' => $comment,
2799 'text' => $redirectText ) );
2800 $redirectRevision->insertOn( $dbw );
2801 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2803 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2805 # Record the just-created redirect's linking to the page
2806 $dbw->insert( 'pagelinks',
2808 'pl_from' => $newid,
2809 'pl_namespace' => $nt->getNamespace(),
2810 'pl_title' => $nt->getDBkey() ),
2813 $this->resetArticleID( 0 );
2816 # Move an image if this is a file
2817 if( $this->getNamespace() == NS_IMAGE
) {
2818 $file = wfLocalFile( $this );
2819 if( $file->exists() ) {
2820 $status = $file->move( $nt );
2821 if( !$status->isOk() ) {
2823 return $status->getErrorsArray();
2830 $log = new LogPage( 'move' );
2831 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2833 # Purge caches as per article creation
2834 Article
::onArticleCreate( $nt );
2836 # Purge old title from squid
2837 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2838 $this->purgeSquid();
2843 * Checks if $this can be moved to a given Title
2844 * - Selects for update, so don't call it unless you mean business
2846 * @param &$nt \type{Title} the new title to check
2847 * @return \type{\bool} TRUE or FALSE
2849 public function isValidMoveTarget( $nt ) {
2851 $fname = 'Title::isValidMoveTarget';
2852 $dbw = wfGetDB( DB_MASTER
);
2854 # Is it an existsing file?
2855 if( $nt->getNamespace() == NS_IMAGE
) {
2856 $file = wfLocalFile( $nt );
2857 if( $file->exists() ) {
2858 wfDebug( __METHOD__
. ": file exists\n" );
2864 $id = $nt->getArticleID();
2865 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2866 array( 'page_is_redirect','old_text','old_flags' ),
2867 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2868 $fname, 'FOR UPDATE' );
2870 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2872 wfDebug( __METHOD__
. ": not a redirect\n" );
2875 $text = Revision
::getRevisionText( $obj );
2877 # Does the redirect point to the source?
2878 # Or is it a broken self-redirect, usually caused by namespace collisions?
2880 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2881 $redirTitle = Title
::newFromText( $m[1] );
2882 if( !is_object( $redirTitle ) ||
2883 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2884 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2885 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2890 wfDebug( __METHOD__
. ": failsafe\n" );
2894 # Does the article have a history?
2895 $row = $dbw->selectRow( array( 'page', 'revision'),
2897 array( 'page_namespace' => $nt->getNamespace(),
2898 'page_title' => $nt->getDBkey(),
2899 'page_id=rev_page AND page_latest != rev_id'
2900 ), $fname, 'FOR UPDATE'
2903 # Return true if there was no history
2904 return $row === false;
2908 * Can this title be added to a user's watchlist?
2910 * @return \type{\bool} TRUE or FALSE
2912 public function isWatchable() {
2913 return !$this->isExternal()
2914 && MWNamespace
::isWatchable( $this->getNamespace() );
2918 * Get categories to which this Title belongs and return an array of
2919 * categories' names.
2921 * @return \type{\array} array an array of parents in the form:
2922 * $parent => $currentarticle
2924 public function getParentCategories() {
2927 $titlekey = $this->getArticleId();
2928 $dbr = wfGetDB( DB_SLAVE
);
2929 $categorylinks = $dbr->tableName( 'categorylinks' );
2932 $sql = "SELECT * FROM $categorylinks"
2933 ." WHERE cl_from='$titlekey'"
2934 ." AND cl_from <> '0'"
2935 ." ORDER BY cl_sortkey";
2937 $res = $dbr->query( $sql );
2939 if( $dbr->numRows( $res ) > 0 ) {
2940 foreach( $res as $row )
2941 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2942 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2943 $dbr->freeResult( $res );
2951 * Get a tree of parent categories
2952 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2953 * @return \type{\array} Tree of parent categories
2955 public function getParentCategoryTree( $children = array() ) {
2957 $parents = $this->getParentCategories();
2960 foreach( $parents as $parent => $current ) {
2961 if ( array_key_exists( $parent, $children ) ) {
2962 # Circular reference
2963 $stack[$parent] = array();
2965 $nt = Title
::newFromText($parent);
2967 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2979 * Get an associative array for selecting this title from
2982 * @return \type{\array} Selection array
2984 public function pageCond() {
2985 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2989 * Get the revision ID of the previous revision
2991 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2992 * @param $flags \type{\int} GAID_FOR_UPDATE
2993 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2995 public function getPreviousRevisionID( $revId, $flags=0 ) {
2996 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2997 return $db->selectField( 'revision', 'rev_id',
2999 'rev_page' => $this->getArticleId($flags),
3000 'rev_id < ' . intval( $revId )
3003 array( 'ORDER BY' => 'rev_id DESC' )
3008 * Get the revision ID of the next revision
3010 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3011 * @param $flags \type{\int} GAID_FOR_UPDATE
3012 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3014 public function getNextRevisionID( $revId, $flags=0 ) {
3015 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3016 return $db->selectField( 'revision', 'rev_id',
3018 'rev_page' => $this->getArticleId($flags),
3019 'rev_id > ' . intval( $revId )
3022 array( 'ORDER BY' => 'rev_id' )
3027 * Get the number of revisions between the given revision IDs.
3028 * Used for diffs and other things that really need it.
3030 * @param $old \type{\int} Revision ID.
3031 * @param $new \type{\int} Revision ID.
3032 * @return \type{\int} Number of revisions between these IDs.
3034 public function countRevisionsBetween( $old, $new ) {
3035 $dbr = wfGetDB( DB_SLAVE
);
3036 return $dbr->selectField( 'revision', 'count(*)',
3037 'rev_page = ' . intval( $this->getArticleId() ) .
3038 ' AND rev_id > ' . intval( $old ) .
3039 ' AND rev_id < ' . intval( $new ),
3041 array( 'USE INDEX' => 'PRIMARY' ) );
3045 * Compare with another title.
3047 * @param \type{Title} $title
3048 * @return \type{\bool} TRUE or FALSE
3050 public function equals( Title
$title ) {
3051 // Note: === is necessary for proper matching of number-like titles.
3052 return $this->getInterwiki() === $title->getInterwiki()
3053 && $this->getNamespace() == $title->getNamespace()
3054 && $this->getDBkey() === $title->getDBkey();
3058 * Callback for usort() to do title sorts by (namespace, title)
3060 static function compare( $a, $b ) {
3061 if( $a->getNamespace() == $b->getNamespace() ) {
3062 return strcmp( $a->getText(), $b->getText() );
3064 return $a->getNamespace() - $b->getNamespace();
3069 * Return a string representation of this title
3071 * @return \type{\string} String representation of this title
3073 public function __toString() {
3074 return $this->getPrefixedText();
3078 * Check if page exists
3079 * @return \type{\bool} TRUE or FALSE
3081 public function exists() {
3082 return $this->getArticleId() != 0;
3086 * Do we know that this title definitely exists, or should we otherwise
3087 * consider that it exists?
3089 * @return \type{\bool} TRUE or FALSE
3091 public function isAlwaysKnown() {
3092 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3093 // the full l10n of that language to be loaded. That takes much memory and
3094 // isn't needed. So we strip the language part away.
3095 // Also, extension messages which are not loaded, are shown as red, because
3096 // we don't call MessageCache::loadAllMessages.
3097 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3098 return $this->isExternal()
3099 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3100 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3104 * Update page_touched timestamps and send squid purge messages for
3105 * pages linking to this title. May be sent to the job queue depending
3106 * on the number of links. Typically called on create and delete.
3108 public function touchLinks() {
3109 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3112 if ( $this->getNamespace() == NS_CATEGORY
) {
3113 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3119 * Get the last touched timestamp
3120 * @return \type{\string} Last touched timestamp
3122 public function getTouched() {
3123 $dbr = wfGetDB( DB_SLAVE
);
3124 $touched = $dbr->selectField( 'page', 'page_touched',
3126 'page_namespace' => $this->getNamespace(),
3127 'page_title' => $this->getDBkey()
3134 * Get the trackback URL for this page
3135 * @return \type{\string} Trackback URL
3137 public function trackbackURL() {
3138 global $wgTitle, $wgScriptPath, $wgServer;
3140 return "$wgServer$wgScriptPath/trackback.php?article="
3141 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3145 * Get the trackback RDF for this page
3146 * @return \type{\string} Trackback RDF
3148 public function trackbackRDF() {
3149 $url = htmlspecialchars($this->getFullURL());
3150 $title = htmlspecialchars($this->getText());
3151 $tburl = $this->trackbackURL();
3153 // Autodiscovery RDF is placed in comments so HTML validator
3154 // won't barf. This is a rather icky workaround, but seems
3155 // frequently used by this kind of RDF thingy.
3157 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3159 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3160 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3161 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3164 dc:identifier=\"$url\"
3166 trackback:ping=\"$tburl\" />
3172 * Generate strings used for xml 'id' names in monobook tabs
3173 * @return \type{\string} XML 'id' name
3175 public function getNamespaceKey() {
3177 switch ($this->getNamespace()) {
3180 return 'nstab-main';
3183 return 'nstab-user';
3185 return 'nstab-media';
3187 return 'nstab-special';
3189 case NS_PROJECT_TALK
:
3190 return 'nstab-project';
3193 return 'nstab-image';
3195 case NS_MEDIAWIKI_TALK
:
3196 return 'nstab-mediawiki';
3198 case NS_TEMPLATE_TALK
:
3199 return 'nstab-template';
3202 return 'nstab-help';
3204 case NS_CATEGORY_TALK
:
3205 return 'nstab-category';
3207 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3212 * Returns true if this title resolves to the named special page
3213 * @param $name \type{\string} The special page name
3215 public function isSpecial( $name ) {
3216 if ( $this->getNamespace() == NS_SPECIAL
) {
3217 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3218 if ( $name == $thisName ) {
3226 * If the Title refers to a special page alias which is not the local default,
3227 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3229 public function fixSpecialName() {
3230 if ( $this->getNamespace() == NS_SPECIAL
) {
3231 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3232 if ( $canonicalName ) {
3233 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3234 if ( $localName != $this->mDbkeyform
) {
3235 return Title
::makeTitle( NS_SPECIAL
, $localName );
3243 * Is this Title in a namespace which contains content?
3244 * In other words, is this a content page, for the purposes of calculating
3247 * @return \type{\bool} TRUE or FALSE
3249 public function isContentPage() {
3250 return MWNamespace
::isContent( $this->getNamespace() );
3254 * Get all extant redirects to this Title
3256 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3257 * NULL to consider all namespaces
3258 * @return \arrayof{Title} Redirects to this title
3260 public function getRedirectsHere( $ns = null ) {
3263 $dbr = wfGetDB( DB_SLAVE
);
3265 'rd_namespace' => $this->getNamespace(),
3266 'rd_title' => $this->getDBkey(),
3269 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3271 $res = $dbr->select(
3272 array( 'redirect', 'page' ),
3273 array( 'page_namespace', 'page_title' ),
3279 foreach( $res as $row ) {
3280 $redirs[] = self
::newFromRow( $row );