Added setVal accessor to $wgRequest->data so we don't have to access it directly...
[mediawiki.git] / includes / Title.php
blobc8de709da3196ec1eae7640cd10ae67820445be3
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
14 /**
15 * Constants for pr_cascade bitfield
17 define( 'CASCADE', 1 );
19 /**
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.
25 class Title {
26 /** @name Static cache variables */
27 //@{
28 static private $titleCache=array();
29 static private $interwikiCache=array();
30 //@}
32 /**
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;
40 /**
41 * @name Private member variables
42 * Please use the accessor functions instead.
43 * @private
45 //@{
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 = array(); ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeSources; ///< 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?
71 //@}
74 /**
75 * Constructor
76 * @private
78 /* private */ function __construct() {}
80 /**
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
84 * interwiki prefixes
85 * @return \type{Title} the new object, or NULL on an error
87 public static function newFromDBkey( $key ) {
88 $t = new Title();
89 $t->mDbkeyform = $key;
90 if( $t->secureAndSplit() )
91 return $t;
92 else
93 return NULL;
96 /**
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
102 * are accepted
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
116 * caching them.
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 &eacute; &#257; or &#x3017; into real text...
127 $filteredText = Sanitizer::decodeCharReferences( $text );
129 $t = new Title();
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();
139 $cachedcount=0;
141 $cachedcount++;
142 Title::$titleCache[$text] =& $t;
144 return $t;
145 } else {
146 $ret = NULL;
147 return $ret;
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;
159 $t = new Title();
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() ) {
170 return $t;
171 } else {
172 return NULL;
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 );
193 } else {
194 $title = NULL;
196 return $title;
200 * Make an array of titles from an array of IDs
201 * @param $ids \type{\arrayof{\int}} Array of IDs
202 * @return \type{\arrayof{Title}} Array of Titles
204 public static function newFromIDs( $ids ) {
205 if ( !count( $ids ) ) {
206 return array();
208 $dbr = wfGetDB( DB_SLAVE );
209 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
210 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
212 $titles = array();
213 foreach( $res as $row ) {
214 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
216 return $titles;
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;
232 return $t;
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 = '' ) {
248 $t = new Title();
249 $t->mInterwiki = '';
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 );
256 return $t;
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 = '' ) {
270 $t = new Title();
271 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment );
272 if( $t->secureAndSplit() ) {
273 return $t;
274 } else {
275 return NULL;
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
286 if ( !$title ) {
287 $title = Title::newFromText( 'Main Page' );
289 return $title;
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' );
301 $text = trim($text);
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!
306 $m = array();
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' ) )
319 return $title;
322 return null;
325 #----------------------------------------------------------------------------
326 # Static functions
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 );
342 return $n;
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
361 * search index
363 public static function indexTitle( $ns, $title ) {
364 global $wgContLang;
366 $lc = SearchEngine::legalSearchChars() . '&#;';
367 $t = $wgContLang->stripForSearch( $title );
368 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
369 $t = $wgContLang->lc( $t );
371 # Handle 's, s'
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 );
380 return trim( $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 = '' ) {
391 global $wgContLang;
393 $namespace = $wgContLang->getNsText( $ns );
394 $name = $namespace == '' ? $title : "$namespace:$title";
395 if ( strval( $fragment ) != '' ) {
396 $name .= '#' . $fragment;
398 return $name;
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
406 * @static (arguably)
407 * @deprecated See Interwiki class
409 public function getInterwikiLink( $key ) {
410 return Interwiki::fetch( $key )->getURL( );
414 * Determine whether the object refers to a page within
415 * this project.
417 * @return \type{\bool} TRUE if this is an in-project interwiki link
418 * or a wikilink, FALSE otherwise
420 public function isLocal() {
421 if ( $this->mInterwiki != '' ) {
422 return Interwiki::fetch( $this->mInterwiki )->isLocal();
423 } else {
424 return true;
429 * Determine whether the object refers to a page within
430 * this project and is transcludable.
432 * @return \type{\bool} TRUE if this is transcludable
434 public function isTrans() {
435 if ($this->mInterwiki == '')
436 return false;
438 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
442 * Escape a text fragment, say from a link, for a URL
444 static function escapeFragmentForURL( $fragment ) {
445 $fragment = str_replace( ' ', '_', $fragment );
446 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
447 $replaceArray = array(
448 '%3A' => ':',
449 '%' => '.'
451 return strtr( $fragment, $replaceArray );
454 #----------------------------------------------------------------------------
455 # Other stuff
456 #----------------------------------------------------------------------------
458 /** Simple accessors */
460 * Get the text form (spaces not underscores) of the main part
461 * @return \type{\string} Main part of the title
463 public function getText() { return $this->mTextform; }
465 * Get the URL-encoded form of the main part
466 * @return \type{\string} Main part of the title, URL-encoded
468 public function getPartialURL() { return $this->mUrlform; }
470 * Get the main part with underscores
471 * @return \type{\string} Main part of the title, with underscores
473 public function getDBkey() { return $this->mDbkeyform; }
475 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
476 * @return \type{\int} Namespace index
478 public function getNamespace() { return $this->mNamespace; }
480 * Get the namespace text
481 * @return \type{\string} Namespace text
483 public function getNsText() {
484 global $wgContLang, $wgCanonicalNamespaceNames;
486 if ( '' != $this->mInterwiki ) {
487 // This probably shouldn't even happen. ohh man, oh yuck.
488 // But for interwiki transclusion it sometimes does.
489 // Shit. Shit shit shit.
491 // Use the canonical namespaces if possible to try to
492 // resolve a foreign namespace.
493 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
494 return $wgCanonicalNamespaceNames[$this->mNamespace];
497 return $wgContLang->getNsText( $this->mNamespace );
500 * Get the DB key with the initial letter case as specified by the user
501 * @return \type{\string} DB key
503 function getUserCaseDBKey() {
504 return $this->mUserCaseDBKey;
507 * Get the namespace text of the subject (rather than talk) page
508 * @return \type{\string} Namespace text
510 public function getSubjectNsText() {
511 global $wgContLang;
512 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
515 * Get the namespace text of the talk page
516 * @return \type{\string} Namespace text
518 public function getTalkNsText() {
519 global $wgContLang;
520 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
523 * Could this title have a corresponding talk page?
524 * @return \type{\bool} TRUE or FALSE
526 public function canTalk() {
527 return( MWNamespace::canTalk( $this->mNamespace ) );
530 * Get the interwiki prefix (or null string)
531 * @return \type{\string} Interwiki prefix
533 public function getInterwiki() { return $this->mInterwiki; }
535 * Get the Title fragment (i.e.\ the bit after the #) in text form
536 * @return \type{\string} Title fragment
538 public function getFragment() { return $this->mFragment; }
540 * Get the fragment in URL form, including the "#" character if there is one
541 * @return \type{\string} Fragment in URL form
543 public function getFragmentForURL() {
544 if ( $this->mFragment == '' ) {
545 return '';
546 } else {
547 return '#' . Title::escapeFragmentForURL( $this->mFragment );
551 * Get the default namespace index, for when there is no namespace
552 * @return \type{\int} Default namespace index
554 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
557 * Get title for search index
558 * @return \type{\string} a stripped-down title string ready for the
559 * search index
561 public function getIndexTitle() {
562 return Title::indexTitle( $this->mNamespace, $this->mTextform );
566 * Get the prefixed database key form
567 * @return \type{\string} the prefixed title, with underscores and
568 * any interwiki and namespace prefixes
570 public function getPrefixedDBkey() {
571 $s = $this->prefix( $this->mDbkeyform );
572 $s = str_replace( ' ', '_', $s );
573 return $s;
577 * Get the prefixed title with spaces.
578 * This is the form usually used for display
579 * @return \type{\string} the prefixed title, with spaces
581 public function getPrefixedText() {
582 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
583 $s = $this->prefix( $this->mTextform );
584 $s = str_replace( '_', ' ', $s );
585 $this->mPrefixedText = $s;
587 return $this->mPrefixedText;
591 * Get the prefixed title with spaces, plus any fragment
592 * (part beginning with '#')
593 * @return \type{\string} the prefixed title, with spaces and
594 * the fragment, including '#'
596 public function getFullText() {
597 $text = $this->getPrefixedText();
598 if( '' != $this->mFragment ) {
599 $text .= '#' . $this->mFragment;
601 return $text;
605 * Get the base name, i.e. the leftmost parts before the /
606 * @return \type{\string} Base name
608 public function getBaseText() {
609 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
610 return $this->getText();
613 $parts = explode( '/', $this->getText() );
614 # Don't discard the real title if there's no subpage involved
615 if( count( $parts ) > 1 )
616 unset( $parts[ count( $parts ) - 1 ] );
617 return implode( '/', $parts );
621 * Get the lowest-level subpage name, i.e. the rightmost part after /
622 * @return \type{\string} Subpage name
624 public function getSubpageText() {
625 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
626 return( $this->mTextform );
628 $parts = explode( '/', $this->mTextform );
629 return( $parts[ count( $parts ) - 1 ] );
633 * Get a URL-encoded form of the subpage text
634 * @return \type{\string} URL-encoded subpage name
636 public function getSubpageUrlForm() {
637 $text = $this->getSubpageText();
638 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
639 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
640 return( $text );
644 * Get a URL-encoded title (not an actual URL) including interwiki
645 * @return \type{\string} the URL-encoded form
647 public function getPrefixedURL() {
648 $s = $this->prefix( $this->mDbkeyform );
649 $s = str_replace( ' ', '_', $s );
651 $s = wfUrlencode ( $s ) ;
653 # Cleaning up URL to make it look nice -- is this safe?
654 $s = str_replace( '%28', '(', $s );
655 $s = str_replace( '%29', ')', $s );
657 return $s;
661 * Get a real URL referring to this title, with interwiki link and
662 * fragment
664 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
665 * links. Can be specified as an associative array as well, e.g.,
666 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
667 * @param $variant \type{\string} language variant of url (for sr, zh..)
668 * @return \type{\string} the URL
670 public function getFullURL( $query = '', $variant = false ) {
671 global $wgContLang, $wgServer, $wgRequest;
673 if( is_array( $query ) ) {
674 $query = wfArrayToCGI( $query );
677 if ( '' == $this->mInterwiki ) {
678 $url = $this->getLocalUrl( $query, $variant );
680 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
681 // Correct fix would be to move the prepending elsewhere.
682 if ($wgRequest->getVal('action') != 'render') {
683 $url = $wgServer . $url;
685 } else {
686 $baseUrl = Interwiki::fetch( $this->mInterwiki )->getURL( );
688 $namespace = wfUrlencode( $this->getNsText() );
689 if ( '' != $namespace ) {
690 # Can this actually happen? Interwikis shouldn't be parsed.
691 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
692 $namespace .= ':';
694 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
695 $url = wfAppendQuery( $url, $query );
698 # Finally, add the fragment.
699 $url .= $this->getFragmentForURL();
701 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
702 return $url;
706 * Get a URL with no fragment or server name. If this page is generated
707 * with action=render, $wgServer is prepended.
708 * @param mixed $query an optional query string; if not specified,
709 * $wgArticlePath will be used. Can be specified as an associative array
710 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
711 * URL-escaped).
712 * @param $variant \type{\string} language variant of url (for sr, zh..)
713 * @return \type{\string} the URL
715 public function getLocalURL( $query = '', $variant = false ) {
716 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
717 global $wgVariantArticlePath, $wgContLang, $wgUser;
719 if( is_array( $query ) ) {
720 $query = wfArrayToCGI( $query );
723 // internal links should point to same variant as current page (only anonymous users)
724 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
725 $pref = $wgContLang->getPreferredVariant(false);
726 if($pref != $wgContLang->getCode())
727 $variant = $pref;
730 if ( $this->isExternal() ) {
731 $url = $this->getFullURL();
732 if ( $query ) {
733 // This is currently only used for edit section links in the
734 // context of interwiki transclusion. In theory we should
735 // append the query to the end of any existing query string,
736 // but interwiki transclusion is already broken in that case.
737 $url .= "?$query";
739 } else {
740 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
741 if ( $query == '' ) {
742 if( $variant != false && $wgContLang->hasVariants() ) {
743 if( $wgVariantArticlePath == false ) {
744 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
745 } else {
746 $variantArticlePath = $wgVariantArticlePath;
748 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
749 $url = str_replace( '$1', $dbkey, $url );
750 } else {
751 $url = str_replace( '$1', $dbkey, $wgArticlePath );
753 } else {
754 global $wgActionPaths;
755 $url = false;
756 $matches = array();
757 if( !empty( $wgActionPaths ) &&
758 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
760 $action = urldecode( $matches[2] );
761 if( isset( $wgActionPaths[$action] ) ) {
762 $query = $matches[1];
763 if( isset( $matches[4] ) ) $query .= $matches[4];
764 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
765 if( $query != '' ) $url .= '?' . $query;
768 if ( $url === false ) {
769 if ( $query == '-' ) {
770 $query = '';
772 $url = "{$wgScript}?title={$dbkey}&{$query}";
776 // FIXME: this causes breakage in various places when we
777 // actually expected a local URL and end up with dupe prefixes.
778 if ($wgRequest->getVal('action') == 'render') {
779 $url = $wgServer . $url;
782 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
783 return $url;
787 * Get a URL that's the simplest URL that will be valid to link, locally,
788 * to the current Title. It includes the fragment, but does not include
789 * the server unless action=render is used (or the link is external). If
790 * there's a fragment but the prefixed text is empty, we just return a link
791 * to the fragment.
793 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
794 * query string. Keys and values will be escaped.
795 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
796 * for external links. Default is "false" (same variant as current page,
797 * for anonymous users).
798 * @return \type{\string} the URL
800 public function getLinkUrl( $query = array(), $variant = false ) {
801 if( !is_array( $query ) ) {
802 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
803 '$query' );
805 if( $this->isExternal() ) {
806 return $this->getFullURL( $query );
807 } elseif( $this->getPrefixedText() === ''
808 and $this->getFragment() !== '' ) {
809 return $this->getFragmentForURL();
810 } else {
811 return $this->getLocalURL( $query, $variant )
812 . $this->getFragmentForURL();
817 * Get an HTML-escaped version of the URL form, suitable for
818 * using in a link, without a server name or fragment
819 * @param $query \type{\string} an optional query string
820 * @return \type{\string} the URL
822 public function escapeLocalURL( $query = '' ) {
823 return htmlspecialchars( $this->getLocalURL( $query ) );
827 * Get an HTML-escaped version of the URL form, suitable for
828 * using in a link, including the server name and fragment
830 * @param $query \type{\string} an optional query string
831 * @return \type{\string} the URL
833 public function escapeFullURL( $query = '' ) {
834 return htmlspecialchars( $this->getFullURL( $query ) );
838 * Get the URL form for an internal link.
839 * - Used in various Squid-related code, in case we have a different
840 * internal hostname for the server from the exposed one.
842 * @param $query \type{\string} an optional query string
843 * @param $variant \type{\string} language variant of url (for sr, zh..)
844 * @return \type{\string} the URL
846 public function getInternalURL( $query = '', $variant = false ) {
847 global $wgInternalServer;
848 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
849 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
850 return $url;
854 * Get the edit URL for this Title
855 * @return \type{\string} the URL, or a null string if this is an
856 * interwiki link
858 public function getEditURL() {
859 if ( '' != $this->mInterwiki ) { return ''; }
860 $s = $this->getLocalURL( 'action=edit' );
862 return $s;
866 * Get the HTML-escaped displayable text form.
867 * Used for the title field in <a> tags.
868 * @return \type{\string} the text, including any prefixes
870 public function getEscapedText() {
871 return htmlspecialchars( $this->getPrefixedText() );
875 * Is this Title interwiki?
876 * @return \type{\bool}
878 public function isExternal() { return ( '' != $this->mInterwiki ); }
881 * Is this page "semi-protected" - the *only* protection is autoconfirm?
883 * @param @action \type{\string} Action to check (default: edit)
884 * @return \type{\bool}
886 public function isSemiProtected( $action = 'edit' ) {
887 if( $this->exists() ) {
888 $restrictions = $this->getRestrictions( $action );
889 if( count( $restrictions ) > 0 ) {
890 foreach( $restrictions as $restriction ) {
891 if( strtolower( $restriction ) != 'autoconfirmed' )
892 return false;
894 } else {
895 # Not protected
896 return false;
898 return true;
899 } else {
900 # If it doesn't exist, it can't be protected
901 return false;
906 * Does the title correspond to a protected article?
907 * @param $what \type{\string} the action the page is protected from,
908 * by default checks move and edit
909 * @return \type{\bool}
911 public function isProtected( $action = '' ) {
912 global $wgRestrictionLevels, $wgRestrictionTypes;
914 # Special pages have inherent protection
915 if( $this->getNamespace() == NS_SPECIAL )
916 return true;
918 # Check regular protection levels
919 foreach( $wgRestrictionTypes as $type ){
920 if( $action == $type || $action == '' ) {
921 $r = $this->getRestrictions( $type );
922 foreach( $wgRestrictionLevels as $level ) {
923 if( in_array( $level, $r ) && $level != '' ) {
924 return true;
930 return false;
934 * Is $wgUser watching this page?
935 * @return \type{\bool}
937 public function userIsWatching() {
938 global $wgUser;
940 if ( is_null( $this->mWatched ) ) {
941 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
942 $this->mWatched = false;
943 } else {
944 $this->mWatched = $wgUser->isWatched( $this );
947 return $this->mWatched;
951 * Can $wgUser perform $action on this page?
952 * This skips potentially expensive cascading permission checks.
954 * Suitable for use for nonessential UI controls in common cases, but
955 * _not_ for functional access control.
957 * May provide false positives, but should never provide a false negative.
959 * @param $action \type{\string} action that permission needs to be checked for
960 * @return \type{\bool}
962 public function quickUserCan( $action ) {
963 return $this->userCan( $action, false );
967 * Determines if $wgUser is unable to edit this page because it has been protected
968 * by $wgNamespaceProtection.
970 * @return \type{\bool}
972 public function isNamespaceProtected() {
973 global $wgNamespaceProtection, $wgUser;
974 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
975 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
976 if( $right != '' && !$wgUser->isAllowed( $right ) )
977 return true;
980 return false;
984 * Can $wgUser perform $action on this page?
985 * @param $action \type{\string} action that permission needs to be checked for
986 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
987 * @return \type{\bool}
989 public function userCan( $action, $doExpensiveQueries = true ) {
990 global $wgUser;
991 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
995 * Can $user perform $action on this page?
997 * FIXME: This *does not* check throttles (User::pingLimiter()).
999 * @param $action \type{\string}action that permission needs to be checked for
1000 * @param $user \type{User} user to check
1001 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1002 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1003 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1005 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1006 if( !StubObject::isRealObject( $user ) ) {
1007 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1008 global $wgUser;
1009 $wgUser->_unstub( '', 5 );
1010 $user = $wgUser;
1012 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1014 global $wgContLang;
1015 global $wgLang;
1016 global $wgEmailConfirmToEdit;
1018 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1019 $errors[] = array( 'confirmedittext' );
1022 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1023 if ( $user->isBlockedFrom( $this ) && $action != 'read' && $action != 'createaccount' ) {
1024 $block = $user->mBlock;
1026 // This is from OutputPage::blockedPage
1027 // Copied at r23888 by werdna
1029 $id = $user->blockedBy();
1030 $reason = $user->blockedFor();
1031 if( $reason == '' ) {
1032 $reason = wfMsg( 'blockednoreason' );
1034 $ip = wfGetIP();
1036 if ( is_numeric( $id ) ) {
1037 $name = User::whoIs( $id );
1038 } else {
1039 $name = $id;
1042 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1043 $blockid = $block->mId;
1044 $blockExpiry = $user->mBlock->mExpiry;
1045 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1047 if ( $blockExpiry == 'infinity' ) {
1048 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1049 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1051 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1052 if ( strpos( $option, ':' ) == false )
1053 continue;
1055 list ($show, $value) = explode( ":", $option );
1057 if ( $value == 'infinite' || $value == 'indefinite' ) {
1058 $blockExpiry = $show;
1059 break;
1062 } else {
1063 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1066 $intended = $user->mBlock->mAddress;
1068 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1069 $blockid, $blockExpiry, $intended, $blockTimestamp );
1072 // Remove the errors being ignored.
1074 foreach( $errors as $index => $error ) {
1075 $error_key = is_array($error) ? $error[0] : $error;
1077 if (in_array( $error_key, $ignoreErrors )) {
1078 unset($errors[$index]);
1082 return $errors;
1086 * Can $user perform $action on this page? This is an internal function,
1087 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1088 * checks on wfReadOnly() and blocks)
1090 * @param $action \type{\string} action that permission needs to be checked for
1091 * @param $user \type{User} user to check
1092 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1093 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1095 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1096 wfProfileIn( __METHOD__ );
1098 $errors = array();
1100 // Use getUserPermissionsErrors instead
1101 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1102 wfProfileOut( __METHOD__ );
1103 return $result ? array() : array( array( 'badaccess-group0' ) );
1106 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1107 if ($result != array() && is_array($result) && !is_array($result[0]))
1108 $errors[] = $result; # A single array representing an error
1109 else if (is_array($result) && is_array($result[0]))
1110 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1111 else if ($result != '' && $result != null && $result !== true && $result !== false)
1112 $errors[] = array($result); # A string representing a message-id
1113 else if ($result === false )
1114 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1116 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1117 if ($result != array() && is_array($result) && !is_array($result[0]))
1118 $errors[] = $result; # A single array representing an error
1119 else if (is_array($result) && is_array($result[0]))
1120 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1121 else if ($result != '' && $result != null && $result !== true && $result !== false)
1122 $errors[] = array($result); # A string representing a message-id
1123 else if ($result === false )
1124 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1127 $specialOKActions = array( 'createaccount', 'execute' );
1128 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1129 $errors[] = array('ns-specialprotected');
1132 if ( $this->isNamespaceProtected() ) {
1133 $ns = $this->getNamespace() == NS_MAIN
1134 ? wfMsg( 'nstab-main' )
1135 : $this->getNsText();
1136 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1137 ? array('protectedinterface')
1138 : array( 'namespaceprotected', $ns ) );
1141 if( $this->mDbkeyform == '_' ) {
1142 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1143 $errors[] = array('badaccess-group0');
1146 # protect css/js subpages of user pages
1147 # XXX: this might be better using restrictions
1148 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1149 if( $this->isCssJsSubpage()
1150 && !$user->isAllowed('editusercssjs')
1151 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1152 $errors[] = array('customcssjsprotected');
1155 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1156 # We /could/ use the protection level on the source page, but it's fairly ugly
1157 # as we have to establish a precedence hierarchy for pages included by multiple
1158 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1159 # as they could remove the protection anyway.
1160 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1161 # Cascading protection depends on more than this page...
1162 # Several cascading protected pages may include this page...
1163 # Check each cascading level
1164 # This is only for protection restrictions, not for all actions
1165 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1166 foreach( $restrictions[$action] as $right ) {
1167 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1168 if( '' != $right && !$user->isAllowed( $right ) ) {
1169 $pages = '';
1170 foreach( $cascadingSources as $page )
1171 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1172 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1178 foreach( $this->getRestrictions($action) as $right ) {
1179 // Backwards compatibility, rewrite sysop -> protect
1180 if ( $right == 'sysop' ) {
1181 $right = 'protect';
1183 if( '' != $right && !$user->isAllowed( $right ) ) {
1184 //Users with 'editprotected' permission can edit protected pages
1185 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1186 //Users with 'editprotected' permission cannot edit protected pages
1187 //with cascading option turned on.
1188 if($this->mCascadeRestriction) {
1189 $errors[] = array( 'protectedpagetext', $right );
1190 } else {
1191 //Nothing, user can edit!
1193 } else {
1194 $errors[] = array( 'protectedpagetext', $right );
1199 if ($action == 'protect') {
1200 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1201 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1205 if ($action == 'create') {
1206 $title_protection = $this->getTitleProtection();
1208 if (is_array($title_protection)) {
1209 extract($title_protection);
1211 if ($pt_create_perm == 'sysop')
1212 $pt_create_perm = 'protect';
1214 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1215 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1219 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1220 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1221 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1223 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1224 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1225 } elseif ( !$user->isAllowed( $action ) ) {
1226 $return = null;
1227 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1228 User::getGroupsWithPermission( $action ) );
1229 if ( $groups ) {
1230 $return = array( 'badaccess-groups',
1231 array(
1232 implode( ', ', $groups ),
1233 count( $groups ) ) );
1235 else {
1236 $return = array( "badaccess-group0" );
1238 $errors[] = $return;
1241 wfProfileOut( __METHOD__ );
1242 return $errors;
1246 * Is this title subject to title protection?
1247 * @return \type{\mixed} An associative array representing any existent title
1248 * protection, or false if there's none.
1250 private function getTitleProtection() {
1251 // Can't protect pages in special namespaces
1252 if ( $this->getNamespace() < 0 ) {
1253 return false;
1256 $dbr = wfGetDB( DB_SLAVE );
1257 $res = $dbr->select( 'protected_titles', '*',
1258 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1260 if ($row = $dbr->fetchRow( $res )) {
1261 return $row;
1262 } else {
1263 return false;
1268 * Update the title protection status
1269 * @param $create_perm \type{\string} Permission required for creation
1270 * @param $reason \type{\string} Reason for protection
1271 * @param $expiry \type{\string} Expiry timestamp
1273 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1274 global $wgUser,$wgContLang;
1276 if ($create_perm == implode(',',$this->getRestrictions('create'))
1277 && $expiry == $this->mRestrictionsExpiry['create']) {
1278 // No change
1279 return true;
1282 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1284 $dbw = wfGetDB( DB_MASTER );
1286 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1288 $expiry_description = '';
1289 if ( $encodedExpiry != 'infinity' ) {
1290 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1292 else {
1293 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1296 # Update protection table
1297 if ($create_perm != '' ) {
1298 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1299 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1300 , 'pt_create_perm' => $create_perm
1301 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1302 , 'pt_expiry' => $encodedExpiry
1303 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1304 } else {
1305 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1306 'pt_title' => $title ), __METHOD__ );
1308 # Update the protection log
1309 $log = new LogPage( 'protect' );
1311 if( $create_perm ) {
1312 $params = array("[create=$create_perm] $expiry_description",'');
1313 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason ), $params );
1314 } else {
1315 $log->addEntry( 'unprotect', $this, $reason );
1318 return true;
1322 * Remove any title protection due to page existing
1324 public function deleteTitleProtection() {
1325 $dbw = wfGetDB( DB_MASTER );
1327 $dbw->delete( 'protected_titles',
1328 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1332 * Can $wgUser edit this page?
1333 * @return \type{\bool} TRUE or FALSE
1334 * @deprecated use userCan('edit')
1336 public function userCanEdit( $doExpensiveQueries = true ) {
1337 return $this->userCan( 'edit', $doExpensiveQueries );
1341 * Can $wgUser create this page?
1342 * @return \type{\bool} TRUE or FALSE
1343 * @deprecated use userCan('create')
1345 public function userCanCreate( $doExpensiveQueries = true ) {
1346 return $this->userCan( 'create', $doExpensiveQueries );
1350 * Can $wgUser move this page?
1351 * @return \type{\bool} TRUE or FALSE
1352 * @deprecated use userCan('move')
1354 public function userCanMove( $doExpensiveQueries = true ) {
1355 return $this->userCan( 'move', $doExpensiveQueries );
1359 * Would anybody with sufficient privileges be able to move this page?
1360 * Some pages just aren't movable.
1362 * @return \type{\bool} TRUE or FALSE
1364 public function isMovable() {
1365 return MWNamespace::isMovable( $this->getNamespace() )
1366 && $this->getInterwiki() == '';
1370 * Can $wgUser read this page?
1371 * @return \type{\bool} TRUE or FALSE
1372 * @todo fold these checks into userCan()
1374 public function userCanRead() {
1375 global $wgUser, $wgGroupPermissions;
1377 $result = null;
1378 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1379 if ( $result !== null ) {
1380 return $result;
1383 # Shortcut for public wikis, allows skipping quite a bit of code
1384 if ($wgGroupPermissions['*']['read'])
1385 return true;
1387 if( $wgUser->isAllowed( 'read' ) ) {
1388 return true;
1389 } else {
1390 global $wgWhitelistRead;
1393 * Always grant access to the login page.
1394 * Even anons need to be able to log in.
1396 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1397 return true;
1401 * Bail out if there isn't whitelist
1403 if( !is_array($wgWhitelistRead) ) {
1404 return false;
1408 * Check for explicit whitelisting
1410 $name = $this->getPrefixedText();
1411 $dbName = $this->getPrefixedDBKey();
1412 // Check with and without underscores
1413 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1414 return true;
1417 * Old settings might have the title prefixed with
1418 * a colon for main-namespace pages
1420 if( $this->getNamespace() == NS_MAIN ) {
1421 if( in_array( ':' . $name, $wgWhitelistRead ) )
1422 return true;
1426 * If it's a special page, ditch the subpage bit
1427 * and check again
1429 if( $this->getNamespace() == NS_SPECIAL ) {
1430 $name = $this->getDBkey();
1431 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1432 if ( $name === false ) {
1433 # Invalid special page, but we show standard login required message
1434 return false;
1437 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1438 if( in_array( $pure, $wgWhitelistRead, true ) )
1439 return true;
1443 return false;
1447 * Is this a talk page of some sort?
1448 * @return \type{\bool} TRUE or FALSE
1450 public function isTalkPage() {
1451 return MWNamespace::isTalk( $this->getNamespace() );
1455 * Is this a subpage?
1456 * @return \type{\bool} TRUE or FALSE
1458 public function isSubpage() {
1459 return MWNamespace::hasSubpages( $this->mNamespace )
1460 ? strpos( $this->getText(), '/' ) !== false
1461 : false;
1465 * Does this have subpages? (Warning, usually requires an extra DB query.)
1466 * @return \type{\bool} TRUE or FALSE
1468 public function hasSubpages() {
1469 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1470 # Duh
1471 return false;
1474 # We dynamically add a member variable for the purpose of this method
1475 # alone to cache the result. There's no point in having it hanging
1476 # around uninitialized in every Title object; therefore we only add it
1477 # if needed and don't declare it statically.
1478 if( isset( $this->mHasSubpages ) ) {
1479 return $this->mHasSubpages;
1482 $db = wfGetDB( DB_SLAVE );
1483 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1484 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1485 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1486 __METHOD__
1491 * Could this page contain custom CSS or JavaScript, based
1492 * on the title?
1494 * @return \type{\bool} TRUE or FALSE
1496 public function isCssOrJsPage() {
1497 return $this->mNamespace == NS_MEDIAWIKI
1498 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1502 * Is this a .css or .js subpage of a user page?
1503 * @return \type{\bool} TRUE or FALSE
1505 public function isCssJsSubpage() {
1506 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1509 * Is this a *valid* .css or .js subpage of a user page?
1510 * Check that the corresponding skin exists
1511 * @return \type{\bool} TRUE or FALSE
1513 public function isValidCssJsSubpage() {
1514 if ( $this->isCssJsSubpage() ) {
1515 $skinNames = Skin::getSkinNames();
1516 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1517 } else {
1518 return false;
1522 * Trim down a .css or .js subpage title to get the corresponding skin name
1524 public function getSkinFromCssJsSubpage() {
1525 $subpage = explode( '/', $this->mTextform );
1526 $subpage = $subpage[ count( $subpage ) - 1 ];
1527 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1530 * Is this a .css subpage of a user page?
1531 * @return \type{\bool} TRUE or FALSE
1533 public function isCssSubpage() {
1534 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1537 * Is this a .js subpage of a user page?
1538 * @return \type{\bool} TRUE or FALSE
1540 public function isJsSubpage() {
1541 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1544 * Protect css/js subpages of user pages: can $wgUser edit
1545 * this page?
1547 * @return \type{\bool} TRUE or FALSE
1548 * @todo XXX: this might be better using restrictions
1550 public function userCanEditCssJsSubpage() {
1551 global $wgUser;
1552 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1556 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1558 * @return \type{\bool} If the page is subject to cascading restrictions.
1560 public function isCascadeProtected() {
1561 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1562 return ( $sources > 0 );
1566 * Cascading protection: Get the source of any cascading restrictions on this page.
1568 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1569 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1570 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1571 * The restriction array is an array of each type, each of which contains an array of unique groups.
1573 public function getCascadeProtectionSources( $get_pages = true ) {
1574 global $wgRestrictionTypes;
1576 # Define our dimension of restrictions types
1577 $pagerestrictions = array();
1578 foreach( $wgRestrictionTypes as $action )
1579 $pagerestrictions[$action] = array();
1581 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1582 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1583 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1584 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1587 wfProfileIn( __METHOD__ );
1589 $dbr = wfGetDb( DB_SLAVE );
1591 if ( $this->getNamespace() == NS_IMAGE ) {
1592 $tables = array ('imagelinks', 'page_restrictions');
1593 $where_clauses = array(
1594 'il_to' => $this->getDBkey(),
1595 'il_from=pr_page',
1596 'pr_cascade' => 1 );
1597 } else {
1598 $tables = array ('templatelinks', 'page_restrictions');
1599 $where_clauses = array(
1600 'tl_namespace' => $this->getNamespace(),
1601 'tl_title' => $this->getDBkey(),
1602 'tl_from=pr_page',
1603 'pr_cascade' => 1 );
1606 if ( $get_pages ) {
1607 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1608 $where_clauses[] = 'page_id=pr_page';
1609 $tables[] = 'page';
1610 } else {
1611 $cols = array( 'pr_expiry' );
1614 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1616 $sources = $get_pages ? array() : false;
1617 $now = wfTimestampNow();
1618 $purgeExpired = false;
1620 foreach( $res as $row ) {
1621 $expiry = Block::decodeExpiry( $row->pr_expiry );
1622 if( $expiry > $now ) {
1623 if ($get_pages) {
1624 $page_id = $row->pr_page;
1625 $page_ns = $row->page_namespace;
1626 $page_title = $row->page_title;
1627 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1628 # Add groups needed for each restriction type if its not already there
1629 # Make sure this restriction type still exists
1630 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1631 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1633 } else {
1634 $sources = true;
1636 } else {
1637 // Trigger lazy purge of expired restrictions from the db
1638 $purgeExpired = true;
1641 if( $purgeExpired ) {
1642 Title::purgeExpiredRestrictions();
1645 wfProfileOut( __METHOD__ );
1647 if ( $get_pages ) {
1648 $this->mCascadeSources = $sources;
1649 $this->mCascadingRestrictions = $pagerestrictions;
1650 } else {
1651 $this->mHasCascadingRestrictions = $sources;
1653 return array( $sources, $pagerestrictions );
1656 function areRestrictionsCascading() {
1657 if (!$this->mRestrictionsLoaded) {
1658 $this->loadRestrictions();
1661 return $this->mCascadeRestriction;
1665 * Loads a string into mRestrictions array
1666 * @param $res \type{Resource} restrictions as an SQL result.
1668 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1669 global $wgRestrictionTypes;
1670 $dbr = wfGetDB( DB_SLAVE );
1672 foreach( $wgRestrictionTypes as $type ){
1673 $this->mRestrictions[$type] = array();
1674 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry('');
1677 $this->mCascadeRestriction = false;
1679 # Backwards-compatibility: also load the restrictions from the page record (old format).
1681 if ( $oldFashionedRestrictions === NULL ) {
1682 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1683 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1686 if ($oldFashionedRestrictions != '') {
1688 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1689 $temp = explode( '=', trim( $restrict ) );
1690 if(count($temp) == 1) {
1691 // old old format should be treated as edit/move restriction
1692 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1693 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1694 } else {
1695 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1699 $this->mOldRestrictions = true;
1703 if( $dbr->numRows( $res ) ) {
1704 # Current system - load second to make them override.
1705 $now = wfTimestampNow();
1706 $purgeExpired = false;
1708 foreach( $res as $row ) {
1709 # Cycle through all the restrictions.
1711 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1712 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1713 continue;
1715 // This code should be refactored, now that it's being used more generally,
1716 // But I don't really see any harm in leaving it in Block for now -werdna
1717 $expiry = Block::decodeExpiry( $row->pr_expiry );
1719 // Only apply the restrictions if they haven't expired!
1720 if ( !$expiry || $expiry > $now ) {
1721 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
1722 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1724 $this->mCascadeRestriction |= $row->pr_cascade;
1725 } else {
1726 // Trigger a lazy purge of expired restrictions
1727 $purgeExpired = true;
1731 if( $purgeExpired ) {
1732 Title::purgeExpiredRestrictions();
1736 $this->mRestrictionsLoaded = true;
1740 * Load restrictions from the page_restrictions table
1742 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1743 if( !$this->mRestrictionsLoaded ) {
1744 if ($this->exists()) {
1745 $dbr = wfGetDB( DB_SLAVE );
1747 $res = $dbr->select( 'page_restrictions', '*',
1748 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1750 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1751 } else {
1752 $title_protection = $this->getTitleProtection();
1754 if (is_array($title_protection)) {
1755 extract($title_protection);
1757 $now = wfTimestampNow();
1758 $expiry = Block::decodeExpiry($pt_expiry);
1760 if (!$expiry || $expiry > $now) {
1761 // Apply the restrictions
1762 $this->mRestrictionsExpiry['create'] = $expiry;
1763 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1764 } else { // Get rid of the old restrictions
1765 Title::purgeExpiredRestrictions();
1767 } else {
1768 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry('');
1770 $this->mRestrictionsLoaded = true;
1776 * Purge expired restrictions from the page_restrictions table
1778 static function purgeExpiredRestrictions() {
1779 $dbw = wfGetDB( DB_MASTER );
1780 $dbw->delete( 'page_restrictions',
1781 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1782 __METHOD__ );
1784 $dbw->delete( 'protected_titles',
1785 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1786 __METHOD__ );
1790 * Accessor/initialisation for mRestrictions
1792 * @param $action \type{\string} action that permission needs to be checked for
1793 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1795 public function getRestrictions( $action ) {
1796 if( !$this->mRestrictionsLoaded ) {
1797 $this->loadRestrictions();
1799 return isset( $this->mRestrictions[$action] )
1800 ? $this->mRestrictions[$action]
1801 : array();
1805 * Get the expiry time for the restriction against a given action
1806 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1807 * or not protected at all, or false if the action is not recognised.
1809 public function getRestrictionExpiry( $action ) {
1810 if( !$this->mRestrictionsLoaded ) {
1811 $this->loadRestrictions();
1813 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
1817 * Is there a version of this page in the deletion archive?
1818 * @return \type{\int} the number of archived revisions
1820 public function isDeleted() {
1821 $fname = 'Title::isDeleted';
1822 if ( $this->getNamespace() < 0 ) {
1823 $n = 0;
1824 } else {
1825 $dbr = wfGetDB( DB_SLAVE );
1826 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1827 'ar_title' => $this->getDBkey() ), $fname );
1828 if( $this->getNamespace() == NS_IMAGE ) {
1829 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1830 array( 'fa_name' => $this->getDBkey() ), $fname );
1833 return (int)$n;
1837 * Get the article ID for this Title from the link cache,
1838 * adding it if necessary
1839 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1840 * for update
1841 * @return \type{\int} the ID
1843 public function getArticleID( $flags = 0 ) {
1844 $linkCache = LinkCache::singleton();
1845 if( $flags & GAID_FOR_UPDATE ) {
1846 $oldUpdate = $linkCache->forUpdate( true );
1847 $linkCache->clearLink( $this );
1848 $this->mArticleID = $linkCache->addLinkObj( $this );
1849 $linkCache->forUpdate( $oldUpdate );
1850 } else {
1851 if( -1 == $this->mArticleID ) {
1852 $this->mArticleID = $linkCache->addLinkObj( $this );
1855 return $this->mArticleID;
1859 * Is this an article that is a redirect page?
1860 * Uses link cache, adding it if necessary
1861 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1862 * @return \type{\bool}
1864 public function isRedirect( $flags = 0 ) {
1865 if( !is_null($this->mRedirect) )
1866 return $this->mRedirect;
1867 # Zero for special pages.
1868 # Also, calling getArticleID() loads the field from cache!
1869 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1870 return false;
1872 $linkCache = LinkCache::singleton();
1873 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1875 return $this->mRedirect;
1879 * What is the length of this page?
1880 * Uses link cache, adding it if necessary
1881 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1882 * @return \type{\bool}
1884 public function getLength( $flags = 0 ) {
1885 if( $this->mLength != -1 )
1886 return $this->mLength;
1887 # Zero for special pages.
1888 # Also, calling getArticleID() loads the field from cache!
1889 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1890 return 0;
1892 $linkCache = LinkCache::singleton();
1893 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1895 return $this->mLength;
1899 * What is the page_latest field for this page?
1900 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1901 * @return \type{\int}
1903 public function getLatestRevID( $flags = 0 ) {
1904 if( $this->mLatestID !== false )
1905 return $this->mLatestID;
1907 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1908 $this->mLatestID = $db->selectField( 'page', 'page_latest',
1909 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1910 __METHOD__ );
1911 return $this->mLatestID;
1915 * This clears some fields in this object, and clears any associated
1916 * keys in the "bad links" section of the link cache.
1918 * - This is called from Article::insertNewArticle() to allow
1919 * loading of the new page_id. It's also called from
1920 * Article::doDeleteArticle()
1922 * @param $newid \type{\int} the new Article ID
1924 public function resetArticleID( $newid ) {
1925 $linkCache = LinkCache::singleton();
1926 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1928 if ( 0 == $newid ) { $this->mArticleID = -1; }
1929 else { $this->mArticleID = $newid; }
1930 $this->mRestrictionsLoaded = false;
1931 $this->mRestrictions = array();
1935 * Updates page_touched for this page; called from LinksUpdate.php
1936 * @return \type{\bool} true if the update succeded
1938 public function invalidateCache() {
1939 global $wgUseFileCache;
1941 if ( wfReadOnly() ) {
1942 return;
1945 $dbw = wfGetDB( DB_MASTER );
1946 $success = $dbw->update( 'page',
1947 array( /* SET */
1948 'page_touched' => $dbw->timestamp()
1949 ), array( /* WHERE */
1950 'page_namespace' => $this->getNamespace() ,
1951 'page_title' => $this->getDBkey()
1952 ), 'Title::invalidateCache'
1955 if ($wgUseFileCache) {
1956 $cache = new HTMLFileCache($this);
1957 @unlink($cache->fileCacheName());
1960 return $success;
1964 * Prefix some arbitrary text with the namespace or interwiki prefix
1965 * of this object
1967 * @param $name \type{\string} the text
1968 * @return \type{\string} the prefixed text
1969 * @private
1971 /* private */ function prefix( $name ) {
1972 $p = '';
1973 if ( '' != $this->mInterwiki ) {
1974 $p = $this->mInterwiki . ':';
1976 if ( 0 != $this->mNamespace ) {
1977 $p .= $this->getNsText() . ':';
1979 return $p . $name;
1983 * Secure and split - main initialisation function for this object
1985 * Assumes that mDbkeyform has been set, and is urldecoded
1986 * and uses underscores, but not otherwise munged. This function
1987 * removes illegal characters, splits off the interwiki and
1988 * namespace prefixes, sets the other forms, and canonicalizes
1989 * everything.
1990 * @return \type{\bool} true on success
1992 private function secureAndSplit() {
1993 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1995 # Initialisation
1996 static $rxTc = false;
1997 if( !$rxTc ) {
1998 # Matching titles will be held as illegal.
1999 $rxTc = '/' .
2000 # Any character not allowed is forbidden...
2001 '[^' . Title::legalChars() . ']' .
2002 # URL percent encoding sequences interfere with the ability
2003 # to round-trip titles -- you can't link to them consistently.
2004 '|%[0-9A-Fa-f]{2}' .
2005 # XML/HTML character references produce similar issues.
2006 '|&[A-Za-z0-9\x80-\xff]+;' .
2007 '|&#[0-9]+;' .
2008 '|&#x[0-9A-Fa-f]+;' .
2009 '/S';
2012 $this->mInterwiki = $this->mFragment = '';
2013 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2015 $dbkey = $this->mDbkeyform;
2017 # Strip Unicode bidi override characters.
2018 # Sometimes they slip into cut-n-pasted page titles, where the
2019 # override chars get included in list displays.
2020 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2021 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2023 # Clean up whitespace
2025 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2026 $dbkey = trim( $dbkey, '_' );
2028 if ( '' == $dbkey ) {
2029 return false;
2032 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2033 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2034 return false;
2037 $this->mDbkeyform = $dbkey;
2039 # Initial colon indicates main namespace rather than specified default
2040 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2041 if ( ':' == $dbkey{0} ) {
2042 $this->mNamespace = NS_MAIN;
2043 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2044 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2047 # Namespace or interwiki prefix
2048 $firstPass = true;
2049 do {
2050 $m = array();
2051 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2052 $p = $m[1];
2053 if ( $ns = $wgContLang->getNsIndex( $p )) {
2054 # Ordinary namespace
2055 $dbkey = $m[2];
2056 $this->mNamespace = $ns;
2057 } elseif( Interwiki::fetch( $p ) ) {
2058 if( !$firstPass ) {
2059 # Can't make a local interwiki link to an interwiki link.
2060 # That's just crazy!
2061 return false;
2064 # Interwiki link
2065 $dbkey = $m[2];
2066 $this->mInterwiki = $wgContLang->lc( $p );
2068 # Redundant interwiki prefix to the local wiki
2069 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2070 if( $dbkey == '' ) {
2071 # Can't have an empty self-link
2072 return false;
2074 $this->mInterwiki = '';
2075 $firstPass = false;
2076 # Do another namespace split...
2077 continue;
2080 # If there's an initial colon after the interwiki, that also
2081 # resets the default namespace
2082 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2083 $this->mNamespace = NS_MAIN;
2084 $dbkey = substr( $dbkey, 1 );
2087 # If there's no recognized interwiki or namespace,
2088 # then let the colon expression be part of the title.
2090 break;
2091 } while( true );
2093 # We already know that some pages won't be in the database!
2095 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2096 $this->mArticleID = 0;
2098 $fragment = strstr( $dbkey, '#' );
2099 if ( false !== $fragment ) {
2100 $this->setFragment( $fragment );
2101 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2102 # remove whitespace again: prevents "Foo_bar_#"
2103 # becoming "Foo_bar_"
2104 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2107 # Reject illegal characters.
2109 if( preg_match( $rxTc, $dbkey ) ) {
2110 return false;
2114 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2115 * reachable due to the way web browsers deal with 'relative' URLs.
2116 * Also, they conflict with subpage syntax. Forbid them explicitly.
2118 if ( strpos( $dbkey, '.' ) !== false &&
2119 ( $dbkey === '.' || $dbkey === '..' ||
2120 strpos( $dbkey, './' ) === 0 ||
2121 strpos( $dbkey, '../' ) === 0 ||
2122 strpos( $dbkey, '/./' ) !== false ||
2123 strpos( $dbkey, '/../' ) !== false ||
2124 substr( $dbkey, -2 ) == '/.' ||
2125 substr( $dbkey, -3 ) == '/..' ) )
2127 return false;
2131 * Magic tilde sequences? Nu-uh!
2133 if( strpos( $dbkey, '~~~' ) !== false ) {
2134 return false;
2138 * Limit the size of titles to 255 bytes.
2139 * This is typically the size of the underlying database field.
2140 * We make an exception for special pages, which don't need to be stored
2141 * in the database, and may edge over 255 bytes due to subpage syntax
2142 * for long titles, e.g. [[Special:Block/Long name]]
2144 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2145 strlen( $dbkey ) > 512 )
2147 return false;
2151 * Normally, all wiki links are forced to have
2152 * an initial capital letter so [[foo]] and [[Foo]]
2153 * point to the same place.
2155 * Don't force it for interwikis, since the other
2156 * site might be case-sensitive.
2158 $this->mUserCaseDBKey = $dbkey;
2159 if( $wgCapitalLinks && $this->mInterwiki == '') {
2160 $dbkey = $wgContLang->ucfirst( $dbkey );
2164 * Can't make a link to a namespace alone...
2165 * "empty" local links can only be self-links
2166 * with a fragment identifier.
2168 if( $dbkey == '' &&
2169 $this->mInterwiki == '' &&
2170 $this->mNamespace != NS_MAIN ) {
2171 return false;
2173 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2174 // IP names are not allowed for accounts, and can only be referring to
2175 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2176 // there are numerous ways to present the same IP. Having sp:contribs scan
2177 // them all is silly and having some show the edits and others not is
2178 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2179 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2180 IP::sanitizeIP( $dbkey ) : $dbkey;
2181 // Any remaining initial :s are illegal.
2182 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2183 return false;
2186 # Fill fields
2187 $this->mDbkeyform = $dbkey;
2188 $this->mUrlform = wfUrlencode( $dbkey );
2190 $this->mTextform = str_replace( '_', ' ', $dbkey );
2192 return true;
2196 * Set the fragment for this title. Removes the first character from the
2197 * specified fragment before setting, so it assumes you're passing it with
2198 * an initial "#".
2200 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2201 * Still in active use privately.
2203 * @param $fragment \type{\string} text
2205 public function setFragment( $fragment ) {
2206 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2210 * Get a Title object associated with the talk page of this article
2211 * @return \type{Title} the object for the talk page
2213 public function getTalkPage() {
2214 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2218 * Get a title object associated with the subject page of this
2219 * talk page
2221 * @return \type{Title} the object for the subject page
2223 public function getSubjectPage() {
2224 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2228 * Get an array of Title objects linking to this Title
2229 * Also stores the IDs in the link cache.
2231 * WARNING: do not use this function on arbitrary user-supplied titles!
2232 * On heavily-used templates it will max out the memory.
2234 * @param $options \type{\string} may be FOR UPDATE
2235 * @return \type{\arrayof{Title}} the Title objects linking here
2237 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2238 $linkCache = LinkCache::singleton();
2240 if ( $options ) {
2241 $db = wfGetDB( DB_MASTER );
2242 } else {
2243 $db = wfGetDB( DB_SLAVE );
2246 $res = $db->select( array( 'page', $table ),
2247 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2248 array(
2249 "{$prefix}_from=page_id",
2250 "{$prefix}_namespace" => $this->getNamespace(),
2251 "{$prefix}_title" => $this->getDBkey() ),
2252 __METHOD__,
2253 $options );
2255 $retVal = array();
2256 if ( $db->numRows( $res ) ) {
2257 foreach( $res as $row ) {
2258 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2259 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2260 $retVal[] = $titleObj;
2264 $db->freeResult( $res );
2265 return $retVal;
2269 * Get an array of Title objects using this Title as a template
2270 * Also stores the IDs in the link cache.
2272 * WARNING: do not use this function on arbitrary user-supplied titles!
2273 * On heavily-used templates it will max out the memory.
2275 * @param $options \type{\string} may be FOR UPDATE
2276 * @return \type{\arrayof{Title}} the Title objects linking here
2278 public function getTemplateLinksTo( $options = '' ) {
2279 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2283 * Get an array of Title objects referring to non-existent articles linked from this page
2285 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2286 * @param $options \type{\string} may be FOR UPDATE
2287 * @return \type{\arrayof{Title}} the Title objects
2289 public function getBrokenLinksFrom( $options = '' ) {
2290 if ( $this->getArticleId() == 0 ) {
2291 # All links from article ID 0 are false positives
2292 return array();
2295 if ( $options ) {
2296 $db = wfGetDB( DB_MASTER );
2297 } else {
2298 $db = wfGetDB( DB_SLAVE );
2301 $res = $db->safeQuery(
2302 "SELECT pl_namespace, pl_title
2303 FROM !
2304 LEFT JOIN !
2305 ON pl_namespace=page_namespace
2306 AND pl_title=page_title
2307 WHERE pl_from=?
2308 AND page_namespace IS NULL
2310 $db->tableName( 'pagelinks' ),
2311 $db->tableName( 'page' ),
2312 $this->getArticleId(),
2313 $options );
2315 $retVal = array();
2316 if ( $db->numRows( $res ) ) {
2317 foreach( $res as $row ) {
2318 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2321 $db->freeResult( $res );
2322 return $retVal;
2327 * Get a list of URLs to purge from the Squid cache when this
2328 * page changes
2330 * @return \type{\arrayof{\string}} the URLs
2332 public function getSquidURLs() {
2333 global $wgContLang;
2335 $urls = array(
2336 $this->getInternalURL(),
2337 $this->getInternalURL( 'action=history' )
2340 // purge variant urls as well
2341 if($wgContLang->hasVariants()){
2342 $variants = $wgContLang->getVariants();
2343 foreach($variants as $vCode){
2344 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2345 $urls[] = $this->getInternalURL('',$vCode);
2349 return $urls;
2353 * Purge all applicable Squid URLs
2355 public function purgeSquid() {
2356 global $wgUseSquid;
2357 if ( $wgUseSquid ) {
2358 $urls = $this->getSquidURLs();
2359 $u = new SquidUpdate( $urls );
2360 $u->doUpdate();
2365 * Move this page without authentication
2366 * @param &$nt \type{Title} the new page Title
2368 public function moveNoAuth( &$nt ) {
2369 return $this->moveTo( $nt, false );
2373 * Check whether a given move operation would be valid.
2374 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2375 * @param &$nt \type{Title} the new title
2376 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2377 * should be checked
2378 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2379 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2381 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2382 $errors = array();
2383 if( !$nt ) {
2384 // Normally we'd add this to $errors, but we'll get
2385 // lots of syntax errors if $nt is not an object
2386 return array(array('badtitletext'));
2388 if( $this->equals( $nt ) ) {
2389 $errors[] = array('selfmove');
2391 if( !$this->isMovable() || !$nt->isMovable() ) {
2392 $errors[] = array('immobile_namespace');
2395 $oldid = $this->getArticleID();
2396 $newid = $nt->getArticleID();
2398 if ( strlen( $nt->getDBkey() ) < 1 ) {
2399 $errors[] = array('articleexists');
2401 if ( ( '' == $this->getDBkey() ) ||
2402 ( !$oldid ) ||
2403 ( '' == $nt->getDBkey() ) ) {
2404 $errors[] = array('badarticleerror');
2407 // Image-specific checks
2408 if( $this->getNamespace() == NS_IMAGE ) {
2409 $file = wfLocalFile( $this );
2410 if( $file->exists() ) {
2411 if( $nt->getNamespace() != NS_IMAGE ) {
2412 $errors[] = array('imagenocrossnamespace');
2414 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2415 $errors[] = array('imageinvalidfilename');
2417 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2418 $errors[] = array('imagetypemismatch');
2423 if ( $auth ) {
2424 global $wgUser;
2425 $errors = wfArrayMerge($errors,
2426 $this->getUserPermissionsErrors('move', $wgUser),
2427 $this->getUserPermissionsErrors('edit', $wgUser),
2428 $nt->getUserPermissionsErrors('move', $wgUser),
2429 $nt->getUserPermissionsErrors('edit', $wgUser));
2432 $match = EditPage::matchSpamRegex( $reason );
2433 if( $match !== false ) {
2434 // This is kind of lame, won't display nice
2435 $errors[] = array('spamprotectiontext');
2438 global $wgUser;
2439 $err = null;
2440 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2441 $errors[] = array('hookaborted', $err);
2444 # The move is allowed only if (1) the target doesn't exist, or
2445 # (2) the target is a redirect to the source, and has no history
2446 # (so we can undo bad moves right after they're done).
2448 if ( 0 != $newid ) { # Target exists; check for validity
2449 if ( ! $this->isValidMoveTarget( $nt ) ) {
2450 $errors[] = array('articleexists');
2452 } else {
2453 $tp = $nt->getTitleProtection();
2454 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2455 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2456 $errors[] = array('cantmove-titleprotected');
2459 if(empty($errors))
2460 return true;
2461 return $errors;
2465 * Move a title to a new location
2466 * @param &$nt \type{Title} the new title
2467 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2468 * should be checked
2469 * @param $reason \type{\string} The reason for the move
2470 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2471 * Ignored if the user doesn't have the suppressredirect right.
2472 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2474 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2475 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2476 if( is_array( $err ) ) {
2477 return $err;
2480 $pageid = $this->getArticleID();
2481 $protected = $this->isProtected();
2482 if( $nt->exists() ) {
2483 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2484 $pageCountChange = ($createRedirect ? 0 : -1);
2485 } else { # Target didn't exist, do normal move.
2486 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2487 $pageCountChange = ($createRedirect ? 1 : 0);
2490 if( is_array( $err ) ) {
2491 return $err;
2493 $redirid = $this->getArticleID();
2495 // Category memberships include a sort key which may be customized.
2496 // If it's left as the default (the page title), we need to update
2497 // the sort key to match the new title.
2499 // Be careful to avoid resetting cl_timestamp, which may disturb
2500 // time-based lists on some sites.
2502 // Warning -- if the sort key is *explicitly* set to the old title,
2503 // we can't actually distinguish it from a default here, and it'll
2504 // be set to the new title even though it really shouldn't.
2505 // It'll get corrected on the next edit, but resetting cl_timestamp.
2506 $dbw = wfGetDB( DB_MASTER );
2507 $dbw->update( 'categorylinks',
2508 array(
2509 'cl_sortkey' => $nt->getPrefixedText(),
2510 'cl_timestamp=cl_timestamp' ),
2511 array(
2512 'cl_from' => $pageid,
2513 'cl_sortkey' => $this->getPrefixedText() ),
2514 __METHOD__ );
2516 if( $protected ) {
2517 # Protect the redirect title as the title used to be...
2518 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2519 array(
2520 'pr_page' => $redirid,
2521 'pr_type' => 'pr_type',
2522 'pr_level' => 'pr_level',
2523 'pr_cascade' => 'pr_cascade',
2524 'pr_user' => 'pr_user',
2525 'pr_expiry' => 'pr_expiry'
2527 array( 'pr_page' => $pageid ),
2528 __METHOD__,
2529 array( 'IGNORE' )
2531 # Update the protection log
2532 $log = new LogPage( 'protect' );
2533 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2534 if( $reason ) $comment .= ': ' . $reason;
2535 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2538 # Update watchlists
2539 $oldnamespace = $this->getNamespace() & ~1;
2540 $newnamespace = $nt->getNamespace() & ~1;
2541 $oldtitle = $this->getDBkey();
2542 $newtitle = $nt->getDBkey();
2544 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2545 WatchedItem::duplicateEntries( $this, $nt );
2548 # Update search engine
2549 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2550 $u->doUpdate();
2551 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2552 $u->doUpdate();
2554 # Update site_stats
2555 if( $this->isContentPage() && !$nt->isContentPage() ) {
2556 # No longer a content page
2557 # Not viewed, edited, removing
2558 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2559 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2560 # Now a content page
2561 # Not viewed, edited, adding
2562 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2563 } elseif( $pageCountChange ) {
2564 # Redirect added
2565 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2566 } else {
2567 # Nothing special
2568 $u = false;
2570 if( $u )
2571 $u->doUpdate();
2572 # Update message cache for interface messages
2573 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2574 global $wgMessageCache;
2575 $oldarticle = new Article( $this );
2576 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2577 $newarticle = new Article( $nt );
2578 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2581 global $wgUser;
2582 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2583 return true;
2587 * Move page to a title which is at present a redirect to the
2588 * source page
2590 * @param &$nt \type{Title} the page to move to, which should currently
2591 * be a redirect
2592 * @param $reason \type{\string} The reason for the move
2593 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2594 * Ignored if the user doesn't have the suppressredirect right
2596 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2597 global $wgUseSquid, $wgUser;
2598 $fname = 'Title::moveOverExistingRedirect';
2599 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2601 if ( $reason ) {
2602 $comment .= ": $reason";
2605 $now = wfTimestampNow();
2606 $newid = $nt->getArticleID();
2607 $oldid = $this->getArticleID();
2608 $latest = $this->getLatestRevID();
2610 $dbw = wfGetDB( DB_MASTER );
2612 # Delete the old redirect. We don't save it to history since
2613 # by definition if we've got here it's rather uninteresting.
2614 # We have to remove it so that the next step doesn't trigger
2615 # a conflict on the unique namespace+title index...
2616 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2617 if ( !$dbw->cascadingDeletes() ) {
2618 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2619 global $wgUseTrackbacks;
2620 if ($wgUseTrackbacks)
2621 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2622 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2623 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2624 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2625 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2626 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2627 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2628 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2631 # Save a null revision in the page's history notifying of the move
2632 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2633 $nullRevId = $nullRevision->insertOn( $dbw );
2635 $article = new Article( $this );
2636 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2638 # Change the name of the target page:
2639 $dbw->update( 'page',
2640 /* SET */ array(
2641 'page_touched' => $dbw->timestamp($now),
2642 'page_namespace' => $nt->getNamespace(),
2643 'page_title' => $nt->getDBkey(),
2644 'page_latest' => $nullRevId,
2646 /* WHERE */ array( 'page_id' => $oldid ),
2647 $fname
2649 $nt->resetArticleID( $oldid );
2651 # Recreate the redirect, this time in the other direction.
2652 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2653 $mwRedir = MagicWord::get( 'redirect' );
2654 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2655 $redirectArticle = new Article( $this );
2656 $newid = $redirectArticle->insertOn( $dbw );
2657 $redirectRevision = new Revision( array(
2658 'page' => $newid,
2659 'comment' => $comment,
2660 'text' => $redirectText ) );
2661 $redirectRevision->insertOn( $dbw );
2662 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2664 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2666 # Now, we record the link from the redirect to the new title.
2667 # It should have no other outgoing links...
2668 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2669 $dbw->insert( 'pagelinks',
2670 array(
2671 'pl_from' => $newid,
2672 'pl_namespace' => $nt->getNamespace(),
2673 'pl_title' => $nt->getDBkey() ),
2674 $fname );
2675 } else {
2676 $this->resetArticleID( 0 );
2679 # Move an image if this is a file
2680 if( $this->getNamespace() == NS_IMAGE ) {
2681 $file = wfLocalFile( $this );
2682 if( $file->exists() ) {
2683 $status = $file->move( $nt );
2684 if( !$status->isOk() ) {
2685 $dbw->rollback();
2686 return $status->getErrorsArray();
2691 # Log the move
2692 $log = new LogPage( 'move' );
2693 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2695 # Purge squid
2696 if ( $wgUseSquid ) {
2697 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2698 $u = new SquidUpdate( $urls );
2699 $u->doUpdate();
2705 * Move page to non-existing title.
2706 * @param &$nt \type{Title} the new Title
2707 * @param $reason \type{\string} The reason for the move
2708 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2709 * Ignored if the user doesn't have the suppressredirect right
2711 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2712 global $wgUseSquid, $wgUser;
2713 $fname = 'MovePageForm::moveToNewTitle';
2714 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2715 if ( $reason ) {
2716 $comment .= wfMsgExt( 'colon-separator',
2717 array( 'escapenoentities', 'content' ) );
2718 $comment .= $reason;
2721 $newid = $nt->getArticleID();
2722 $oldid = $this->getArticleID();
2723 $latest = $this->getLatestRevId();
2725 $dbw = wfGetDB( DB_MASTER );
2726 $now = $dbw->timestamp();
2728 # Save a null revision in the page's history notifying of the move
2729 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2730 $nullRevId = $nullRevision->insertOn( $dbw );
2732 $article = new Article( $this );
2733 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2735 # Rename page entry
2736 $dbw->update( 'page',
2737 /* SET */ array(
2738 'page_touched' => $now,
2739 'page_namespace' => $nt->getNamespace(),
2740 'page_title' => $nt->getDBkey(),
2741 'page_latest' => $nullRevId,
2743 /* WHERE */ array( 'page_id' => $oldid ),
2744 $fname
2746 $nt->resetArticleID( $oldid );
2748 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2749 # Insert redirect
2750 $mwRedir = MagicWord::get( 'redirect' );
2751 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2752 $redirectArticle = new Article( $this );
2753 $newid = $redirectArticle->insertOn( $dbw );
2754 $redirectRevision = new Revision( array(
2755 'page' => $newid,
2756 'comment' => $comment,
2757 'text' => $redirectText ) );
2758 $redirectRevision->insertOn( $dbw );
2759 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2761 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2763 # Record the just-created redirect's linking to the page
2764 $dbw->insert( 'pagelinks',
2765 array(
2766 'pl_from' => $newid,
2767 'pl_namespace' => $nt->getNamespace(),
2768 'pl_title' => $nt->getDBkey() ),
2769 $fname );
2770 } else {
2771 $this->resetArticleID( 0 );
2774 # Move an image if this is a file
2775 if( $this->getNamespace() == NS_IMAGE ) {
2776 $file = wfLocalFile( $this );
2777 if( $file->exists() ) {
2778 $status = $file->move( $nt );
2779 if( !$status->isOk() ) {
2780 $dbw->rollback();
2781 return $status->getErrorsArray();
2786 # Log the move
2787 $log = new LogPage( 'move' );
2788 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2790 # Purge caches as per article creation
2791 Article::onArticleCreate( $nt );
2793 # Purge old title from squid
2794 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2795 $this->purgeSquid();
2800 * Checks if $this can be moved to a given Title
2801 * - Selects for update, so don't call it unless you mean business
2803 * @param &$nt \type{Title} the new title to check
2804 * @return \type{\bool} TRUE or FALSE
2806 public function isValidMoveTarget( $nt ) {
2808 $fname = 'Title::isValidMoveTarget';
2809 $dbw = wfGetDB( DB_MASTER );
2811 # Is it an existsing file?
2812 if( $nt->getNamespace() == NS_IMAGE ) {
2813 $file = wfLocalFile( $nt );
2814 if( $file->exists() ) {
2815 wfDebug( __METHOD__ . ": file exists\n" );
2816 return false;
2820 # Is it a redirect?
2821 $id = $nt->getArticleID();
2822 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2823 array( 'page_is_redirect','old_text','old_flags' ),
2824 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2825 $fname, 'FOR UPDATE' );
2827 if ( !$obj || 0 == $obj->page_is_redirect ) {
2828 # Not a redirect
2829 wfDebug( __METHOD__ . ": not a redirect\n" );
2830 return false;
2832 $text = Revision::getRevisionText( $obj );
2834 # Does the redirect point to the source?
2835 # Or is it a broken self-redirect, usually caused by namespace collisions?
2836 $m = array();
2837 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2838 $redirTitle = Title::newFromText( $m[1] );
2839 if( !is_object( $redirTitle ) ||
2840 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2841 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2842 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2843 return false;
2845 } else {
2846 # Fail safe
2847 wfDebug( __METHOD__ . ": failsafe\n" );
2848 return false;
2851 # Does the article have a history?
2852 $row = $dbw->selectRow( array( 'page', 'revision'),
2853 array( 'rev_id' ),
2854 array( 'page_namespace' => $nt->getNamespace(),
2855 'page_title' => $nt->getDBkey(),
2856 'page_id=rev_page AND page_latest != rev_id'
2857 ), $fname, 'FOR UPDATE'
2860 # Return true if there was no history
2861 return $row === false;
2865 * Can this title be added to a user's watchlist?
2867 * @return \type{\bool} TRUE or FALSE
2869 public function isWatchable() {
2870 return !$this->isExternal()
2871 && MWNamespace::isWatchable( $this->getNamespace() );
2875 * Get categories to which this Title belongs and return an array of
2876 * categories' names.
2878 * @return \type{\array} array an array of parents in the form:
2879 * $parent => $currentarticle
2881 public function getParentCategories() {
2882 global $wgContLang;
2884 $titlekey = $this->getArticleId();
2885 $dbr = wfGetDB( DB_SLAVE );
2886 $categorylinks = $dbr->tableName( 'categorylinks' );
2888 # NEW SQL
2889 $sql = "SELECT * FROM $categorylinks"
2890 ." WHERE cl_from='$titlekey'"
2891 ." AND cl_from <> '0'"
2892 ." ORDER BY cl_sortkey";
2894 $res = $dbr->query( $sql );
2896 if( $dbr->numRows( $res ) > 0 ) {
2897 foreach( $res as $row )
2898 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2899 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
2900 $dbr->freeResult( $res );
2901 } else {
2902 $data = array();
2904 return $data;
2908 * Get a tree of parent categories
2909 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2910 * @return \type{\array} Tree of parent categories
2912 public function getParentCategoryTree( $children = array() ) {
2913 $stack = array();
2914 $parents = $this->getParentCategories();
2916 if( $parents ) {
2917 foreach( $parents as $parent => $current ) {
2918 if ( array_key_exists( $parent, $children ) ) {
2919 # Circular reference
2920 $stack[$parent] = array();
2921 } else {
2922 $nt = Title::newFromText($parent);
2923 if ( $nt ) {
2924 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2928 return $stack;
2929 } else {
2930 return array();
2936 * Get an associative array for selecting this title from
2937 * the "page" table
2939 * @return \type{\array} Selection array
2941 public function pageCond() {
2942 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2946 * Get the revision ID of the previous revision
2948 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2949 * @param $flags \type{\int} GAID_FOR_UPDATE
2950 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2952 public function getPreviousRevisionID( $revId, $flags=0 ) {
2953 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2954 return $db->selectField( 'revision', 'rev_id',
2955 array(
2956 'rev_page' => $this->getArticleId($flags),
2957 'rev_id < ' . intval( $revId )
2959 __METHOD__,
2960 array( 'ORDER BY' => 'rev_id DESC' )
2965 * Get the revision ID of the next revision
2967 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
2968 * @param $flags \type{\int} GAID_FOR_UPDATE
2969 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
2971 public function getNextRevisionID( $revId, $flags=0 ) {
2972 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2973 return $db->selectField( 'revision', 'rev_id',
2974 array(
2975 'rev_page' => $this->getArticleId($flags),
2976 'rev_id > ' . intval( $revId )
2978 __METHOD__,
2979 array( 'ORDER BY' => 'rev_id' )
2984 * Get the number of revisions between the given revision IDs.
2985 * Used for diffs and other things that really need it.
2987 * @param $old \type{\int} Revision ID.
2988 * @param $new \type{\int} Revision ID.
2989 * @return \type{\int} Number of revisions between these IDs.
2991 public function countRevisionsBetween( $old, $new ) {
2992 $dbr = wfGetDB( DB_SLAVE );
2993 return $dbr->selectField( 'revision', 'count(*)',
2994 'rev_page = ' . intval( $this->getArticleId() ) .
2995 ' AND rev_id > ' . intval( $old ) .
2996 ' AND rev_id < ' . intval( $new ),
2997 __METHOD__,
2998 array( 'USE INDEX' => 'PRIMARY' ) );
3002 * Compare with another title.
3004 * @param \type{Title} $title
3005 * @return \type{\bool} TRUE or FALSE
3007 public function equals( Title $title ) {
3008 // Note: === is necessary for proper matching of number-like titles.
3009 return $this->getInterwiki() === $title->getInterwiki()
3010 && $this->getNamespace() == $title->getNamespace()
3011 && $this->getDBkey() === $title->getDBkey();
3015 * Callback for usort() to do title sorts by (namespace, title)
3017 static function compare( $a, $b ) {
3018 if( $a->getNamespace() == $b->getNamespace() ) {
3019 return strcmp( $a->getText(), $b->getText() );
3020 } else {
3021 return $a->getNamespace() - $b->getNamespace();
3026 * Return a string representation of this title
3028 * @return \type{\string} String representation of this title
3030 public function __toString() {
3031 return $this->getPrefixedText();
3035 * Check if page exists
3036 * @return \type{\bool} TRUE or FALSE
3038 public function exists() {
3039 return $this->getArticleId() != 0;
3043 * Do we know that this title definitely exists, or should we otherwise
3044 * consider that it exists?
3046 * @return \type{\bool} TRUE or FALSE
3048 public function isAlwaysKnown() {
3049 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3050 // the full l10n of that language to be loaded. That takes much memory and
3051 // isn't needed. So we strip the language part away.
3052 // Also, extension messages which are not loaded, are shown as red, because
3053 // we don't call MessageCache::loadAllMessages.
3054 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3055 return $this->isExternal()
3056 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3057 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3061 * Update page_touched timestamps and send squid purge messages for
3062 * pages linking to this title. May be sent to the job queue depending
3063 * on the number of links. Typically called on create and delete.
3065 public function touchLinks() {
3066 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3067 $u->doUpdate();
3069 if ( $this->getNamespace() == NS_CATEGORY ) {
3070 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3071 $u->doUpdate();
3076 * Get the last touched timestamp
3077 * @param Database $db, optional db
3078 * @return \type{\string} Last touched timestamp
3080 public function getTouched( $db = NULL ) {
3081 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3082 $touched = $db->selectField( 'page', 'page_touched',
3083 array(
3084 'page_namespace' => $this->getNamespace(),
3085 'page_title' => $this->getDBkey()
3086 ), __METHOD__
3088 return $touched;
3092 * Get the trackback URL for this page
3093 * @return \type{\string} Trackback URL
3095 public function trackbackURL() {
3096 global $wgScriptPath, $wgServer;
3098 return "$wgServer$wgScriptPath/trackback.php?article="
3099 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3103 * Get the trackback RDF for this page
3104 * @return \type{\string} Trackback RDF
3106 public function trackbackRDF() {
3107 $url = htmlspecialchars($this->getFullURL());
3108 $title = htmlspecialchars($this->getText());
3109 $tburl = $this->trackbackURL();
3111 // Autodiscovery RDF is placed in comments so HTML validator
3112 // won't barf. This is a rather icky workaround, but seems
3113 // frequently used by this kind of RDF thingy.
3115 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3116 return "<!--
3117 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3118 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3119 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3120 <rdf:Description
3121 rdf:about=\"$url\"
3122 dc:identifier=\"$url\"
3123 dc:title=\"$title\"
3124 trackback:ping=\"$tburl\" />
3125 </rdf:RDF>
3126 -->";
3130 * Generate strings used for xml 'id' names in monobook tabs
3131 * @return \type{\string} XML 'id' name
3133 public function getNamespaceKey() {
3134 global $wgContLang;
3135 switch ($this->getNamespace()) {
3136 case NS_MAIN:
3137 case NS_TALK:
3138 return 'nstab-main';
3139 case NS_USER:
3140 case NS_USER_TALK:
3141 return 'nstab-user';
3142 case NS_MEDIA:
3143 return 'nstab-media';
3144 case NS_SPECIAL:
3145 return 'nstab-special';
3146 case NS_PROJECT:
3147 case NS_PROJECT_TALK:
3148 return 'nstab-project';
3149 case NS_IMAGE:
3150 case NS_IMAGE_TALK:
3151 return 'nstab-image';
3152 case NS_MEDIAWIKI:
3153 case NS_MEDIAWIKI_TALK:
3154 return 'nstab-mediawiki';
3155 case NS_TEMPLATE:
3156 case NS_TEMPLATE_TALK:
3157 return 'nstab-template';
3158 case NS_HELP:
3159 case NS_HELP_TALK:
3160 return 'nstab-help';
3161 case NS_CATEGORY:
3162 case NS_CATEGORY_TALK:
3163 return 'nstab-category';
3164 default:
3165 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3170 * Returns true if this title resolves to the named special page
3171 * @param $name \type{\string} The special page name
3173 public function isSpecial( $name ) {
3174 if ( $this->getNamespace() == NS_SPECIAL ) {
3175 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3176 if ( $name == $thisName ) {
3177 return true;
3180 return false;
3184 * If the Title refers to a special page alias which is not the local default,
3185 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3187 public function fixSpecialName() {
3188 if ( $this->getNamespace() == NS_SPECIAL ) {
3189 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3190 if ( $canonicalName ) {
3191 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3192 if ( $localName != $this->mDbkeyform ) {
3193 return Title::makeTitle( NS_SPECIAL, $localName );
3197 return $this;
3201 * Is this Title in a namespace which contains content?
3202 * In other words, is this a content page, for the purposes of calculating
3203 * statistics, etc?
3205 * @return \type{\bool} TRUE or FALSE
3207 public function isContentPage() {
3208 return MWNamespace::isContent( $this->getNamespace() );
3212 * Get all extant redirects to this Title
3214 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3215 * NULL to consider all namespaces
3216 * @return \type{\arrayof{Title}} Redirects to this title
3218 public function getRedirectsHere( $ns = null ) {
3219 $redirs = array();
3221 $dbr = wfGetDB( DB_SLAVE );
3222 $where = array(
3223 'rd_namespace' => $this->getNamespace(),
3224 'rd_title' => $this->getDBkey(),
3225 'rd_from = page_id'
3227 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3229 $res = $dbr->select(
3230 array( 'redirect', 'page' ),
3231 array( 'page_namespace', 'page_title' ),
3232 $where,
3233 __METHOD__
3237 foreach( $res as $row ) {
3238 $redirs[] = self::newFromRow( $row );
3240 return $redirs;