7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
15 * Constants for pr_cascade bitfield
17 define( 'CASCADE', 1 );
20 * Represents a title within MediaWiki.
21 * Optionally may contain an interwiki designation or namespace.
22 * @note This class can fetch various kinds of data from the database;
23 * however, it does so inefficiently.
26 /** @name Static cache variables */
28 static private $titleCache=array();
29 static private $interwikiCache=array();
33 * Title::newFromText maintains a cache to avoid expensive re-normalization of
34 * commonly used titles. On a batch operation this can become a memory leak
35 * if not bounded. After hitting this many titles reset the cache.
37 const CACHE_MAX
= 1000;
41 * @name Private member variables
42 * Please use the accessor functions instead.
47 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
48 var $mUrlform = ''; ///< URL-encoded form of the main part
49 var $mDbkeyform = ''; ///< Main part with underscores
50 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
51 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
53 var $mFragment; ///< Title fragment (i.e. the bit after the #)
54 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
55 var $mLatestID = false; ///< ID of most recent revision
56 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
59 var $mRestrictionsExpiry; ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeRestrictionSources; ///< Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
63 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; ///< The page length, 0 for special pages
70 var $mRedirect = null; ///< Is the article at this title a redirect?
78 /* private */ function __construct() {}
81 * Create a new Title from a prefixed DB key
82 * @param $key \type{\string} The database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return \type{Title} the new object, or NULL on an error
87 public static function newFromDBkey( $key ) {
89 $t->mDbkeyform
= $key;
90 if( $t->secureAndSplit() )
97 * Create a new Title from text, such as what one would
98 * find in a link. Decodes any HTML entities in the text.
100 * @param $text \type{\string} the link text; spaces, prefixes,
101 * and an initial ':' indicating the main namespace
103 * @param $defaultNamespace \type{\int} the namespace to use if
104 * none is specified by a prefix
105 * @return \type{Title} the new object, or NULL on an error
107 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
108 if( is_object( $text ) ) {
109 throw new MWException( 'Title::newFromText given an object' );
113 * Wiki pages often contain multiple links to the same page.
114 * Title normalization and parsing can become expensive on
115 * pages with many links, so we can save a little time by
118 * In theory these are value objects and won't get changed...
120 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
121 return Title
::$titleCache[$text];
125 * Convert things like é ā or 〗 into real text...
127 $filteredText = Sanitizer
::decodeCharReferences( $text );
130 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
131 $t->mDefaultNamespace
= $defaultNamespace;
133 static $cachedcount = 0 ;
134 if( $t->secureAndSplit() ) {
135 if( $defaultNamespace == NS_MAIN
) {
136 if( $cachedcount >= self
::CACHE_MAX
) {
137 # Avoid memory leaks on mass operations...
138 Title
::$titleCache = array();
142 Title
::$titleCache[$text] =& $t;
152 * Create a new Title from URL-encoded text. Ensures that
153 * the given title's length does not exceed the maximum.
154 * @param $url \type{\string} the title, as might be taken from a URL
155 * @return \type{Title} the new object, or NULL on an error
157 public static function newFromURL( $url ) {
158 global $wgLegalTitleChars;
161 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
162 # but some URLs used it as a space replacement and they still come
163 # from some external search tools.
164 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
165 $url = str_replace( '+', ' ', $url );
168 $t->mDbkeyform
= str_replace( ' ', '_', $url );
169 if( $t->secureAndSplit() ) {
177 * Create a new Title from an article ID
179 * @todo This is inefficiently implemented, the page row is requested
180 * but not used for anything else
182 * @param $id \type{\int} the page_id corresponding to the Title to create
183 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
184 * @return \type{Title} the new object, or NULL on an error
186 public static function newFromID( $id, $flags = 0 ) {
187 $fname = 'Title::newFromID';
188 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
189 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
190 array( 'page_id' => $id ), $fname );
191 if ( $row !== false ) {
192 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
200 * Make an array of titles from an array of IDs
201 * @param $ids \arrayof{\int} Array of IDs
202 * @return \arrayof{Title} Array of Titles
204 public static function newFromIDs( $ids ) {
205 if ( !count( $ids ) ) {
208 $dbr = wfGetDB( DB_SLAVE
);
209 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
210 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
213 foreach( $res as $row ) {
214 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
220 * Make a Title object from a DB row
221 * @param $row \type{Row} (needs at least page_title,page_namespace)
222 * @return \type{Title} corresponding Title
224 public static function newFromRow( $row ) {
225 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
227 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
228 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
229 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
230 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
236 * Create a new Title from a namespace index and a DB key.
237 * It's assumed that $ns and $title are *valid*, for instance when
238 * they came directly from the database or a special page name.
239 * For convenience, spaces are converted to underscores so that
240 * eg user_text fields can be used directly.
242 * @param $ns \type{\int} the namespace of the article
243 * @param $title \type{\string} the unprefixed database key form
244 * @param $fragment \type{\string} The link fragment (after the "#")
245 * @return \type{Title} the new object
247 public static function &makeTitle( $ns, $title, $fragment = '' ) {
250 $t->mFragment
= $fragment;
251 $t->mNamespace
= $ns = intval( $ns );
252 $t->mDbkeyform
= str_replace( ' ', '_', $title );
253 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
254 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
255 $t->mTextform
= str_replace( '_', ' ', $title );
260 * Create a new Title from a namespace index and a DB key.
261 * The parameters will be checked for validity, which is a bit slower
262 * than makeTitle() but safer for user-provided data.
264 * @param $ns \type{\int} the namespace of the article
265 * @param $title \type{\string} the database key form
266 * @param $fragment \type{\string} The link fragment (after the "#")
267 * @return \type{Title} the new object, or NULL on an error
269 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
271 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
272 if( $t->secureAndSplit() ) {
280 * Create a new Title for the Main Page
281 * @return \type{Title} the new object
283 public static function newMainPage() {
284 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
285 // Don't give fatal errors if the message is broken
287 $title = Title
::newFromText( 'Main Page' );
293 * Extract a redirect destination from a string and return the
294 * Title, or null if the text doesn't contain a valid redirect
296 * @param $text \type{String} Text with possible redirect
297 * @return \type{Title} The corresponding Title
299 public static function newFromRedirect( $text ) {
300 $redir = MagicWord
::get( 'redirect' );
302 if( $redir->matchStartAndRemove( $text ) ) {
303 // Extract the first link and see if it's usable
304 // Ensure that it really does come directly after #REDIRECT
305 // Some older redirects included a colon, so don't freak about that!
307 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
308 // Strip preceding colon used to "escape" categories, etc.
309 // and URL-decode links
310 if( strpos( $m[1], '%' ) !== false ) {
311 // Match behavior of inline link parsing here;
312 // don't interpret + as " " most of the time!
313 // It might be safe to just use rawurldecode instead, though.
314 $m[1] = urldecode( ltrim( $m[1], ':' ) );
316 $title = Title
::newFromText( $m[1] );
317 // Redirects to Special:Userlogout are not permitted
318 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
325 #----------------------------------------------------------------------------
327 #----------------------------------------------------------------------------
330 * Get the prefixed DB key associated with an ID
331 * @param $id \type{\int} the page_id of the article
332 * @return \type{Title} an object representing the article, or NULL
333 * if no such article was found
335 public static function nameOf( $id ) {
336 $dbr = wfGetDB( DB_SLAVE
);
338 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
339 if ( $s === false ) { return NULL; }
341 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
346 * Get a regex character class describing the legal characters in a link
347 * @return \type{\string} the list of characters, not delimited
349 public static function legalChars() {
350 global $wgLegalTitleChars;
351 return $wgLegalTitleChars;
355 * Get a string representation of a title suitable for
356 * including in a search index
358 * @param $ns \type{\int} a namespace index
359 * @param $title \type{\string} text-form main part
360 * @return \type{\string} a stripped-down title string ready for the
363 public static function indexTitle( $ns, $title ) {
366 $lc = SearchEngine
::legalSearchChars() . '&#;';
367 $t = $wgContLang->stripForSearch( $title );
368 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
369 $t = $wgContLang->lc( $t );
372 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
373 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
375 $t = preg_replace( "/\\s+/", ' ', $t );
377 if ( $ns == NS_IMAGE
) {
378 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
384 * Make a prefixed DB key from a DB key and a namespace index
385 * @param $ns \type{\int} numerical representation of the namespace
386 * @param $title \type{\string} the DB key form the title
387 * @param $fragment \type{\string} The link fragment (after the "#")
388 * @return \type{\string} the prefixed form of the title
390 public static function makeName( $ns, $title, $fragment = '' ) {
393 $namespace = $wgContLang->getNsText( $ns );
394 $name = $namespace == '' ?
$title : "$namespace:$title";
395 if ( strval( $fragment ) != '' ) {
396 $name .= '#' . $fragment;
402 * Returns the URL associated with an interwiki prefix
403 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
404 * @return \type{\string} the associated URL, containing "$1",
405 * which should be replaced by an article title
408 public function getInterwikiLink( $key ) {
409 global $wgMemc, $wgInterwikiExpiry;
410 global $wgInterwikiCache, $wgContLang;
411 $fname = 'Title::getInterwikiLink';
413 $key = $wgContLang->lc( $key );
415 $k = wfMemcKey( 'interwiki', $key );
416 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
417 return Title
::$interwikiCache[$k]->iw_url
;
420 if ($wgInterwikiCache) {
421 return Title
::getInterwikiCached( $key );
424 $s = $wgMemc->get( $k );
425 # Ignore old keys with no iw_local
426 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
427 Title
::$interwikiCache[$k] = $s;
431 $dbr = wfGetDB( DB_SLAVE
);
432 $res = $dbr->select( 'interwiki',
433 array( 'iw_url', 'iw_local', 'iw_trans' ),
434 array( 'iw_prefix' => $key ), $fname );
439 $s = $dbr->fetchObject( $res );
441 # Cache non-existence: create a blank object and save it to memcached
447 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
448 Title
::$interwikiCache[$k] = $s;
454 * Fetch interwiki prefix data from local cache in constant database.
456 * @note More logic is explained in DefaultSettings.
458 * @param $key \type{\string} Database key
459 * @return \type{\string} URL of interwiki site
461 public static function getInterwikiCached( $key ) {
462 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
466 $db=dba_open($wgInterwikiCache,'r','cdb');
467 /* Resolve site name */
468 if ($wgInterwikiScopes>=3 and !$site) {
469 $site = dba_fetch('__sites:' . wfWikiID(), $db);
471 $site = $wgInterwikiFallbackSite;
473 $value = dba_fetch( wfMemcKey( $key ), $db);
474 if ($value=='' and $wgInterwikiScopes>=3) {
476 $value = dba_fetch("_{$site}:{$key}", $db);
478 if ($value=='' and $wgInterwikiScopes>=2) {
480 $value = dba_fetch("__global:{$key}", $db);
489 list($local,$url)=explode(' ',$value,2);
491 $s->iw_local
=(int)$local;
493 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
498 * Determine whether the object refers to a page within
501 * @return \type{\bool} TRUE if this is an in-project interwiki link
502 * or a wikilink, FALSE otherwise
504 public function isLocal() {
505 if ( $this->mInterwiki
!= '' ) {
506 # Make sure key is loaded into cache
507 $this->getInterwikiLink( $this->mInterwiki
);
508 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
509 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
516 * Determine whether the object refers to a page within
517 * this project and is transcludable.
519 * @return \type{\bool} TRUE if this is transcludable
521 public function isTrans() {
522 if ($this->mInterwiki
== '')
524 # Make sure key is loaded into cache
525 $this->getInterwikiLink( $this->mInterwiki
);
526 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
527 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
531 * Escape a text fragment, say from a link, for a URL
533 static function escapeFragmentForURL( $fragment ) {
534 $fragment = str_replace( ' ', '_', $fragment );
535 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
536 $replaceArray = array(
540 return strtr( $fragment, $replaceArray );
543 #----------------------------------------------------------------------------
545 #----------------------------------------------------------------------------
547 /** Simple accessors */
549 * Get the text form (spaces not underscores) of the main part
550 * @return \type{\string} Main part of the title
552 public function getText() { return $this->mTextform
; }
554 * Get the URL-encoded form of the main part
555 * @return \type{\string} Main part of the title, URL-encoded
557 public function getPartialURL() { return $this->mUrlform
; }
559 * Get the main part with underscores
560 * @return \type{\string} Main part of the title, with underscores
562 public function getDBkey() { return $this->mDbkeyform
; }
564 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
565 * @return \type{\int} Namespace index
567 public function getNamespace() { return $this->mNamespace
; }
569 * Get the namespace text
570 * @return \type{\string} Namespace text
572 public function getNsText() {
573 global $wgContLang, $wgCanonicalNamespaceNames;
575 if ( '' != $this->mInterwiki
) {
576 // This probably shouldn't even happen. ohh man, oh yuck.
577 // But for interwiki transclusion it sometimes does.
578 // Shit. Shit shit shit.
580 // Use the canonical namespaces if possible to try to
581 // resolve a foreign namespace.
582 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
583 return $wgCanonicalNamespaceNames[$this->mNamespace
];
586 return $wgContLang->getNsText( $this->mNamespace
);
589 * Get the DB key with the initial letter case as specified by the user
590 * @return \type{\string} DB key
592 function getUserCaseDBKey() {
593 return $this->mUserCaseDBKey
;
596 * Get the namespace text of the subject (rather than talk) page
597 * @return \type{\string} Namespace text
599 public function getSubjectNsText() {
601 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
604 * Get the namespace text of the talk page
605 * @return \type{\string} Namespace text
607 public function getTalkNsText() {
609 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
612 * Could this title have a corresponding talk page?
613 * @return \type{\bool} TRUE or FALSE
615 public function canTalk() {
616 return( MWNamespace
::canTalk( $this->mNamespace
) );
619 * Get the interwiki prefix (or null string)
620 * @return \type{\string} Interwiki prefix
622 public function getInterwiki() { return $this->mInterwiki
; }
624 * Get the Title fragment (i.e.\ the bit after the #) in text form
625 * @return \type{\string} Title fragment
627 public function getFragment() { return $this->mFragment
; }
629 * Get the fragment in URL form, including the "#" character if there is one
630 * @return \type{\string} Fragment in URL form
632 public function getFragmentForURL() {
633 if ( $this->mFragment
== '' ) {
636 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
640 * Get the default namespace index, for when there is no namespace
641 * @return \type{\int} Default namespace index
643 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
646 * Get title for search index
647 * @return \type{\string} a stripped-down title string ready for the
650 public function getIndexTitle() {
651 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
655 * Get the prefixed database key form
656 * @return \type{\string} the prefixed title, with underscores and
657 * any interwiki and namespace prefixes
659 public function getPrefixedDBkey() {
660 $s = $this->prefix( $this->mDbkeyform
);
661 $s = str_replace( ' ', '_', $s );
666 * Get the prefixed title with spaces.
667 * This is the form usually used for display
668 * @return \type{\string} the prefixed title, with spaces
670 public function getPrefixedText() {
671 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
672 $s = $this->prefix( $this->mTextform
);
673 $s = str_replace( '_', ' ', $s );
674 $this->mPrefixedText
= $s;
676 return $this->mPrefixedText
;
680 * Get the prefixed title with spaces, plus any fragment
681 * (part beginning with '#')
682 * @return \type{\string} the prefixed title, with spaces and
683 * the fragment, including '#'
685 public function getFullText() {
686 $text = $this->getPrefixedText();
687 if( '' != $this->mFragment
) {
688 $text .= '#' . $this->mFragment
;
694 * Get the base name, i.e. the leftmost parts before the /
695 * @return \type{\string} Base name
697 public function getBaseText() {
698 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
699 return $this->getText();
702 $parts = explode( '/', $this->getText() );
703 # Don't discard the real title if there's no subpage involved
704 if( count( $parts ) > 1 )
705 unset( $parts[ count( $parts ) - 1 ] );
706 return implode( '/', $parts );
710 * Get the lowest-level subpage name, i.e. the rightmost part after /
711 * @return \type{\string} Subpage name
713 public function getSubpageText() {
714 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
715 return( $this->mTextform
);
717 $parts = explode( '/', $this->mTextform
);
718 return( $parts[ count( $parts ) - 1 ] );
722 * Get a URL-encoded form of the subpage text
723 * @return \type{\string} URL-encoded subpage name
725 public function getSubpageUrlForm() {
726 $text = $this->getSubpageText();
727 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
728 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
733 * Get a URL-encoded title (not an actual URL) including interwiki
734 * @return \type{\string} the URL-encoded form
736 public function getPrefixedURL() {
737 $s = $this->prefix( $this->mDbkeyform
);
738 $s = str_replace( ' ', '_', $s );
740 $s = wfUrlencode ( $s ) ;
742 # Cleaning up URL to make it look nice -- is this safe?
743 $s = str_replace( '%28', '(', $s );
744 $s = str_replace( '%29', ')', $s );
750 * Get a real URL referring to this title, with interwiki link and
753 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
754 * links. Can be specified as an associative array as well, e.g.,
755 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
756 * @param $variant \type{\string} language variant of url (for sr, zh..)
757 * @return \type{\string} the URL
759 public function getFullURL( $query = '', $variant = false ) {
760 global $wgContLang, $wgServer, $wgRequest;
762 if( is_array( $query ) ) {
763 $query = wfArrayToCGI( $query );
766 if ( '' == $this->mInterwiki
) {
767 $url = $this->getLocalUrl( $query, $variant );
769 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
770 // Correct fix would be to move the prepending elsewhere.
771 if ($wgRequest->getVal('action') != 'render') {
772 $url = $wgServer . $url;
775 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
777 $namespace = wfUrlencode( $this->getNsText() );
778 if ( '' != $namespace ) {
779 # Can this actually happen? Interwikis shouldn't be parsed.
780 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
783 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
784 $url = wfAppendQuery( $url, $query );
787 # Finally, add the fragment.
788 $url .= $this->getFragmentForURL();
790 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
795 * Get a URL with no fragment or server name. If this page is generated
796 * with action=render, $wgServer is prepended.
797 * @param mixed $query an optional query string; if not specified,
798 * $wgArticlePath will be used. Can be specified as an associative array
799 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
801 * @param $variant \type{\string} language variant of url (for sr, zh..)
802 * @return \type{\string} the URL
804 public function getLocalURL( $query = '', $variant = false ) {
805 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
806 global $wgVariantArticlePath, $wgContLang, $wgUser;
808 if( is_array( $query ) ) {
809 $query = wfArrayToCGI( $query );
812 // internal links should point to same variant as current page (only anonymous users)
813 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
814 $pref = $wgContLang->getPreferredVariant(false);
815 if($pref != $wgContLang->getCode())
819 if ( $this->isExternal() ) {
820 $url = $this->getFullURL();
822 // This is currently only used for edit section links in the
823 // context of interwiki transclusion. In theory we should
824 // append the query to the end of any existing query string,
825 // but interwiki transclusion is already broken in that case.
829 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
830 if ( $query == '' ) {
831 if( $variant != false && $wgContLang->hasVariants() ) {
832 if( $wgVariantArticlePath == false ) {
833 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
835 $variantArticlePath = $wgVariantArticlePath;
837 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
838 $url = str_replace( '$1', $dbkey, $url );
840 $url = str_replace( '$1', $dbkey, $wgArticlePath );
843 global $wgActionPaths;
846 if( !empty( $wgActionPaths ) &&
847 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
849 $action = urldecode( $matches[2] );
850 if( isset( $wgActionPaths[$action] ) ) {
851 $query = $matches[1];
852 if( isset( $matches[4] ) ) $query .= $matches[4];
853 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
854 if( $query != '' ) $url .= '?' . $query;
857 if ( $url === false ) {
858 if ( $query == '-' ) {
861 $url = "{$wgScript}?title={$dbkey}&{$query}";
865 // FIXME: this causes breakage in various places when we
866 // actually expected a local URL and end up with dupe prefixes.
867 if ($wgRequest->getVal('action') == 'render') {
868 $url = $wgServer . $url;
871 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
876 * Get a URL that's the simplest URL that will be valid to link, locally,
877 * to the current Title. It includes the fragment, but does not include
878 * the server unless action=render is used (or the link is external). If
879 * there's a fragment but the prefixed text is empty, we just return a link
882 * @param $query \arrayof{\string} An associative array of key => value pairs for the
883 * query string. Keys and values will be escaped.
884 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
885 * for external links. Default is "false" (same variant as current page,
886 * for anonymous users).
887 * @return \type{\string} the URL
889 public function getLinkUrl( $query = array(), $variant = false ) {
890 if( !is_array( $query ) ) {
891 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
894 if( $this->isExternal() ) {
895 return $this->getFullURL( $query );
896 } elseif( $this->getPrefixedText() === ''
897 and $this->getFragment() !== '' ) {
898 return $this->getFragmentForURL();
900 return $this->getLocalURL( $query, $variant )
901 . $this->getFragmentForURL();
906 * Get an HTML-escaped version of the URL form, suitable for
907 * using in a link, without a server name or fragment
908 * @param $query \type{\string} an optional query string
909 * @return \type{\string} the URL
911 public function escapeLocalURL( $query = '' ) {
912 return htmlspecialchars( $this->getLocalURL( $query ) );
916 * Get an HTML-escaped version of the URL form, suitable for
917 * using in a link, including the server name and fragment
919 * @param $query \type{\string} an optional query string
920 * @return \type{\string} the URL
922 public function escapeFullURL( $query = '' ) {
923 return htmlspecialchars( $this->getFullURL( $query ) );
927 * Get the URL form for an internal link.
928 * - Used in various Squid-related code, in case we have a different
929 * internal hostname for the server from the exposed one.
931 * @param $query \type{\string} an optional query string
932 * @param $variant \type{\string} language variant of url (for sr, zh..)
933 * @return \type{\string} the URL
935 public function getInternalURL( $query = '', $variant = false ) {
936 global $wgInternalServer;
937 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
938 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
943 * Get the edit URL for this Title
944 * @return \type{\string} the URL, or a null string if this is an
947 public function getEditURL() {
948 if ( '' != $this->mInterwiki
) { return ''; }
949 $s = $this->getLocalURL( 'action=edit' );
955 * Get the HTML-escaped displayable text form.
956 * Used for the title field in <a> tags.
957 * @return \type{\string} the text, including any prefixes
959 public function getEscapedText() {
960 return htmlspecialchars( $this->getPrefixedText() );
964 * Is this Title interwiki?
965 * @return \type{\bool}
967 public function isExternal() { return ( '' != $this->mInterwiki
); }
970 * Is this page "semi-protected" - the *only* protection is autoconfirm?
972 * @param @action \type{\string} Action to check (default: edit)
973 * @return \type{\bool}
975 public function isSemiProtected( $action = 'edit' ) {
976 if( $this->exists() ) {
977 $restrictions = $this->getRestrictions( $action );
978 if( count( $restrictions ) > 0 ) {
979 foreach( $restrictions as $restriction ) {
980 if( strtolower( $restriction ) != 'autoconfirmed' )
989 # If it doesn't exist, it can't be protected
995 * Does the title correspond to a protected article?
996 * @param $what \type{\string} the action the page is protected from,
997 * by default checks move and edit
998 * @return \type{\bool}
1000 public function isProtected( $action = '' ) {
1001 global $wgRestrictionLevels, $wgRestrictionTypes;
1003 # Special pages have inherent protection
1004 if( $this->getNamespace() == NS_SPECIAL
)
1007 # Check regular protection levels
1008 foreach( $wgRestrictionTypes as $type ){
1009 if( $action == $type ||
$action == '' ) {
1010 $r = $this->getRestrictions( $type );
1011 foreach( $wgRestrictionLevels as $level ) {
1012 if( in_array( $level, $r ) && $level != '' ) {
1023 * Is $wgUser watching this page?
1024 * @return \type{\bool}
1026 public function userIsWatching() {
1029 if ( is_null( $this->mWatched
) ) {
1030 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1031 $this->mWatched
= false;
1033 $this->mWatched
= $wgUser->isWatched( $this );
1036 return $this->mWatched
;
1040 * Can $wgUser perform $action on this page?
1041 * This skips potentially expensive cascading permission checks.
1043 * Suitable for use for nonessential UI controls in common cases, but
1044 * _not_ for functional access control.
1046 * May provide false positives, but should never provide a false negative.
1048 * @param $action \type{\string} action that permission needs to be checked for
1049 * @return \type{\bool}
1051 public function quickUserCan( $action ) {
1052 return $this->userCan( $action, false );
1056 * Determines if $wgUser is unable to edit this page because it has been protected
1057 * by $wgNamespaceProtection.
1059 * @return \type{\bool}
1061 public function isNamespaceProtected() {
1062 global $wgNamespaceProtection, $wgUser;
1063 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1064 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1065 if( $right != '' && !$wgUser->isAllowed( $right ) )
1073 * Can $wgUser perform $action on this page?
1074 * @param \type{\string} $action action that permission needs to be checked for
1075 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1076 * @return \type{\bool}
1078 public function userCan( $action, $doExpensiveQueries = true ) {
1080 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1084 * Can $user perform $action on this page?
1086 * FIXME: This *does not* check throttles (User::pingLimiter()).
1088 * @param $action \type{\string}action that permission needs to be checked for
1089 * @param $user \type{User} user to check
1090 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1091 * @param $ignoreErrors \arrayof{\string} Set this to a list of message keys whose corresponding errors may be ignored.
1092 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1094 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1095 if( !StubObject
::isRealObject( $user ) ) {
1096 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1098 $wgUser->_unstub( '', 5 );
1101 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1105 global $wgEmailConfirmToEdit;
1107 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1108 $errors[] = array( 'confirmedittext' );
1111 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1112 $block = $user->mBlock
;
1114 // This is from OutputPage::blockedPage
1115 // Copied at r23888 by werdna
1117 $id = $user->blockedBy();
1118 $reason = $user->blockedFor();
1119 if( $reason == '' ) {
1120 $reason = wfMsg( 'blockednoreason' );
1124 if ( is_numeric( $id ) ) {
1125 $name = User
::whoIs( $id );
1130 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1131 $blockid = $block->mId
;
1132 $blockExpiry = $user->mBlock
->mExpiry
;
1133 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1135 if ( $blockExpiry == 'infinity' ) {
1136 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1137 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1139 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1140 if ( strpos( $option, ':' ) == false )
1143 list ($show, $value) = explode( ":", $option );
1145 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1146 $blockExpiry = $show;
1151 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1154 $intended = $user->mBlock
->mAddress
;
1156 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1157 $blockid, $blockExpiry, $intended, $blockTimestamp );
1160 // Remove the errors being ignored.
1162 foreach( $errors as $index => $error ) {
1163 $error_key = is_array($error) ?
$error[0] : $error;
1165 if (in_array( $error_key, $ignoreErrors )) {
1166 unset($errors[$index]);
1174 * Can $user perform $action on this page? This is an internal function,
1175 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1176 * checks on wfReadOnly() and blocks)
1178 * @param $action \type{\string} action that permission needs to be checked for
1179 * @param $user \type{User} user to check
1180 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1181 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1183 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1184 wfProfileIn( __METHOD__
);
1188 // Use getUserPermissionsErrors instead
1189 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1190 wfProfileOut( __METHOD__
);
1191 return $result ?
array() : array( array( 'badaccess-group0' ) );
1194 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1195 if ($result != array() && is_array($result) && !is_array($result[0]))
1196 $errors[] = $result; # A single array representing an error
1197 else if (is_array($result) && is_array($result[0]))
1198 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1199 else if ($result != '' && $result != null && $result !== true && $result !== false)
1200 $errors[] = array($result); # A string representing a message-id
1201 else if ($result === false )
1202 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1204 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1205 if ($result != array() && is_array($result) && !is_array($result[0]))
1206 $errors[] = $result; # A single array representing an error
1207 else if (is_array($result) && is_array($result[0]))
1208 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1209 else if ($result != '' && $result != null && $result !== true && $result !== false)
1210 $errors[] = array($result); # A string representing a message-id
1211 else if ($result === false )
1212 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1215 $specialOKActions = array( 'createaccount', 'execute' );
1216 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1217 $errors[] = array('ns-specialprotected');
1220 if ( $this->isNamespaceProtected() ) {
1221 $ns = $this->getNamespace() == NS_MAIN
1222 ?
wfMsg( 'nstab-main' )
1223 : $this->getNsText();
1224 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1225 ?
array('protectedinterface')
1226 : array( 'namespaceprotected', $ns ) );
1229 if( $this->mDbkeyform
== '_' ) {
1230 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1231 $errors[] = array('badaccess-group0');
1234 # protect css/js subpages of user pages
1235 # XXX: this might be better using restrictions
1236 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1237 if( $this->isCssJsSubpage()
1238 && !$user->isAllowed('editusercssjs')
1239 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1240 $errors[] = array('customcssjsprotected');
1243 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1244 # We /could/ use the protection level on the source page, but it's fairly ugly
1245 # as we have to establish a precedence hierarchy for pages included by multiple
1246 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1247 # as they could remove the protection anyway.
1248 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1249 # Cascading protection depends on more than this page...
1250 # Several cascading protected pages may include this page...
1251 # Check each cascading level
1252 # This is only for protection restrictions, not for all actions
1253 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1254 foreach( $restrictions[$action] as $right ) {
1255 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1256 if( '' != $right && !$user->isAllowed( $right ) ) {
1258 foreach( $cascadingSources as $page )
1259 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1260 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1266 foreach( $this->getRestrictions($action) as $right ) {
1267 // Backwards compatibility, rewrite sysop -> protect
1268 if ( $right == 'sysop' ) {
1271 if( '' != $right && !$user->isAllowed( $right ) ) {
1272 //Users with 'editprotected' permission can edit protected pages
1273 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1274 //Users with 'editprotected' permission cannot edit protected pages
1275 //with cascading option turned on.
1276 if($this->mCascadeRestriction
) {
1277 $errors[] = array( 'protectedpagetext', $right );
1279 //Nothing, user can edit!
1282 $errors[] = array( 'protectedpagetext', $right );
1287 if ($action == 'protect') {
1288 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1289 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1293 if ($action == 'create') {
1294 $title_protection = $this->getTitleProtection();
1296 if (is_array($title_protection)) {
1297 extract($title_protection);
1299 if ($pt_create_perm == 'sysop')
1300 $pt_create_perm = 'protect';
1302 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1303 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1307 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1308 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1309 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1311 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1312 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1313 } elseif ( !$user->isAllowed( $action ) ) {
1315 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1316 User
::getGroupsWithPermission( $action ) );
1318 $return = array( 'badaccess-groups',
1320 implode( ', ', $groups ),
1321 count( $groups ) ) );
1324 $return = array( "badaccess-group0" );
1326 $errors[] = $return;
1329 wfProfileOut( __METHOD__
);
1334 * Is this title subject to title protection?
1335 * @return \type{\mixed} An associative array representing any existent title
1336 * protection, or false if there's none.
1338 private function getTitleProtection() {
1339 // Can't protect pages in special namespaces
1340 if ( $this->getNamespace() < 0 ) {
1344 $dbr = wfGetDB( DB_SLAVE
);
1345 $res = $dbr->select( 'protected_titles', '*',
1346 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1348 if ($row = $dbr->fetchRow( $res )) {
1356 * Update the title protection status
1357 * @param $create_perm \type{\string} Permission required for creation
1358 * @param $reason \type{\string} Reason for protection
1359 * @param $expiry \type{\string} Expiry timestamp
1361 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1362 global $wgUser,$wgContLang;
1364 if ($create_perm == implode(',',$this->getRestrictions('create'))
1365 && $expiry == $this->mRestrictionsExpiry
) {
1370 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1372 $dbw = wfGetDB( DB_MASTER
);
1374 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1376 $expiry_description = '';
1377 if ( $encodedExpiry != 'infinity' ) {
1378 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1381 # Update protection table
1382 if ($create_perm != '' ) {
1383 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1384 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1385 , 'pt_create_perm' => $create_perm
1386 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1387 , 'pt_expiry' => $encodedExpiry
1388 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1390 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1391 'pt_title' => $title ), __METHOD__
);
1393 # Update the protection log
1394 $log = new LogPage( 'protect' );
1396 if( $create_perm ) {
1397 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1399 $log->addEntry( 'unprotect', $this, $reason );
1406 * Remove any title protection due to page existing
1408 public function deleteTitleProtection() {
1409 $dbw = wfGetDB( DB_MASTER
);
1411 $dbw->delete( 'protected_titles',
1412 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1416 * Can $wgUser edit this page?
1417 * @return \type{\bool} TRUE or FALSE
1418 * @deprecated use userCan('edit')
1420 public function userCanEdit( $doExpensiveQueries = true ) {
1421 return $this->userCan( 'edit', $doExpensiveQueries );
1425 * Can $wgUser create this page?
1426 * @return \type{\bool} TRUE or FALSE
1427 * @deprecated use userCan('create')
1429 public function userCanCreate( $doExpensiveQueries = true ) {
1430 return $this->userCan( 'create', $doExpensiveQueries );
1434 * Can $wgUser move this page?
1435 * @return \type{\bool} TRUE or FALSE
1436 * @deprecated use userCan('move')
1438 public function userCanMove( $doExpensiveQueries = true ) {
1439 return $this->userCan( 'move', $doExpensiveQueries );
1443 * Would anybody with sufficient privileges be able to move this page?
1444 * Some pages just aren't movable.
1446 * @return \type{\bool} TRUE or FALSE
1448 public function isMovable() {
1449 return MWNamespace
::isMovable( $this->getNamespace() )
1450 && $this->getInterwiki() == '';
1454 * Can $wgUser read this page?
1455 * @return \type{\bool} TRUE or FALSE
1456 * @todo fold these checks into userCan()
1458 public function userCanRead() {
1459 global $wgUser, $wgGroupPermissions;
1462 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1463 if ( $result !== null ) {
1467 # Shortcut for public wikis, allows skipping quite a bit of code
1468 if ($wgGroupPermissions['*']['read'])
1471 if( $wgUser->isAllowed( 'read' ) ) {
1474 global $wgWhitelistRead;
1477 * Always grant access to the login page.
1478 * Even anons need to be able to log in.
1480 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1485 * Bail out if there isn't whitelist
1487 if( !is_array($wgWhitelistRead) ) {
1492 * Check for explicit whitelisting
1494 $name = $this->getPrefixedText();
1495 $dbName = $this->getPrefixedDBKey();
1496 // Check with and without underscores
1497 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1501 * Old settings might have the title prefixed with
1502 * a colon for main-namespace pages
1504 if( $this->getNamespace() == NS_MAIN
) {
1505 if( in_array( ':' . $name, $wgWhitelistRead ) )
1510 * If it's a special page, ditch the subpage bit
1513 if( $this->getNamespace() == NS_SPECIAL
) {
1514 $name = $this->getDBkey();
1515 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1516 if ( $name === false ) {
1517 # Invalid special page, but we show standard login required message
1521 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1522 if( in_array( $pure, $wgWhitelistRead, true ) )
1531 * Is this a talk page of some sort?
1532 * @return \type{\bool} TRUE or FALSE
1534 public function isTalkPage() {
1535 return MWNamespace
::isTalk( $this->getNamespace() );
1539 * Is this a subpage?
1540 * @return \type{\bool} TRUE or FALSE
1542 public function isSubpage() {
1543 return MWNamespace
::hasSubpages( $this->mNamespace
)
1544 ?
strpos( $this->getText(), '/' ) !== false
1549 * Does this have subpages? (Warning, usually requires an extra DB query.)
1550 * @return \type{\bool} TRUE or FALSE
1552 public function hasSubpages() {
1553 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1558 # We dynamically add a member variable for the purpose of this method
1559 # alone to cache the result. There's no point in having it hanging
1560 # around uninitialized in every Title object; therefore we only add it
1561 # if needed and don't declare it statically.
1562 if( isset( $this->mHasSubpages
) ) {
1563 return $this->mHasSubpages
;
1566 $db = wfGetDB( DB_SLAVE
);
1567 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1568 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1569 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1575 * Could this page contain custom CSS or JavaScript, based
1578 * @return \type{\bool} TRUE or FALSE
1580 public function isCssOrJsPage() {
1581 return $this->mNamespace
== NS_MEDIAWIKI
1582 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1586 * Is this a .css or .js subpage of a user page?
1587 * @return \type{\bool} TRUE or FALSE
1589 public function isCssJsSubpage() {
1590 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1593 * Is this a *valid* .css or .js subpage of a user page?
1594 * Check that the corresponding skin exists
1595 * @return \type{\bool} TRUE or FALSE
1597 public function isValidCssJsSubpage() {
1598 if ( $this->isCssJsSubpage() ) {
1599 $skinNames = Skin
::getSkinNames();
1600 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1606 * Trim down a .css or .js subpage title to get the corresponding skin name
1608 public function getSkinFromCssJsSubpage() {
1609 $subpage = explode( '/', $this->mTextform
);
1610 $subpage = $subpage[ count( $subpage ) - 1 ];
1611 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1614 * Is this a .css subpage of a user page?
1615 * @return \type{\bool} TRUE or FALSE
1617 public function isCssSubpage() {
1618 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1621 * Is this a .js subpage of a user page?
1622 * @return \type{\bool} TRUE or FALSE
1624 public function isJsSubpage() {
1625 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1628 * Protect css/js subpages of user pages: can $wgUser edit
1631 * @return \type{\bool} TRUE or FALSE
1632 * @todo XXX: this might be better using restrictions
1634 public function userCanEditCssJsSubpage() {
1636 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1640 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1642 * @return \type{\bool} If the page is subject to cascading restrictions.
1644 public function isCascadeProtected() {
1645 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1646 return ( $sources > 0 );
1650 * Cascading protection: Get the source of any cascading restrictions on this page.
1652 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1653 * @return \arrayof{mixed title array, restriction array} Array of the Title objects of the pages from
1654 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1655 * The restriction array is an array of each type, each of which contains an array of unique groups.
1657 public function getCascadeProtectionSources( $get_pages = true ) {
1658 global $wgRestrictionTypes;
1660 # Define our dimension of restrictions types
1661 $pagerestrictions = array();
1662 foreach( $wgRestrictionTypes as $action )
1663 $pagerestrictions[$action] = array();
1665 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1666 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1667 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1668 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1671 wfProfileIn( __METHOD__
);
1673 $dbr = wfGetDb( DB_SLAVE
);
1675 if ( $this->getNamespace() == NS_IMAGE
) {
1676 $tables = array ('imagelinks', 'page_restrictions');
1677 $where_clauses = array(
1678 'il_to' => $this->getDBkey(),
1680 'pr_cascade' => 1 );
1682 $tables = array ('templatelinks', 'page_restrictions');
1683 $where_clauses = array(
1684 'tl_namespace' => $this->getNamespace(),
1685 'tl_title' => $this->getDBkey(),
1687 'pr_cascade' => 1 );
1691 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1692 $where_clauses[] = 'page_id=pr_page';
1695 $cols = array( 'pr_expiry' );
1698 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1700 $sources = $get_pages ?
array() : false;
1701 $now = wfTimestampNow();
1702 $purgeExpired = false;
1704 foreach( $res as $row ) {
1705 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1706 if( $expiry > $now ) {
1708 $page_id = $row->pr_page
;
1709 $page_ns = $row->page_namespace
;
1710 $page_title = $row->page_title
;
1711 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1712 # Add groups needed for each restriction type if its not already there
1713 # Make sure this restriction type still exists
1714 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1715 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1721 // Trigger lazy purge of expired restrictions from the db
1722 $purgeExpired = true;
1725 if( $purgeExpired ) {
1726 Title
::purgeExpiredRestrictions();
1729 wfProfileOut( __METHOD__
);
1732 $this->mCascadeSources
= $sources;
1733 $this->mCascadingRestrictions
= $pagerestrictions;
1735 $this->mHasCascadingRestrictions
= $sources;
1738 return array( $sources, $pagerestrictions );
1741 function areRestrictionsCascading() {
1742 if (!$this->mRestrictionsLoaded
) {
1743 $this->loadRestrictions();
1746 return $this->mCascadeRestriction
;
1750 * Loads a string into mRestrictions array
1751 * @param $res \type{Resource} restrictions as an SQL result.
1753 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1754 global $wgRestrictionTypes;
1755 $dbr = wfGetDB( DB_SLAVE
);
1757 foreach( $wgRestrictionTypes as $type ){
1758 $this->mRestrictions
[$type] = array();
1761 $this->mCascadeRestriction
= false;
1762 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1764 # Backwards-compatibility: also load the restrictions from the page record (old format).
1766 if ( $oldFashionedRestrictions === NULL ) {
1767 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1768 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1771 if ($oldFashionedRestrictions != '') {
1773 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1774 $temp = explode( '=', trim( $restrict ) );
1775 if(count($temp) == 1) {
1776 // old old format should be treated as edit/move restriction
1777 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1778 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1780 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1784 $this->mOldRestrictions
= true;
1788 if( $dbr->numRows( $res ) ) {
1789 # Current system - load second to make them override.
1790 $now = wfTimestampNow();
1791 $purgeExpired = false;
1793 foreach( $res as $row ) {
1794 # Cycle through all the restrictions.
1796 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1797 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1800 // This code should be refactored, now that it's being used more generally,
1801 // But I don't really see any harm in leaving it in Block for now -werdna
1802 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1804 // Only apply the restrictions if they haven't expired!
1805 if ( !$expiry ||
$expiry > $now ) {
1806 $this->mRestrictionsExpiry
= $expiry;
1807 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1809 $this->mCascadeRestriction |
= $row->pr_cascade
;
1811 // Trigger a lazy purge of expired restrictions
1812 $purgeExpired = true;
1816 if( $purgeExpired ) {
1817 Title
::purgeExpiredRestrictions();
1821 $this->mRestrictionsLoaded
= true;
1825 * Load restrictions from the page_restrictions table
1827 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1828 if( !$this->mRestrictionsLoaded
) {
1829 if ($this->exists()) {
1830 $dbr = wfGetDB( DB_SLAVE
);
1832 $res = $dbr->select( 'page_restrictions', '*',
1833 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1835 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1837 $title_protection = $this->getTitleProtection();
1839 if (is_array($title_protection)) {
1840 extract($title_protection);
1842 $now = wfTimestampNow();
1843 $expiry = Block
::decodeExpiry($pt_expiry);
1845 if (!$expiry ||
$expiry > $now) {
1846 // Apply the restrictions
1847 $this->mRestrictionsExpiry
= $expiry;
1848 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1849 } else { // Get rid of the old restrictions
1850 Title
::purgeExpiredRestrictions();
1853 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1855 $this->mRestrictionsLoaded
= true;
1861 * Purge expired restrictions from the page_restrictions table
1863 static function purgeExpiredRestrictions() {
1864 $dbw = wfGetDB( DB_MASTER
);
1865 $dbw->delete( 'page_restrictions',
1866 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1869 $dbw->delete( 'protected_titles',
1870 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1875 * Accessor/initialisation for mRestrictions
1877 * @param $action \type{\string} action that permission needs to be checked for
1878 * @return \arrayof{\string} the array of groups allowed to edit this article
1880 public function getRestrictions( $action ) {
1881 if( !$this->mRestrictionsLoaded
) {
1882 $this->loadRestrictions();
1884 return isset( $this->mRestrictions
[$action] )
1885 ?
$this->mRestrictions
[$action]
1890 * Is there a version of this page in the deletion archive?
1891 * @return \type{\int} the number of archived revisions
1893 public function isDeleted() {
1894 $fname = 'Title::isDeleted';
1895 if ( $this->getNamespace() < 0 ) {
1898 $dbr = wfGetDB( DB_SLAVE
);
1899 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1900 'ar_title' => $this->getDBkey() ), $fname );
1901 if( $this->getNamespace() == NS_IMAGE
) {
1902 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1903 array( 'fa_name' => $this->getDBkey() ), $fname );
1910 * Get the article ID for this Title from the link cache,
1911 * adding it if necessary
1912 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1914 * @return \type{\int} the ID
1916 public function getArticleID( $flags = 0 ) {
1917 $linkCache = LinkCache
::singleton();
1918 if ( $flags & GAID_FOR_UPDATE
) {
1919 $oldUpdate = $linkCache->forUpdate( true );
1920 $this->mArticleID
= $linkCache->addLinkObj( $this );
1921 $linkCache->forUpdate( $oldUpdate );
1923 if ( -1 == $this->mArticleID
) {
1924 $this->mArticleID
= $linkCache->addLinkObj( $this );
1927 return $this->mArticleID
;
1931 * Is this an article that is a redirect page?
1932 * Uses link cache, adding it if necessary
1933 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1934 * @return \type{\bool}
1936 public function isRedirect( $flags = 0 ) {
1937 if( !is_null($this->mRedirect
) )
1938 return $this->mRedirect
;
1939 # Zero for special pages.
1940 # Also, calling getArticleID() loads the field from cache!
1941 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1944 $linkCache = LinkCache
::singleton();
1945 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1947 return $this->mRedirect
;
1951 * What is the length of this page?
1952 * Uses link cache, adding it if necessary
1953 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1954 * @return \type{\bool}
1956 public function getLength( $flags = 0 ) {
1957 if( $this->mLength
!= -1 )
1958 return $this->mLength
;
1959 # Zero for special pages.
1960 # Also, calling getArticleID() loads the field from cache!
1961 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1964 $linkCache = LinkCache
::singleton();
1965 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1967 return $this->mLength
;
1971 * What is the page_latest field for this page?
1972 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1973 * @return \type{\int}
1975 public function getLatestRevID( $flags = 0 ) {
1976 if ($this->mLatestID
!== false)
1977 return $this->mLatestID
;
1979 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1980 return $this->mLatestID
= $db->selectField( 'revision',
1982 array('rev_page' => $this->getArticleID($flags)),
1983 'Title::getLatestRevID' );
1987 * This clears some fields in this object, and clears any associated
1988 * keys in the "bad links" section of the link cache.
1990 * - This is called from Article::insertNewArticle() to allow
1991 * loading of the new page_id. It's also called from
1992 * Article::doDeleteArticle()
1994 * @param $newid \type{\int} the new Article ID
1996 public function resetArticleID( $newid ) {
1997 $linkCache = LinkCache
::singleton();
1998 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2000 if ( 0 == $newid ) { $this->mArticleID
= -1; }
2001 else { $this->mArticleID
= $newid; }
2002 $this->mRestrictionsLoaded
= false;
2003 $this->mRestrictions
= array();
2007 * Updates page_touched for this page; called from LinksUpdate.php
2008 * @return \type{\bool} true if the update succeded
2010 public function invalidateCache() {
2011 global $wgUseFileCache;
2013 if ( wfReadOnly() ) {
2017 $dbw = wfGetDB( DB_MASTER
);
2018 $success = $dbw->update( 'page',
2020 'page_touched' => $dbw->timestamp()
2021 ), array( /* WHERE */
2022 'page_namespace' => $this->getNamespace() ,
2023 'page_title' => $this->getDBkey()
2024 ), 'Title::invalidateCache'
2027 if ($wgUseFileCache) {
2028 $cache = new HTMLFileCache($this);
2029 @unlink
($cache->fileCacheName());
2036 * Prefix some arbitrary text with the namespace or interwiki prefix
2039 * @param $name \type{\string} the text
2040 * @return \type{\string} the prefixed text
2043 /* private */ function prefix( $name ) {
2045 if ( '' != $this->mInterwiki
) {
2046 $p = $this->mInterwiki
. ':';
2048 if ( 0 != $this->mNamespace
) {
2049 $p .= $this->getNsText() . ':';
2055 * Secure and split - main initialisation function for this object
2057 * Assumes that mDbkeyform has been set, and is urldecoded
2058 * and uses underscores, but not otherwise munged. This function
2059 * removes illegal characters, splits off the interwiki and
2060 * namespace prefixes, sets the other forms, and canonicalizes
2062 * @return \type{\bool} true on success
2064 private function secureAndSplit() {
2065 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2068 static $rxTc = false;
2070 # Matching titles will be held as illegal.
2072 # Any character not allowed is forbidden...
2073 '[^' . Title
::legalChars() . ']' .
2074 # URL percent encoding sequences interfere with the ability
2075 # to round-trip titles -- you can't link to them consistently.
2076 '|%[0-9A-Fa-f]{2}' .
2077 # XML/HTML character references produce similar issues.
2078 '|&[A-Za-z0-9\x80-\xff]+;' .
2080 '|&#x[0-9A-Fa-f]+;' .
2084 $this->mInterwiki
= $this->mFragment
= '';
2085 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2087 $dbkey = $this->mDbkeyform
;
2089 # Strip Unicode bidi override characters.
2090 # Sometimes they slip into cut-n-pasted page titles, where the
2091 # override chars get included in list displays.
2092 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2093 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2095 # Clean up whitespace
2097 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2098 $dbkey = trim( $dbkey, '_' );
2100 if ( '' == $dbkey ) {
2104 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2105 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2109 $this->mDbkeyform
= $dbkey;
2111 # Initial colon indicates main namespace rather than specified default
2112 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2113 if ( ':' == $dbkey{0} ) {
2114 $this->mNamespace
= NS_MAIN
;
2115 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2116 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2119 # Namespace or interwiki prefix
2123 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2125 if ( $ns = $wgContLang->getNsIndex( $p )) {
2126 # Ordinary namespace
2128 $this->mNamespace
= $ns;
2129 } elseif( $this->getInterwikiLink( $p ) ) {
2131 # Can't make a local interwiki link to an interwiki link.
2132 # That's just crazy!
2138 $this->mInterwiki
= $wgContLang->lc( $p );
2140 # Redundant interwiki prefix to the local wiki
2141 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2142 if( $dbkey == '' ) {
2143 # Can't have an empty self-link
2146 $this->mInterwiki
= '';
2148 # Do another namespace split...
2152 # If there's an initial colon after the interwiki, that also
2153 # resets the default namespace
2154 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2155 $this->mNamespace
= NS_MAIN
;
2156 $dbkey = substr( $dbkey, 1 );
2159 # If there's no recognized interwiki or namespace,
2160 # then let the colon expression be part of the title.
2165 # We already know that some pages won't be in the database!
2167 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2168 $this->mArticleID
= 0;
2170 $fragment = strstr( $dbkey, '#' );
2171 if ( false !== $fragment ) {
2172 $this->setFragment( $fragment );
2173 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2174 # remove whitespace again: prevents "Foo_bar_#"
2175 # becoming "Foo_bar_"
2176 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2179 # Reject illegal characters.
2181 if( preg_match( $rxTc, $dbkey ) ) {
2186 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2187 * reachable due to the way web browsers deal with 'relative' URLs.
2188 * Also, they conflict with subpage syntax. Forbid them explicitly.
2190 if ( strpos( $dbkey, '.' ) !== false &&
2191 ( $dbkey === '.' ||
$dbkey === '..' ||
2192 strpos( $dbkey, './' ) === 0 ||
2193 strpos( $dbkey, '../' ) === 0 ||
2194 strpos( $dbkey, '/./' ) !== false ||
2195 strpos( $dbkey, '/../' ) !== false ||
2196 substr( $dbkey, -2 ) == '/.' ||
2197 substr( $dbkey, -3 ) == '/..' ) )
2203 * Magic tilde sequences? Nu-uh!
2205 if( strpos( $dbkey, '~~~' ) !== false ) {
2210 * Limit the size of titles to 255 bytes.
2211 * This is typically the size of the underlying database field.
2212 * We make an exception for special pages, which don't need to be stored
2213 * in the database, and may edge over 255 bytes due to subpage syntax
2214 * for long titles, e.g. [[Special:Block/Long name]]
2216 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2217 strlen( $dbkey ) > 512 )
2223 * Normally, all wiki links are forced to have
2224 * an initial capital letter so [[foo]] and [[Foo]]
2225 * point to the same place.
2227 * Don't force it for interwikis, since the other
2228 * site might be case-sensitive.
2230 $this->mUserCaseDBKey
= $dbkey;
2231 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2232 $dbkey = $wgContLang->ucfirst( $dbkey );
2236 * Can't make a link to a namespace alone...
2237 * "empty" local links can only be self-links
2238 * with a fragment identifier.
2241 $this->mInterwiki
== '' &&
2242 $this->mNamespace
!= NS_MAIN
) {
2245 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2246 // IP names are not allowed for accounts, and can only be referring to
2247 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2248 // there are numerous ways to present the same IP. Having sp:contribs scan
2249 // them all is silly and having some show the edits and others not is
2250 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2251 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2252 IP
::sanitizeIP( $dbkey ) : $dbkey;
2253 // Any remaining initial :s are illegal.
2254 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2259 $this->mDbkeyform
= $dbkey;
2260 $this->mUrlform
= wfUrlencode( $dbkey );
2262 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2268 * Set the fragment for this title
2269 * This is kind of bad, since except for this rarely-used function, Title objects
2270 * are immutable. The reason this is here is because it's better than setting the
2271 * members directly, which is what Linker::formatComment was doing previously.
2273 * @param $fragment \type{\string} text
2274 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2276 public function setFragment( $fragment ) {
2277 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2281 * Get a Title object associated with the talk page of this article
2282 * @return \type{Title} the object for the talk page
2284 public function getTalkPage() {
2285 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2289 * Get a title object associated with the subject page of this
2292 * @return \type{Title} the object for the subject page
2294 public function getSubjectPage() {
2295 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2299 * Get an array of Title objects linking to this Title
2300 * Also stores the IDs in the link cache.
2302 * WARNING: do not use this function on arbitrary user-supplied titles!
2303 * On heavily-used templates it will max out the memory.
2305 * @param $options \type{\string} may be FOR UPDATE
2306 * @return \arrayof{Title} the Title objects linking here
2308 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2309 $linkCache = LinkCache
::singleton();
2312 $db = wfGetDB( DB_MASTER
);
2314 $db = wfGetDB( DB_SLAVE
);
2317 $res = $db->select( array( 'page', $table ),
2318 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2320 "{$prefix}_from=page_id",
2321 "{$prefix}_namespace" => $this->getNamespace(),
2322 "{$prefix}_title" => $this->getDBkey() ),
2327 if ( $db->numRows( $res ) ) {
2328 foreach( $res as $row ) {
2329 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2330 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2331 $retVal[] = $titleObj;
2335 $db->freeResult( $res );
2340 * Get an array of Title objects using this Title as a template
2341 * Also stores the IDs in the link cache.
2343 * WARNING: do not use this function on arbitrary user-supplied titles!
2344 * On heavily-used templates it will max out the memory.
2346 * @param $options \type{\string} may be FOR UPDATE
2347 * @return \arrayof{Title} the Title objects linking here
2349 public function getTemplateLinksTo( $options = '' ) {
2350 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2354 * Get an array of Title objects referring to non-existent articles linked from this page
2356 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2357 * @param $options \type{\string} may be FOR UPDATE
2358 * @return \arrayof{Title} the Title objects
2360 public function getBrokenLinksFrom( $options = '' ) {
2361 if ( $this->getArticleId() == 0 ) {
2362 # All links from article ID 0 are false positives
2367 $db = wfGetDB( DB_MASTER
);
2369 $db = wfGetDB( DB_SLAVE
);
2372 $res = $db->safeQuery(
2373 "SELECT pl_namespace, pl_title
2376 ON pl_namespace=page_namespace
2377 AND pl_title=page_title
2379 AND page_namespace IS NULL
2381 $db->tableName( 'pagelinks' ),
2382 $db->tableName( 'page' ),
2383 $this->getArticleId(),
2387 if ( $db->numRows( $res ) ) {
2388 foreach( $res as $row ) {
2389 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2392 $db->freeResult( $res );
2398 * Get a list of URLs to purge from the Squid cache when this
2401 * @return \arrayof{\string} the URLs
2403 public function getSquidURLs() {
2407 $this->getInternalURL(),
2408 $this->getInternalURL( 'action=history' )
2411 // purge variant urls as well
2412 if($wgContLang->hasVariants()){
2413 $variants = $wgContLang->getVariants();
2414 foreach($variants as $vCode){
2415 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2416 $urls[] = $this->getInternalURL('',$vCode);
2424 * Purge all applicable Squid URLs
2426 public function purgeSquid() {
2428 if ( $wgUseSquid ) {
2429 $urls = $this->getSquidURLs();
2430 $u = new SquidUpdate( $urls );
2436 * Move this page without authentication
2437 * @param &$nt \type{Title} the new page Title
2439 public function moveNoAuth( &$nt ) {
2440 return $this->moveTo( $nt, false );
2444 * Check whether a given move operation would be valid.
2445 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2446 * @param &$nt \type{Title} the new title
2447 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2449 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2450 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2452 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2455 // Normally we'd add this to $errors, but we'll get
2456 // lots of syntax errors if $nt is not an object
2457 return array(array('badtitletext'));
2459 if( $this->equals( $nt ) ) {
2460 $errors[] = array('selfmove');
2462 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2463 $errors[] = array('immobile_namespace');
2466 $oldid = $this->getArticleID();
2467 $newid = $nt->getArticleID();
2469 if ( strlen( $nt->getDBkey() ) < 1 ) {
2470 $errors[] = array('articleexists');
2472 if ( ( '' == $this->getDBkey() ) ||
2474 ( '' == $nt->getDBkey() ) ) {
2475 $errors[] = array('badarticleerror');
2478 // Image-specific checks
2479 if( $this->getNamespace() == NS_IMAGE
) {
2480 $file = wfLocalFile( $this );
2481 if( $file->exists() ) {
2482 if( $nt->getNamespace() != NS_IMAGE
) {
2483 $errors[] = array('imagenocrossnamespace');
2485 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2486 $errors[] = array('imageinvalidfilename');
2488 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2489 $errors[] = array('imagetypemismatch');
2496 $errors = array_merge($errors,
2497 $this->getUserPermissionsErrors('move', $wgUser),
2498 $this->getUserPermissionsErrors('edit', $wgUser),
2499 $nt->getUserPermissionsErrors('move', $wgUser),
2500 $nt->getUserPermissionsErrors('edit', $wgUser));
2505 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2506 $errors[] = array('hookaborted', $err);
2509 # The move is allowed only if (1) the target doesn't exist, or
2510 # (2) the target is a redirect to the source, and has no history
2511 # (so we can undo bad moves right after they're done).
2513 if ( 0 != $newid ) { # Target exists; check for validity
2514 if ( ! $this->isValidMoveTarget( $nt ) ) {
2515 $errors[] = array('articleexists');
2518 $tp = $nt->getTitleProtection();
2519 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2520 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2521 $errors[] = array('cantmove-titleprotected');
2530 * Move a title to a new location
2531 * @param &$nt \type{Title} the new title
2532 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2534 * @param $reason \type{\string} The reason for the move
2535 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2536 * Ignored if the user doesn't have the suppressredirect right.
2537 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2539 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2540 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2541 if( is_array( $err ) ) {
2545 $pageid = $this->getArticleID();
2546 if( $nt->exists() ) {
2547 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2548 $pageCountChange = ($createRedirect ?
0 : -1);
2549 } else { # Target didn't exist, do normal move.
2550 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2551 $pageCountChange = ($createRedirect ?
1 : 0);
2554 if( is_array( $err ) ) {
2557 $redirid = $this->getArticleID();
2559 // Category memberships include a sort key which may be customized.
2560 // If it's left as the default (the page title), we need to update
2561 // the sort key to match the new title.
2563 // Be careful to avoid resetting cl_timestamp, which may disturb
2564 // time-based lists on some sites.
2566 // Warning -- if the sort key is *explicitly* set to the old title,
2567 // we can't actually distinguish it from a default here, and it'll
2568 // be set to the new title even though it really shouldn't.
2569 // It'll get corrected on the next edit, but resetting cl_timestamp.
2570 $dbw = wfGetDB( DB_MASTER
);
2571 $dbw->update( 'categorylinks',
2573 'cl_sortkey' => $nt->getPrefixedText(),
2574 'cl_timestamp=cl_timestamp' ),
2576 'cl_from' => $pageid,
2577 'cl_sortkey' => $this->getPrefixedText() ),
2582 $oldnamespace = $this->getNamespace() & ~
1;
2583 $newnamespace = $nt->getNamespace() & ~
1;
2584 $oldtitle = $this->getDBkey();
2585 $newtitle = $nt->getDBkey();
2587 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2588 WatchedItem
::duplicateEntries( $this, $nt );
2591 # Update search engine
2592 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2594 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2598 if( $this->isContentPage() && !$nt->isContentPage() ) {
2599 # No longer a content page
2600 # Not viewed, edited, removing
2601 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2602 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2603 # Now a content page
2604 # Not viewed, edited, adding
2605 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2606 } elseif( $pageCountChange ) {
2608 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2615 # Update message cache for interface messages
2616 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2617 global $wgMessageCache;
2618 $oldarticle = new Article( $this );
2619 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2620 $newarticle = new Article( $nt );
2621 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2625 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2630 * Move page to a title which is at present a redirect to the
2633 * @param &$nt \type{Title} the page to move to, which should currently
2635 * @param $reason \type{\string} The reason for the move
2636 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2637 * Ignored if the user doesn't have the suppressredirect right
2639 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2640 global $wgUseSquid, $wgUser;
2641 $fname = 'Title::moveOverExistingRedirect';
2642 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2645 $comment .= ": $reason";
2648 $now = wfTimestampNow();
2649 $newid = $nt->getArticleID();
2650 $oldid = $this->getArticleID();
2651 $latest = $this->getLatestRevID();
2653 $dbw = wfGetDB( DB_MASTER
);
2656 # Delete the old redirect. We don't save it to history since
2657 # by definition if we've got here it's rather uninteresting.
2658 # We have to remove it so that the next step doesn't trigger
2659 # a conflict on the unique namespace+title index...
2660 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2661 if ( !$dbw->cascadingDeletes() ) {
2662 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2663 global $wgUseTrackbacks;
2664 if ($wgUseTrackbacks)
2665 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2666 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2667 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2668 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2669 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2670 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2671 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2672 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2675 # Save a null revision in the page's history notifying of the move
2676 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2677 $nullRevId = $nullRevision->insertOn( $dbw );
2679 $article = new Article( $this );
2680 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2682 # Change the name of the target page:
2683 $dbw->update( 'page',
2685 'page_touched' => $dbw->timestamp($now),
2686 'page_namespace' => $nt->getNamespace(),
2687 'page_title' => $nt->getDBkey(),
2688 'page_latest' => $nullRevId,
2690 /* WHERE */ array( 'page_id' => $oldid ),
2693 $nt->resetArticleID( $oldid );
2695 # Recreate the redirect, this time in the other direction.
2696 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2697 $mwRedir = MagicWord
::get( 'redirect' );
2698 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2699 $redirectArticle = new Article( $this );
2700 $newid = $redirectArticle->insertOn( $dbw );
2701 $redirectRevision = new Revision( array(
2703 'comment' => $comment,
2704 'text' => $redirectText ) );
2705 $redirectRevision->insertOn( $dbw );
2706 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2708 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2710 # Now, we record the link from the redirect to the new title.
2711 # It should have no other outgoing links...
2712 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2713 $dbw->insert( 'pagelinks',
2715 'pl_from' => $newid,
2716 'pl_namespace' => $nt->getNamespace(),
2717 'pl_title' => $nt->getDBkey() ),
2720 $this->resetArticleID( 0 );
2723 # Move an image if this is a file
2724 if( $this->getNamespace() == NS_IMAGE
) {
2725 $file = wfLocalFile( $this );
2726 if( $file->exists() ) {
2727 $status = $file->move( $nt );
2728 if( !$status->isOk() ) {
2730 return $status->getErrorsArray();
2737 $log = new LogPage( 'move' );
2738 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2741 if ( $wgUseSquid ) {
2742 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2743 $u = new SquidUpdate( $urls );
2750 * Move page to non-existing title.
2751 * @param &$nt \type{Title} the new Title
2752 * @param $reason \type{\string} The reason for the move
2753 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2754 * Ignored if the user doesn't have the suppressredirect right
2756 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2757 global $wgUseSquid, $wgUser;
2758 $fname = 'MovePageForm::moveToNewTitle';
2759 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2761 $comment .= ": $reason";
2764 $newid = $nt->getArticleID();
2765 $oldid = $this->getArticleID();
2766 $latest = $this->getLatestRevId();
2768 $dbw = wfGetDB( DB_MASTER
);
2770 $now = $dbw->timestamp();
2772 # Save a null revision in the page's history notifying of the move
2773 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2774 $nullRevId = $nullRevision->insertOn( $dbw );
2776 $article = new Article( $this );
2777 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2780 $dbw->update( 'page',
2782 'page_touched' => $now,
2783 'page_namespace' => $nt->getNamespace(),
2784 'page_title' => $nt->getDBkey(),
2785 'page_latest' => $nullRevId,
2787 /* WHERE */ array( 'page_id' => $oldid ),
2790 $nt->resetArticleID( $oldid );
2792 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2794 $mwRedir = MagicWord
::get( 'redirect' );
2795 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2796 $redirectArticle = new Article( $this );
2797 $newid = $redirectArticle->insertOn( $dbw );
2798 $redirectRevision = new Revision( array(
2800 'comment' => $comment,
2801 'text' => $redirectText ) );
2802 $redirectRevision->insertOn( $dbw );
2803 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2805 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2807 # Record the just-created redirect's linking to the page
2808 $dbw->insert( 'pagelinks',
2810 'pl_from' => $newid,
2811 'pl_namespace' => $nt->getNamespace(),
2812 'pl_title' => $nt->getDBkey() ),
2815 $this->resetArticleID( 0 );
2818 # Move an image if this is a file
2819 if( $this->getNamespace() == NS_IMAGE
) {
2820 $file = wfLocalFile( $this );
2821 if( $file->exists() ) {
2822 $status = $file->move( $nt );
2823 if( !$status->isOk() ) {
2825 return $status->getErrorsArray();
2832 $log = new LogPage( 'move' );
2833 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2835 # Purge caches as per article creation
2836 Article
::onArticleCreate( $nt );
2838 # Purge old title from squid
2839 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2840 $this->purgeSquid();
2845 * Checks if $this can be moved to a given Title
2846 * - Selects for update, so don't call it unless you mean business
2848 * @param &$nt \type{Title} the new title to check
2849 * @return \type{\bool} TRUE or FALSE
2851 public function isValidMoveTarget( $nt ) {
2853 $fname = 'Title::isValidMoveTarget';
2854 $dbw = wfGetDB( DB_MASTER
);
2856 # Is it an existsing file?
2857 if( $nt->getNamespace() == NS_IMAGE
) {
2858 $file = wfLocalFile( $nt );
2859 if( $file->exists() ) {
2860 wfDebug( __METHOD__
. ": file exists\n" );
2866 $id = $nt->getArticleID();
2867 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2868 array( 'page_is_redirect','old_text','old_flags' ),
2869 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2870 $fname, 'FOR UPDATE' );
2872 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2874 wfDebug( __METHOD__
. ": not a redirect\n" );
2877 $text = Revision
::getRevisionText( $obj );
2879 # Does the redirect point to the source?
2880 # Or is it a broken self-redirect, usually caused by namespace collisions?
2882 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2883 $redirTitle = Title
::newFromText( $m[1] );
2884 if( !is_object( $redirTitle ) ||
2885 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2886 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2887 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2892 wfDebug( __METHOD__
. ": failsafe\n" );
2896 # Does the article have a history?
2897 $row = $dbw->selectRow( array( 'page', 'revision'),
2899 array( 'page_namespace' => $nt->getNamespace(),
2900 'page_title' => $nt->getDBkey(),
2901 'page_id=rev_page AND page_latest != rev_id'
2902 ), $fname, 'FOR UPDATE'
2905 # Return true if there was no history
2906 return $row === false;
2910 * Can this title be added to a user's watchlist?
2912 * @return \type{\bool} TRUE or FALSE
2914 public function isWatchable() {
2915 return !$this->isExternal()
2916 && MWNamespace
::isWatchable( $this->getNamespace() );
2920 * Get categories to which this Title belongs and return an array of
2921 * categories' names.
2923 * @return \type{\array} array an array of parents in the form:
2924 * $parent => $currentarticle
2926 public function getParentCategories() {
2929 $titlekey = $this->getArticleId();
2930 $dbr = wfGetDB( DB_SLAVE
);
2931 $categorylinks = $dbr->tableName( 'categorylinks' );
2934 $sql = "SELECT * FROM $categorylinks"
2935 ." WHERE cl_from='$titlekey'"
2936 ." AND cl_from <> '0'"
2937 ." ORDER BY cl_sortkey";
2939 $res = $dbr->query( $sql );
2941 if( $dbr->numRows( $res ) > 0 ) {
2942 foreach( $res as $row )
2943 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2944 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2945 $dbr->freeResult( $res );
2953 * Get a tree of parent categories
2954 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2955 * @return \type{\array} Tree of parent categories
2957 public function getParentCategoryTree( $children = array() ) {
2959 $parents = $this->getParentCategories();
2962 foreach( $parents as $parent => $current ) {
2963 if ( array_key_exists( $parent, $children ) ) {
2964 # Circular reference
2965 $stack[$parent] = array();
2967 $nt = Title
::newFromText($parent);
2969 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2981 * Get an associative array for selecting this title from
2984 * @return \type{\array} Selection array
2986 public function pageCond() {
2987 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2991 * Get the revision ID of the previous revision
2993 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2994 * @param $flags \type{\int} GAID_FOR_UPDATE
2995 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2997 public function getPreviousRevisionID( $revId, $flags=0 ) {
2998 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2999 return $db->selectField( 'revision', 'rev_id',
3001 'rev_page' => $this->getArticleId($flags),
3002 'rev_id < ' . intval( $revId )
3005 array( 'ORDER BY' => 'rev_id DESC' )
3010 * Get the revision ID of the next revision
3012 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3013 * @param $flags \type{\int} GAID_FOR_UPDATE
3014 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3016 public function getNextRevisionID( $revId, $flags=0 ) {
3017 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3018 return $db->selectField( 'revision', 'rev_id',
3020 'rev_page' => $this->getArticleId($flags),
3021 'rev_id > ' . intval( $revId )
3024 array( 'ORDER BY' => 'rev_id' )
3029 * Get the number of revisions between the given revision IDs.
3030 * Used for diffs and other things that really need it.
3032 * @param $old \type{\int} Revision ID.
3033 * @param $new \type{\int} Revision ID.
3034 * @return \type{\int} Number of revisions between these IDs.
3036 public function countRevisionsBetween( $old, $new ) {
3037 $dbr = wfGetDB( DB_SLAVE
);
3038 return $dbr->selectField( 'revision', 'count(*)',
3039 'rev_page = ' . intval( $this->getArticleId() ) .
3040 ' AND rev_id > ' . intval( $old ) .
3041 ' AND rev_id < ' . intval( $new ),
3043 array( 'USE INDEX' => 'PRIMARY' ) );
3047 * Compare with another title.
3049 * @param \type{Title} $title
3050 * @return \type{\bool} TRUE or FALSE
3052 public function equals( Title
$title ) {
3053 // Note: === is necessary for proper matching of number-like titles.
3054 return $this->getInterwiki() === $title->getInterwiki()
3055 && $this->getNamespace() == $title->getNamespace()
3056 && $this->getDBkey() === $title->getDBkey();
3060 * Callback for usort() to do title sorts by (namespace, title)
3062 static function compare( $a, $b ) {
3063 if( $a->getNamespace() == $b->getNamespace() ) {
3064 return strcmp( $a->getText(), $b->getText() );
3066 return $a->getNamespace() - $b->getNamespace();
3071 * Return a string representation of this title
3073 * @return \type{\string} String representation of this title
3075 public function __toString() {
3076 return $this->getPrefixedText();
3080 * Check if page exists
3081 * @return \type{\bool} TRUE or FALSE
3083 public function exists() {
3084 return $this->getArticleId() != 0;
3088 * Do we know that this title definitely exists, or should we otherwise
3089 * consider that it exists?
3091 * @return \type{\bool} TRUE or FALSE
3093 public function isAlwaysKnown() {
3094 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3095 // the full l10n of that language to be loaded. That takes much memory and
3096 // isn't needed. So we strip the language part away.
3097 // Also, extension messages which are not loaded, are shown as red, because
3098 // we don't call MessageCache::loadAllMessages.
3099 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3100 return $this->isExternal()
3101 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3102 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3106 * Update page_touched timestamps and send squid purge messages for
3107 * pages linking to this title. May be sent to the job queue depending
3108 * on the number of links. Typically called on create and delete.
3110 public function touchLinks() {
3111 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3114 if ( $this->getNamespace() == NS_CATEGORY
) {
3115 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3121 * Get the last touched timestamp
3122 * @return \type{\string} Last touched timestamp
3124 public function getTouched() {
3125 $dbr = wfGetDB( DB_SLAVE
);
3126 $touched = $dbr->selectField( 'page', 'page_touched',
3128 'page_namespace' => $this->getNamespace(),
3129 'page_title' => $this->getDBkey()
3136 * Get the trackback URL for this page
3137 * @return \type{\string} Trackback URL
3139 public function trackbackURL() {
3140 global $wgTitle, $wgScriptPath, $wgServer;
3142 return "$wgServer$wgScriptPath/trackback.php?article="
3143 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3147 * Get the trackback RDF for this page
3148 * @return \type{\string} Trackback RDF
3150 public function trackbackRDF() {
3151 $url = htmlspecialchars($this->getFullURL());
3152 $title = htmlspecialchars($this->getText());
3153 $tburl = $this->trackbackURL();
3155 // Autodiscovery RDF is placed in comments so HTML validator
3156 // won't barf. This is a rather icky workaround, but seems
3157 // frequently used by this kind of RDF thingy.
3159 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3161 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3162 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3163 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3166 dc:identifier=\"$url\"
3168 trackback:ping=\"$tburl\" />
3174 * Generate strings used for xml 'id' names in monobook tabs
3175 * @return \type{\string} XML 'id' name
3177 public function getNamespaceKey() {
3179 switch ($this->getNamespace()) {
3182 return 'nstab-main';
3185 return 'nstab-user';
3187 return 'nstab-media';
3189 return 'nstab-special';
3191 case NS_PROJECT_TALK
:
3192 return 'nstab-project';
3195 return 'nstab-image';
3197 case NS_MEDIAWIKI_TALK
:
3198 return 'nstab-mediawiki';
3200 case NS_TEMPLATE_TALK
:
3201 return 'nstab-template';
3204 return 'nstab-help';
3206 case NS_CATEGORY_TALK
:
3207 return 'nstab-category';
3209 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3214 * Returns true if this title resolves to the named special page
3215 * @param $name \type{\string} The special page name
3217 public function isSpecial( $name ) {
3218 if ( $this->getNamespace() == NS_SPECIAL
) {
3219 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3220 if ( $name == $thisName ) {
3228 * If the Title refers to a special page alias which is not the local default,
3229 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3231 public function fixSpecialName() {
3232 if ( $this->getNamespace() == NS_SPECIAL
) {
3233 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3234 if ( $canonicalName ) {
3235 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3236 if ( $localName != $this->mDbkeyform
) {
3237 return Title
::makeTitle( NS_SPECIAL
, $localName );
3245 * Is this Title in a namespace which contains content?
3246 * In other words, is this a content page, for the purposes of calculating
3249 * @return \type{\bool} TRUE or FALSE
3251 public function isContentPage() {
3252 return MWNamespace
::isContent( $this->getNamespace() );
3256 * Get all extant redirects to this Title
3258 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3259 * NULL to consider all namespaces
3260 * @return \arrayof{Title} Redirects to this title
3262 public function getRedirectsHere( $ns = null ) {
3265 $dbr = wfGetDB( DB_SLAVE
);
3267 'rd_namespace' => $this->getNamespace(),
3268 'rd_title' => $this->getDBkey(),
3271 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3273 $res = $dbr->select(
3274 array( 'redirect', 'page' ),
3275 array( 'page_namespace', 'page_title' ),
3281 foreach( $res as $row ) {
3282 $redirs[] = self
::newFromRow( $row );