Clarify documentation
[mediawiki.git] / includes / Title.php
blob8c256fe2f64ae6de3827ae736b4f4437b90806f4
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; ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeRestrictionSources; ///< Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
63 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN; ///< Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; ///< The page length, 0 for special pages
70 var $mRedirect = null; ///< Is the article at this title a redirect?
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)
408 public function getInterwikiLink( $key ) {
409 global $wgMemc, $wgInterwikiExpiry;
410 global $wgInterwikiCache, $wgContLang;
411 $fname = 'Title::getInterwikiLink';
413 if ( count( Title::$interwikiCache ) >= self::CACHE_MAX ) {
414 // Don't use infinite memory
415 reset( Title::$interwikiCache );
416 unset( Title::$interwikiCache[ key( Title::$interwikiCache ) ] );
419 $key = $wgContLang->lc( $key );
421 $k = wfMemcKey( 'interwiki', $key );
422 if( array_key_exists( $k, Title::$interwikiCache ) ) {
423 return Title::$interwikiCache[$k]->iw_url;
426 if ($wgInterwikiCache) {
427 return Title::getInterwikiCached( $key );
430 $s = $wgMemc->get( $k );
431 # Ignore old keys with no iw_local
432 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
433 Title::$interwikiCache[$k] = $s;
434 return $s->iw_url;
437 $dbr = wfGetDB( DB_SLAVE );
438 $res = $dbr->select( 'interwiki',
439 array( 'iw_url', 'iw_local', 'iw_trans' ),
440 array( 'iw_prefix' => $key ), $fname );
441 if( !$res ) {
442 return '';
445 $s = $dbr->fetchObject( $res );
446 if( !$s ) {
447 # Cache non-existence: create a blank object and save it to memcached
448 $s = (object)false;
449 $s->iw_url = '';
450 $s->iw_local = 0;
451 $s->iw_trans = 0;
453 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
454 Title::$interwikiCache[$k] = $s;
456 return $s->iw_url;
460 * Fetch interwiki prefix data from local cache in constant database.
462 * @note More logic is explained in DefaultSettings.
464 * @param $key \type{\string} Database key
465 * @return \type{\string} URL of interwiki site
467 public static function getInterwikiCached( $key ) {
468 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
469 static $db, $site;
471 if (!$db)
472 $db=dba_open($wgInterwikiCache,'r','cdb');
473 /* Resolve site name */
474 if ($wgInterwikiScopes>=3 and !$site) {
475 $site = dba_fetch('__sites:' . wfWikiID(), $db);
476 if ($site=="")
477 $site = $wgInterwikiFallbackSite;
479 $value = dba_fetch( wfMemcKey( $key ), $db);
480 if ($value=='' and $wgInterwikiScopes>=3) {
481 /* try site-level */
482 $value = dba_fetch("_{$site}:{$key}", $db);
484 if ($value=='' and $wgInterwikiScopes>=2) {
485 /* try globals */
486 $value = dba_fetch("__global:{$key}", $db);
488 if ($value=='undef')
489 $value='';
490 $s = (object)false;
491 $s->iw_url = '';
492 $s->iw_local = 0;
493 $s->iw_trans = 0;
494 if ($value!='') {
495 list($local,$url)=explode(' ',$value,2);
496 $s->iw_url=$url;
497 $s->iw_local=(int)$local;
499 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
500 return $s->iw_url;
504 * Determine whether the object refers to a page within
505 * this project.
507 * @return \type{\bool} TRUE if this is an in-project interwiki link
508 * or a wikilink, FALSE otherwise
510 public function isLocal() {
511 if ( $this->mInterwiki != '' ) {
512 # Make sure key is loaded into cache
513 $this->getInterwikiLink( $this->mInterwiki );
514 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
515 return (bool)(Title::$interwikiCache[$k]->iw_local);
516 } else {
517 return true;
522 * Determine whether the object refers to a page within
523 * this project and is transcludable.
525 * @return \type{\bool} TRUE if this is transcludable
527 public function isTrans() {
528 if ($this->mInterwiki == '')
529 return false;
530 # Make sure key is loaded into cache
531 $this->getInterwikiLink( $this->mInterwiki );
532 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
533 return (bool)(Title::$interwikiCache[$k]->iw_trans);
537 * Escape a text fragment, say from a link, for a URL
539 static function escapeFragmentForURL( $fragment ) {
540 $fragment = str_replace( ' ', '_', $fragment );
541 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
542 $replaceArray = array(
543 '%3A' => ':',
544 '%' => '.'
546 return strtr( $fragment, $replaceArray );
549 #----------------------------------------------------------------------------
550 # Other stuff
551 #----------------------------------------------------------------------------
553 /** Simple accessors */
555 * Get the text form (spaces not underscores) of the main part
556 * @return \type{\string} Main part of the title
558 public function getText() { return $this->mTextform; }
560 * Get the URL-encoded form of the main part
561 * @return \type{\string} Main part of the title, URL-encoded
563 public function getPartialURL() { return $this->mUrlform; }
565 * Get the main part with underscores
566 * @return \type{\string} Main part of the title, with underscores
568 public function getDBkey() { return $this->mDbkeyform; }
570 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
571 * @return \type{\int} Namespace index
573 public function getNamespace() { return $this->mNamespace; }
575 * Get the namespace text
576 * @return \type{\string} Namespace text
578 public function getNsText() {
579 global $wgContLang, $wgCanonicalNamespaceNames;
581 if ( '' != $this->mInterwiki ) {
582 // This probably shouldn't even happen. ohh man, oh yuck.
583 // But for interwiki transclusion it sometimes does.
584 // Shit. Shit shit shit.
586 // Use the canonical namespaces if possible to try to
587 // resolve a foreign namespace.
588 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
589 return $wgCanonicalNamespaceNames[$this->mNamespace];
592 return $wgContLang->getNsText( $this->mNamespace );
595 * Get the DB key with the initial letter case as specified by the user
596 * @return \type{\string} DB key
598 function getUserCaseDBKey() {
599 return $this->mUserCaseDBKey;
602 * Get the namespace text of the subject (rather than talk) page
603 * @return \type{\string} Namespace text
605 public function getSubjectNsText() {
606 global $wgContLang;
607 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
610 * Get the namespace text of the talk page
611 * @return \type{\string} Namespace text
613 public function getTalkNsText() {
614 global $wgContLang;
615 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
618 * Could this title have a corresponding talk page?
619 * @return \type{\bool} TRUE or FALSE
621 public function canTalk() {
622 return( MWNamespace::canTalk( $this->mNamespace ) );
625 * Get the interwiki prefix (or null string)
626 * @return \type{\string} Interwiki prefix
628 public function getInterwiki() { return $this->mInterwiki; }
630 * Get the Title fragment (i.e.\ the bit after the #) in text form
631 * @return \type{\string} Title fragment
633 public function getFragment() { return $this->mFragment; }
635 * Get the fragment in URL form, including the "#" character if there is one
636 * @return \type{\string} Fragment in URL form
638 public function getFragmentForURL() {
639 if ( $this->mFragment == '' ) {
640 return '';
641 } else {
642 return '#' . Title::escapeFragmentForURL( $this->mFragment );
646 * Get the default namespace index, for when there is no namespace
647 * @return \type{\int} Default namespace index
649 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
652 * Get title for search index
653 * @return \type{\string} a stripped-down title string ready for the
654 * search index
656 public function getIndexTitle() {
657 return Title::indexTitle( $this->mNamespace, $this->mTextform );
661 * Get the prefixed database key form
662 * @return \type{\string} the prefixed title, with underscores and
663 * any interwiki and namespace prefixes
665 public function getPrefixedDBkey() {
666 $s = $this->prefix( $this->mDbkeyform );
667 $s = str_replace( ' ', '_', $s );
668 return $s;
672 * Get the prefixed title with spaces.
673 * This is the form usually used for display
674 * @return \type{\string} the prefixed title, with spaces
676 public function getPrefixedText() {
677 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
678 $s = $this->prefix( $this->mTextform );
679 $s = str_replace( '_', ' ', $s );
680 $this->mPrefixedText = $s;
682 return $this->mPrefixedText;
686 * Get the prefixed title with spaces, plus any fragment
687 * (part beginning with '#')
688 * @return \type{\string} the prefixed title, with spaces and
689 * the fragment, including '#'
691 public function getFullText() {
692 $text = $this->getPrefixedText();
693 if( '' != $this->mFragment ) {
694 $text .= '#' . $this->mFragment;
696 return $text;
700 * Get the base name, i.e. the leftmost parts before the /
701 * @return \type{\string} Base name
703 public function getBaseText() {
704 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
705 return $this->getText();
708 $parts = explode( '/', $this->getText() );
709 # Don't discard the real title if there's no subpage involved
710 if( count( $parts ) > 1 )
711 unset( $parts[ count( $parts ) - 1 ] );
712 return implode( '/', $parts );
716 * Get the lowest-level subpage name, i.e. the rightmost part after /
717 * @return \type{\string} Subpage name
719 public function getSubpageText() {
720 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
721 return( $this->mTextform );
723 $parts = explode( '/', $this->mTextform );
724 return( $parts[ count( $parts ) - 1 ] );
728 * Get a URL-encoded form of the subpage text
729 * @return \type{\string} URL-encoded subpage name
731 public function getSubpageUrlForm() {
732 $text = $this->getSubpageText();
733 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
734 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
735 return( $text );
739 * Get a URL-encoded title (not an actual URL) including interwiki
740 * @return \type{\string} the URL-encoded form
742 public function getPrefixedURL() {
743 $s = $this->prefix( $this->mDbkeyform );
744 $s = str_replace( ' ', '_', $s );
746 $s = wfUrlencode ( $s ) ;
748 # Cleaning up URL to make it look nice -- is this safe?
749 $s = str_replace( '%28', '(', $s );
750 $s = str_replace( '%29', ')', $s );
752 return $s;
756 * Get a real URL referring to this title, with interwiki link and
757 * fragment
759 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
760 * links. Can be specified as an associative array as well, e.g.,
761 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
762 * @param $variant \type{\string} language variant of url (for sr, zh..)
763 * @return \type{\string} the URL
765 public function getFullURL( $query = '', $variant = false ) {
766 global $wgContLang, $wgServer, $wgRequest;
768 if( is_array( $query ) ) {
769 $query = wfArrayToCGI( $query );
772 if ( '' == $this->mInterwiki ) {
773 $url = $this->getLocalUrl( $query, $variant );
775 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
776 // Correct fix would be to move the prepending elsewhere.
777 if ($wgRequest->getVal('action') != 'render') {
778 $url = $wgServer . $url;
780 } else {
781 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
783 $namespace = wfUrlencode( $this->getNsText() );
784 if ( '' != $namespace ) {
785 # Can this actually happen? Interwikis shouldn't be parsed.
786 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
787 $namespace .= ':';
789 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
790 $url = wfAppendQuery( $url, $query );
793 # Finally, add the fragment.
794 $url .= $this->getFragmentForURL();
796 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
797 return $url;
801 * Get a URL with no fragment or server name. If this page is generated
802 * with action=render, $wgServer is prepended.
803 * @param mixed $query an optional query string; if not specified,
804 * $wgArticlePath will be used. Can be specified as an associative array
805 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
806 * URL-escaped).
807 * @param $variant \type{\string} language variant of url (for sr, zh..)
808 * @return \type{\string} the URL
810 public function getLocalURL( $query = '', $variant = false ) {
811 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
812 global $wgVariantArticlePath, $wgContLang, $wgUser;
814 if( is_array( $query ) ) {
815 $query = wfArrayToCGI( $query );
818 // internal links should point to same variant as current page (only anonymous users)
819 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
820 $pref = $wgContLang->getPreferredVariant(false);
821 if($pref != $wgContLang->getCode())
822 $variant = $pref;
825 if ( $this->isExternal() ) {
826 $url = $this->getFullURL();
827 if ( $query ) {
828 // This is currently only used for edit section links in the
829 // context of interwiki transclusion. In theory we should
830 // append the query to the end of any existing query string,
831 // but interwiki transclusion is already broken in that case.
832 $url .= "?$query";
834 } else {
835 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
836 if ( $query == '' ) {
837 if( $variant != false && $wgContLang->hasVariants() ) {
838 if( $wgVariantArticlePath == false ) {
839 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
840 } else {
841 $variantArticlePath = $wgVariantArticlePath;
843 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
844 $url = str_replace( '$1', $dbkey, $url );
845 } else {
846 $url = str_replace( '$1', $dbkey, $wgArticlePath );
848 } else {
849 global $wgActionPaths;
850 $url = false;
851 $matches = array();
852 if( !empty( $wgActionPaths ) &&
853 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
855 $action = urldecode( $matches[2] );
856 if( isset( $wgActionPaths[$action] ) ) {
857 $query = $matches[1];
858 if( isset( $matches[4] ) ) $query .= $matches[4];
859 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
860 if( $query != '' ) $url .= '?' . $query;
863 if ( $url === false ) {
864 if ( $query == '-' ) {
865 $query = '';
867 $url = "{$wgScript}?title={$dbkey}&{$query}";
871 // FIXME: this causes breakage in various places when we
872 // actually expected a local URL and end up with dupe prefixes.
873 if ($wgRequest->getVal('action') == 'render') {
874 $url = $wgServer . $url;
877 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
878 return $url;
882 * Get a URL that's the simplest URL that will be valid to link, locally,
883 * to the current Title. It includes the fragment, but does not include
884 * the server unless action=render is used (or the link is external). If
885 * there's a fragment but the prefixed text is empty, we just return a link
886 * to the fragment.
888 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
889 * query string. Keys and values will be escaped.
890 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
891 * for external links. Default is "false" (same variant as current page,
892 * for anonymous users).
893 * @return \type{\string} the URL
895 public function getLinkUrl( $query = array(), $variant = false ) {
896 if( !is_array( $query ) ) {
897 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
898 '$query' );
900 if( $this->isExternal() ) {
901 return $this->getFullURL( $query );
902 } elseif( $this->getPrefixedText() === ''
903 and $this->getFragment() !== '' ) {
904 return $this->getFragmentForURL();
905 } else {
906 return $this->getLocalURL( $query, $variant )
907 . $this->getFragmentForURL();
912 * Get an HTML-escaped version of the URL form, suitable for
913 * using in a link, without a server name or fragment
914 * @param $query \type{\string} an optional query string
915 * @return \type{\string} the URL
917 public function escapeLocalURL( $query = '' ) {
918 return htmlspecialchars( $this->getLocalURL( $query ) );
922 * Get an HTML-escaped version of the URL form, suitable for
923 * using in a link, including the server name and fragment
925 * @param $query \type{\string} an optional query string
926 * @return \type{\string} the URL
928 public function escapeFullURL( $query = '' ) {
929 return htmlspecialchars( $this->getFullURL( $query ) );
933 * Get the URL form for an internal link.
934 * - Used in various Squid-related code, in case we have a different
935 * internal hostname for the server from the exposed one.
937 * @param $query \type{\string} an optional query string
938 * @param $variant \type{\string} language variant of url (for sr, zh..)
939 * @return \type{\string} the URL
941 public function getInternalURL( $query = '', $variant = false ) {
942 global $wgInternalServer;
943 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
944 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
945 return $url;
949 * Get the edit URL for this Title
950 * @return \type{\string} the URL, or a null string if this is an
951 * interwiki link
953 public function getEditURL() {
954 if ( '' != $this->mInterwiki ) { return ''; }
955 $s = $this->getLocalURL( 'action=edit' );
957 return $s;
961 * Get the HTML-escaped displayable text form.
962 * Used for the title field in <a> tags.
963 * @return \type{\string} the text, including any prefixes
965 public function getEscapedText() {
966 return htmlspecialchars( $this->getPrefixedText() );
970 * Is this Title interwiki?
971 * @return \type{\bool}
973 public function isExternal() { return ( '' != $this->mInterwiki ); }
976 * Is this page "semi-protected" - the *only* protection is autoconfirm?
978 * @param @action \type{\string} Action to check (default: edit)
979 * @return \type{\bool}
981 public function isSemiProtected( $action = 'edit' ) {
982 if( $this->exists() ) {
983 $restrictions = $this->getRestrictions( $action );
984 if( count( $restrictions ) > 0 ) {
985 foreach( $restrictions as $restriction ) {
986 if( strtolower( $restriction ) != 'autoconfirmed' )
987 return false;
989 } else {
990 # Not protected
991 return false;
993 return true;
994 } else {
995 # If it doesn't exist, it can't be protected
996 return false;
1001 * Does the title correspond to a protected article?
1002 * @param $what \type{\string} the action the page is protected from,
1003 * by default checks move and edit
1004 * @return \type{\bool}
1006 public function isProtected( $action = '' ) {
1007 global $wgRestrictionLevels, $wgRestrictionTypes;
1009 # Special pages have inherent protection
1010 if( $this->getNamespace() == NS_SPECIAL )
1011 return true;
1013 # Check regular protection levels
1014 foreach( $wgRestrictionTypes as $type ){
1015 if( $action == $type || $action == '' ) {
1016 $r = $this->getRestrictions( $type );
1017 foreach( $wgRestrictionLevels as $level ) {
1018 if( in_array( $level, $r ) && $level != '' ) {
1019 return true;
1025 return false;
1029 * Is $wgUser watching this page?
1030 * @return \type{\bool}
1032 public function userIsWatching() {
1033 global $wgUser;
1035 if ( is_null( $this->mWatched ) ) {
1036 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1037 $this->mWatched = false;
1038 } else {
1039 $this->mWatched = $wgUser->isWatched( $this );
1042 return $this->mWatched;
1046 * Can $wgUser perform $action on this page?
1047 * This skips potentially expensive cascading permission checks.
1049 * Suitable for use for nonessential UI controls in common cases, but
1050 * _not_ for functional access control.
1052 * May provide false positives, but should never provide a false negative.
1054 * @param $action \type{\string} action that permission needs to be checked for
1055 * @return \type{\bool}
1057 public function quickUserCan( $action ) {
1058 return $this->userCan( $action, false );
1062 * Determines if $wgUser is unable to edit this page because it has been protected
1063 * by $wgNamespaceProtection.
1065 * @return \type{\bool}
1067 public function isNamespaceProtected() {
1068 global $wgNamespaceProtection, $wgUser;
1069 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
1070 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
1071 if( $right != '' && !$wgUser->isAllowed( $right ) )
1072 return true;
1075 return false;
1079 * Can $wgUser perform $action on this page?
1080 * @param $action \type{\string} action that permission needs to be checked for
1081 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1082 * @return \type{\bool}
1084 public function userCan( $action, $doExpensiveQueries = true ) {
1085 global $wgUser;
1086 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1090 * Can $user perform $action on this page?
1092 * FIXME: This *does not* check throttles (User::pingLimiter()).
1094 * @param $action \type{\string}action that permission needs to be checked for
1095 * @param $user \type{User} user to check
1096 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1097 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1098 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1100 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1101 if( !StubObject::isRealObject( $user ) ) {
1102 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1103 global $wgUser;
1104 $wgUser->_unstub( '', 5 );
1105 $user = $wgUser;
1107 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1109 global $wgContLang;
1110 global $wgLang;
1111 global $wgEmailConfirmToEdit;
1113 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1114 $errors[] = array( 'confirmedittext' );
1117 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1118 $block = $user->mBlock;
1120 // This is from OutputPage::blockedPage
1121 // Copied at r23888 by werdna
1123 $id = $user->blockedBy();
1124 $reason = $user->blockedFor();
1125 if( $reason == '' ) {
1126 $reason = wfMsg( 'blockednoreason' );
1128 $ip = wfGetIP();
1130 if ( is_numeric( $id ) ) {
1131 $name = User::whoIs( $id );
1132 } else {
1133 $name = $id;
1136 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1137 $blockid = $block->mId;
1138 $blockExpiry = $user->mBlock->mExpiry;
1139 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1141 if ( $blockExpiry == 'infinity' ) {
1142 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1143 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1145 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1146 if ( strpos( $option, ':' ) == false )
1147 continue;
1149 list ($show, $value) = explode( ":", $option );
1151 if ( $value == 'infinite' || $value == 'indefinite' ) {
1152 $blockExpiry = $show;
1153 break;
1156 } else {
1157 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1160 $intended = $user->mBlock->mAddress;
1162 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1163 $blockid, $blockExpiry, $intended, $blockTimestamp );
1166 // Remove the errors being ignored.
1168 foreach( $errors as $index => $error ) {
1169 $error_key = is_array($error) ? $error[0] : $error;
1171 if (in_array( $error_key, $ignoreErrors )) {
1172 unset($errors[$index]);
1176 return $errors;
1180 * Can $user perform $action on this page? This is an internal function,
1181 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1182 * checks on wfReadOnly() and blocks)
1184 * @param $action \type{\string} action that permission needs to be checked for
1185 * @param $user \type{User} user to check
1186 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1187 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1189 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1190 wfProfileIn( __METHOD__ );
1192 $errors = array();
1194 // Use getUserPermissionsErrors instead
1195 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1196 wfProfileOut( __METHOD__ );
1197 return $result ? array() : array( array( 'badaccess-group0' ) );
1200 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1201 if ($result != array() && is_array($result) && !is_array($result[0]))
1202 $errors[] = $result; # A single array representing an error
1203 else if (is_array($result) && is_array($result[0]))
1204 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1205 else if ($result != '' && $result != null && $result !== true && $result !== false)
1206 $errors[] = array($result); # A string representing a message-id
1207 else if ($result === false )
1208 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1210 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1211 if ($result != array() && is_array($result) && !is_array($result[0]))
1212 $errors[] = $result; # A single array representing an error
1213 else if (is_array($result) && is_array($result[0]))
1214 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1215 else if ($result != '' && $result != null && $result !== true && $result !== false)
1216 $errors[] = array($result); # A string representing a message-id
1217 else if ($result === false )
1218 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1221 $specialOKActions = array( 'createaccount', 'execute' );
1222 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1223 $errors[] = array('ns-specialprotected');
1226 if ( $this->isNamespaceProtected() ) {
1227 $ns = $this->getNamespace() == NS_MAIN
1228 ? wfMsg( 'nstab-main' )
1229 : $this->getNsText();
1230 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1231 ? array('protectedinterface')
1232 : array( 'namespaceprotected', $ns ) );
1235 if( $this->mDbkeyform == '_' ) {
1236 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1237 $errors[] = array('badaccess-group0');
1240 # protect css/js subpages of user pages
1241 # XXX: this might be better using restrictions
1242 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1243 if( $this->isCssJsSubpage()
1244 && !$user->isAllowed('editusercssjs')
1245 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1246 $errors[] = array('customcssjsprotected');
1249 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1250 # We /could/ use the protection level on the source page, but it's fairly ugly
1251 # as we have to establish a precedence hierarchy for pages included by multiple
1252 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1253 # as they could remove the protection anyway.
1254 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1255 # Cascading protection depends on more than this page...
1256 # Several cascading protected pages may include this page...
1257 # Check each cascading level
1258 # This is only for protection restrictions, not for all actions
1259 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1260 foreach( $restrictions[$action] as $right ) {
1261 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1262 if( '' != $right && !$user->isAllowed( $right ) ) {
1263 $pages = '';
1264 foreach( $cascadingSources as $page )
1265 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1266 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1272 foreach( $this->getRestrictions($action) as $right ) {
1273 // Backwards compatibility, rewrite sysop -> protect
1274 if ( $right == 'sysop' ) {
1275 $right = 'protect';
1277 if( '' != $right && !$user->isAllowed( $right ) ) {
1278 //Users with 'editprotected' permission can edit protected pages
1279 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1280 //Users with 'editprotected' permission cannot edit protected pages
1281 //with cascading option turned on.
1282 if($this->mCascadeRestriction) {
1283 $errors[] = array( 'protectedpagetext', $right );
1284 } else {
1285 //Nothing, user can edit!
1287 } else {
1288 $errors[] = array( 'protectedpagetext', $right );
1293 if ($action == 'protect') {
1294 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1295 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1299 if ($action == 'create') {
1300 $title_protection = $this->getTitleProtection();
1302 if (is_array($title_protection)) {
1303 extract($title_protection);
1305 if ($pt_create_perm == 'sysop')
1306 $pt_create_perm = 'protect';
1308 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1309 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1313 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1314 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1315 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1317 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1318 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1319 } elseif ( !$user->isAllowed( $action ) ) {
1320 $return = null;
1321 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1322 User::getGroupsWithPermission( $action ) );
1323 if ( $groups ) {
1324 $return = array( 'badaccess-groups',
1325 array(
1326 implode( ', ', $groups ),
1327 count( $groups ) ) );
1329 else {
1330 $return = array( "badaccess-group0" );
1332 $errors[] = $return;
1335 wfProfileOut( __METHOD__ );
1336 return $errors;
1340 * Is this title subject to title protection?
1341 * @return \type{\mixed} An associative array representing any existent title
1342 * protection, or false if there's none.
1344 private function getTitleProtection() {
1345 // Can't protect pages in special namespaces
1346 if ( $this->getNamespace() < 0 ) {
1347 return false;
1350 $dbr = wfGetDB( DB_SLAVE );
1351 $res = $dbr->select( 'protected_titles', '*',
1352 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1354 if ($row = $dbr->fetchRow( $res )) {
1355 return $row;
1356 } else {
1357 return false;
1362 * Update the title protection status
1363 * @param $create_perm \type{\string} Permission required for creation
1364 * @param $reason \type{\string} Reason for protection
1365 * @param $expiry \type{\string} Expiry timestamp
1367 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1368 global $wgUser,$wgContLang;
1370 if ($create_perm == implode(',',$this->getRestrictions('create'))
1371 && $expiry == $this->mRestrictionsExpiry) {
1372 // No change
1373 return true;
1376 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1378 $dbw = wfGetDB( DB_MASTER );
1380 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1382 $expiry_description = '';
1383 if ( $encodedExpiry != 'infinity' ) {
1384 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1387 # Update protection table
1388 if ($create_perm != '' ) {
1389 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1390 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1391 , 'pt_create_perm' => $create_perm
1392 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1393 , 'pt_expiry' => $encodedExpiry
1394 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1395 } else {
1396 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1397 'pt_title' => $title ), __METHOD__ );
1399 # Update the protection log
1400 $log = new LogPage( 'protect' );
1402 if( $create_perm ) {
1403 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1404 } else {
1405 $log->addEntry( 'unprotect', $this, $reason );
1408 return true;
1412 * Remove any title protection due to page existing
1414 public function deleteTitleProtection() {
1415 $dbw = wfGetDB( DB_MASTER );
1417 $dbw->delete( 'protected_titles',
1418 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1422 * Can $wgUser edit this page?
1423 * @return \type{\bool} TRUE or FALSE
1424 * @deprecated use userCan('edit')
1426 public function userCanEdit( $doExpensiveQueries = true ) {
1427 return $this->userCan( 'edit', $doExpensiveQueries );
1431 * Can $wgUser create this page?
1432 * @return \type{\bool} TRUE or FALSE
1433 * @deprecated use userCan('create')
1435 public function userCanCreate( $doExpensiveQueries = true ) {
1436 return $this->userCan( 'create', $doExpensiveQueries );
1440 * Can $wgUser move this page?
1441 * @return \type{\bool} TRUE or FALSE
1442 * @deprecated use userCan('move')
1444 public function userCanMove( $doExpensiveQueries = true ) {
1445 return $this->userCan( 'move', $doExpensiveQueries );
1449 * Would anybody with sufficient privileges be able to move this page?
1450 * Some pages just aren't movable.
1452 * @return \type{\bool} TRUE or FALSE
1454 public function isMovable() {
1455 return MWNamespace::isMovable( $this->getNamespace() )
1456 && $this->getInterwiki() == '';
1460 * Can $wgUser read this page?
1461 * @return \type{\bool} TRUE or FALSE
1462 * @todo fold these checks into userCan()
1464 public function userCanRead() {
1465 global $wgUser, $wgGroupPermissions;
1467 $result = null;
1468 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1469 if ( $result !== null ) {
1470 return $result;
1473 # Shortcut for public wikis, allows skipping quite a bit of code
1474 if ($wgGroupPermissions['*']['read'])
1475 return true;
1477 if( $wgUser->isAllowed( 'read' ) ) {
1478 return true;
1479 } else {
1480 global $wgWhitelistRead;
1483 * Always grant access to the login page.
1484 * Even anons need to be able to log in.
1486 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1487 return true;
1491 * Bail out if there isn't whitelist
1493 if( !is_array($wgWhitelistRead) ) {
1494 return false;
1498 * Check for explicit whitelisting
1500 $name = $this->getPrefixedText();
1501 $dbName = $this->getPrefixedDBKey();
1502 // Check with and without underscores
1503 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1504 return true;
1507 * Old settings might have the title prefixed with
1508 * a colon for main-namespace pages
1510 if( $this->getNamespace() == NS_MAIN ) {
1511 if( in_array( ':' . $name, $wgWhitelistRead ) )
1512 return true;
1516 * If it's a special page, ditch the subpage bit
1517 * and check again
1519 if( $this->getNamespace() == NS_SPECIAL ) {
1520 $name = $this->getDBkey();
1521 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1522 if ( $name === false ) {
1523 # Invalid special page, but we show standard login required message
1524 return false;
1527 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1528 if( in_array( $pure, $wgWhitelistRead, true ) )
1529 return true;
1533 return false;
1537 * Is this a talk page of some sort?
1538 * @return \type{\bool} TRUE or FALSE
1540 public function isTalkPage() {
1541 return MWNamespace::isTalk( $this->getNamespace() );
1545 * Is this a subpage?
1546 * @return \type{\bool} TRUE or FALSE
1548 public function isSubpage() {
1549 return MWNamespace::hasSubpages( $this->mNamespace )
1550 ? strpos( $this->getText(), '/' ) !== false
1551 : false;
1555 * Does this have subpages? (Warning, usually requires an extra DB query.)
1556 * @return \type{\bool} TRUE or FALSE
1558 public function hasSubpages() {
1559 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1560 # Duh
1561 return false;
1564 # We dynamically add a member variable for the purpose of this method
1565 # alone to cache the result. There's no point in having it hanging
1566 # around uninitialized in every Title object; therefore we only add it
1567 # if needed and don't declare it statically.
1568 if( isset( $this->mHasSubpages ) ) {
1569 return $this->mHasSubpages;
1572 $db = wfGetDB( DB_SLAVE );
1573 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1574 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1575 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1576 __METHOD__
1581 * Could this page contain custom CSS or JavaScript, based
1582 * on the title?
1584 * @return \type{\bool} TRUE or FALSE
1586 public function isCssOrJsPage() {
1587 return $this->mNamespace == NS_MEDIAWIKI
1588 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1592 * Is this a .css or .js subpage of a user page?
1593 * @return \type{\bool} TRUE or FALSE
1595 public function isCssJsSubpage() {
1596 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1599 * Is this a *valid* .css or .js subpage of a user page?
1600 * Check that the corresponding skin exists
1601 * @return \type{\bool} TRUE or FALSE
1603 public function isValidCssJsSubpage() {
1604 if ( $this->isCssJsSubpage() ) {
1605 $skinNames = Skin::getSkinNames();
1606 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1607 } else {
1608 return false;
1612 * Trim down a .css or .js subpage title to get the corresponding skin name
1614 public function getSkinFromCssJsSubpage() {
1615 $subpage = explode( '/', $this->mTextform );
1616 $subpage = $subpage[ count( $subpage ) - 1 ];
1617 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1620 * Is this a .css subpage of a user page?
1621 * @return \type{\bool} TRUE or FALSE
1623 public function isCssSubpage() {
1624 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1627 * Is this a .js subpage of a user page?
1628 * @return \type{\bool} TRUE or FALSE
1630 public function isJsSubpage() {
1631 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1634 * Protect css/js subpages of user pages: can $wgUser edit
1635 * this page?
1637 * @return \type{\bool} TRUE or FALSE
1638 * @todo XXX: this might be better using restrictions
1640 public function userCanEditCssJsSubpage() {
1641 global $wgUser;
1642 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1646 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1648 * @return \type{\bool} If the page is subject to cascading restrictions.
1650 public function isCascadeProtected() {
1651 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1652 return ( $sources > 0 );
1656 * Cascading protection: Get the source of any cascading restrictions on this page.
1658 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1659 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1660 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1661 * The restriction array is an array of each type, each of which contains an array of unique groups.
1663 public function getCascadeProtectionSources( $get_pages = true ) {
1664 global $wgRestrictionTypes;
1666 # Define our dimension of restrictions types
1667 $pagerestrictions = array();
1668 foreach( $wgRestrictionTypes as $action )
1669 $pagerestrictions[$action] = array();
1671 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1672 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1673 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1674 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1677 wfProfileIn( __METHOD__ );
1679 $dbr = wfGetDb( DB_SLAVE );
1681 if ( $this->getNamespace() == NS_IMAGE ) {
1682 $tables = array ('imagelinks', 'page_restrictions');
1683 $where_clauses = array(
1684 'il_to' => $this->getDBkey(),
1685 'il_from=pr_page',
1686 'pr_cascade' => 1 );
1687 } else {
1688 $tables = array ('templatelinks', 'page_restrictions');
1689 $where_clauses = array(
1690 'tl_namespace' => $this->getNamespace(),
1691 'tl_title' => $this->getDBkey(),
1692 'tl_from=pr_page',
1693 'pr_cascade' => 1 );
1696 if ( $get_pages ) {
1697 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1698 $where_clauses[] = 'page_id=pr_page';
1699 $tables[] = 'page';
1700 } else {
1701 $cols = array( 'pr_expiry' );
1704 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1706 $sources = $get_pages ? array() : false;
1707 $now = wfTimestampNow();
1708 $purgeExpired = false;
1710 foreach( $res as $row ) {
1711 $expiry = Block::decodeExpiry( $row->pr_expiry );
1712 if( $expiry > $now ) {
1713 if ($get_pages) {
1714 $page_id = $row->pr_page;
1715 $page_ns = $row->page_namespace;
1716 $page_title = $row->page_title;
1717 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1718 # Add groups needed for each restriction type if its not already there
1719 # Make sure this restriction type still exists
1720 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1721 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1723 } else {
1724 $sources = true;
1726 } else {
1727 // Trigger lazy purge of expired restrictions from the db
1728 $purgeExpired = true;
1731 if( $purgeExpired ) {
1732 Title::purgeExpiredRestrictions();
1735 wfProfileOut( __METHOD__ );
1737 if ( $get_pages ) {
1738 $this->mCascadeSources = $sources;
1739 $this->mCascadingRestrictions = $pagerestrictions;
1740 } else {
1741 $this->mHasCascadingRestrictions = $sources;
1744 return array( $sources, $pagerestrictions );
1747 function areRestrictionsCascading() {
1748 if (!$this->mRestrictionsLoaded) {
1749 $this->loadRestrictions();
1752 return $this->mCascadeRestriction;
1756 * Loads a string into mRestrictions array
1757 * @param $res \type{Resource} restrictions as an SQL result.
1759 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1760 global $wgRestrictionTypes;
1761 $dbr = wfGetDB( DB_SLAVE );
1763 foreach( $wgRestrictionTypes as $type ){
1764 $this->mRestrictions[$type] = array();
1767 $this->mCascadeRestriction = false;
1768 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1770 # Backwards-compatibility: also load the restrictions from the page record (old format).
1772 if ( $oldFashionedRestrictions === NULL ) {
1773 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1774 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1777 if ($oldFashionedRestrictions != '') {
1779 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1780 $temp = explode( '=', trim( $restrict ) );
1781 if(count($temp) == 1) {
1782 // old old format should be treated as edit/move restriction
1783 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1784 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1785 } else {
1786 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1790 $this->mOldRestrictions = true;
1794 if( $dbr->numRows( $res ) ) {
1795 # Current system - load second to make them override.
1796 $now = wfTimestampNow();
1797 $purgeExpired = false;
1799 foreach( $res as $row ) {
1800 # Cycle through all the restrictions.
1802 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1803 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1804 continue;
1806 // This code should be refactored, now that it's being used more generally,
1807 // But I don't really see any harm in leaving it in Block for now -werdna
1808 $expiry = Block::decodeExpiry( $row->pr_expiry );
1810 // Only apply the restrictions if they haven't expired!
1811 if ( !$expiry || $expiry > $now ) {
1812 $this->mRestrictionsExpiry = $expiry;
1813 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1815 $this->mCascadeRestriction |= $row->pr_cascade;
1816 } else {
1817 // Trigger a lazy purge of expired restrictions
1818 $purgeExpired = true;
1822 if( $purgeExpired ) {
1823 Title::purgeExpiredRestrictions();
1827 $this->mRestrictionsLoaded = true;
1831 * Load restrictions from the page_restrictions table
1833 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1834 if( !$this->mRestrictionsLoaded ) {
1835 if ($this->exists()) {
1836 $dbr = wfGetDB( DB_SLAVE );
1838 $res = $dbr->select( 'page_restrictions', '*',
1839 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1841 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1842 } else {
1843 $title_protection = $this->getTitleProtection();
1845 if (is_array($title_protection)) {
1846 extract($title_protection);
1848 $now = wfTimestampNow();
1849 $expiry = Block::decodeExpiry($pt_expiry);
1851 if (!$expiry || $expiry > $now) {
1852 // Apply the restrictions
1853 $this->mRestrictionsExpiry = $expiry;
1854 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1855 } else { // Get rid of the old restrictions
1856 Title::purgeExpiredRestrictions();
1858 } else {
1859 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1861 $this->mRestrictionsLoaded = true;
1867 * Purge expired restrictions from the page_restrictions table
1869 static function purgeExpiredRestrictions() {
1870 $dbw = wfGetDB( DB_MASTER );
1871 $dbw->delete( 'page_restrictions',
1872 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1873 __METHOD__ );
1875 $dbw->delete( 'protected_titles',
1876 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1877 __METHOD__ );
1881 * Accessor/initialisation for mRestrictions
1883 * @param $action \type{\string} action that permission needs to be checked for
1884 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1886 public function getRestrictions( $action ) {
1887 if( !$this->mRestrictionsLoaded ) {
1888 $this->loadRestrictions();
1890 return isset( $this->mRestrictions[$action] )
1891 ? $this->mRestrictions[$action]
1892 : array();
1896 * Is there a version of this page in the deletion archive?
1897 * @return \type{\int} the number of archived revisions
1899 public function isDeleted() {
1900 $fname = 'Title::isDeleted';
1901 if ( $this->getNamespace() < 0 ) {
1902 $n = 0;
1903 } else {
1904 $dbr = wfGetDB( DB_SLAVE );
1905 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1906 'ar_title' => $this->getDBkey() ), $fname );
1907 if( $this->getNamespace() == NS_IMAGE ) {
1908 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1909 array( 'fa_name' => $this->getDBkey() ), $fname );
1912 return (int)$n;
1916 * Get the article ID for this Title from the link cache,
1917 * adding it if necessary
1918 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1919 * for update
1920 * @return \type{\int} the ID
1922 public function getArticleID( $flags = 0 ) {
1923 $linkCache = LinkCache::singleton();
1924 if ( $flags & GAID_FOR_UPDATE ) {
1925 $oldUpdate = $linkCache->forUpdate( true );
1926 $this->mArticleID = $linkCache->addLinkObj( $this );
1927 $linkCache->forUpdate( $oldUpdate );
1928 } else {
1929 if ( -1 == $this->mArticleID ) {
1930 $this->mArticleID = $linkCache->addLinkObj( $this );
1933 return $this->mArticleID;
1937 * Is this an article that is a redirect page?
1938 * Uses link cache, adding it if necessary
1939 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1940 * @return \type{\bool}
1942 public function isRedirect( $flags = 0 ) {
1943 if( !is_null($this->mRedirect) )
1944 return $this->mRedirect;
1945 # Zero for special pages.
1946 # Also, calling getArticleID() loads the field from cache!
1947 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1948 return false;
1950 $linkCache = LinkCache::singleton();
1951 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1953 return $this->mRedirect;
1957 * What is the length of this page?
1958 * Uses link cache, adding it if necessary
1959 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1960 * @return \type{\bool}
1962 public function getLength( $flags = 0 ) {
1963 if( $this->mLength != -1 )
1964 return $this->mLength;
1965 # Zero for special pages.
1966 # Also, calling getArticleID() loads the field from cache!
1967 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1968 return 0;
1970 $linkCache = LinkCache::singleton();
1971 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1973 return $this->mLength;
1977 * What is the page_latest field for this page?
1978 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1979 * @return \type{\int}
1981 public function getLatestRevID( $flags = 0 ) {
1982 if( $this->mLatestID !== false )
1983 return $this->mLatestID;
1985 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1986 $this->mLatestID = $db->selectField( 'page', 'page_latest',
1987 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1988 __METHOD__ );
1989 return $this->mLatestID;
1993 * This clears some fields in this object, and clears any associated
1994 * keys in the "bad links" section of the link cache.
1996 * - This is called from Article::insertNewArticle() to allow
1997 * loading of the new page_id. It's also called from
1998 * Article::doDeleteArticle()
2000 * @param $newid \type{\int} the new Article ID
2002 public function resetArticleID( $newid ) {
2003 $linkCache = LinkCache::singleton();
2004 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2006 if ( 0 == $newid ) { $this->mArticleID = -1; }
2007 else { $this->mArticleID = $newid; }
2008 $this->mRestrictionsLoaded = false;
2009 $this->mRestrictions = array();
2013 * Updates page_touched for this page; called from LinksUpdate.php
2014 * @return \type{\bool} true if the update succeded
2016 public function invalidateCache() {
2017 global $wgUseFileCache;
2019 if ( wfReadOnly() ) {
2020 return;
2023 $dbw = wfGetDB( DB_MASTER );
2024 $success = $dbw->update( 'page',
2025 array( /* SET */
2026 'page_touched' => $dbw->timestamp()
2027 ), array( /* WHERE */
2028 'page_namespace' => $this->getNamespace() ,
2029 'page_title' => $this->getDBkey()
2030 ), 'Title::invalidateCache'
2033 if ($wgUseFileCache) {
2034 $cache = new HTMLFileCache($this);
2035 @unlink($cache->fileCacheName());
2038 return $success;
2042 * Prefix some arbitrary text with the namespace or interwiki prefix
2043 * of this object
2045 * @param $name \type{\string} the text
2046 * @return \type{\string} the prefixed text
2047 * @private
2049 /* private */ function prefix( $name ) {
2050 $p = '';
2051 if ( '' != $this->mInterwiki ) {
2052 $p = $this->mInterwiki . ':';
2054 if ( 0 != $this->mNamespace ) {
2055 $p .= $this->getNsText() . ':';
2057 return $p . $name;
2061 * Secure and split - main initialisation function for this object
2063 * Assumes that mDbkeyform has been set, and is urldecoded
2064 * and uses underscores, but not otherwise munged. This function
2065 * removes illegal characters, splits off the interwiki and
2066 * namespace prefixes, sets the other forms, and canonicalizes
2067 * everything.
2068 * @return \type{\bool} true on success
2070 private function secureAndSplit() {
2071 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2073 # Initialisation
2074 static $rxTc = false;
2075 if( !$rxTc ) {
2076 # Matching titles will be held as illegal.
2077 $rxTc = '/' .
2078 # Any character not allowed is forbidden...
2079 '[^' . Title::legalChars() . ']' .
2080 # URL percent encoding sequences interfere with the ability
2081 # to round-trip titles -- you can't link to them consistently.
2082 '|%[0-9A-Fa-f]{2}' .
2083 # XML/HTML character references produce similar issues.
2084 '|&[A-Za-z0-9\x80-\xff]+;' .
2085 '|&#[0-9]+;' .
2086 '|&#x[0-9A-Fa-f]+;' .
2087 '/S';
2090 $this->mInterwiki = $this->mFragment = '';
2091 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2093 $dbkey = $this->mDbkeyform;
2095 # Strip Unicode bidi override characters.
2096 # Sometimes they slip into cut-n-pasted page titles, where the
2097 # override chars get included in list displays.
2098 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2099 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2101 # Clean up whitespace
2103 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2104 $dbkey = trim( $dbkey, '_' );
2106 if ( '' == $dbkey ) {
2107 return false;
2110 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2111 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2112 return false;
2115 $this->mDbkeyform = $dbkey;
2117 # Initial colon indicates main namespace rather than specified default
2118 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2119 if ( ':' == $dbkey{0} ) {
2120 $this->mNamespace = NS_MAIN;
2121 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2122 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2125 # Namespace or interwiki prefix
2126 $firstPass = true;
2127 do {
2128 $m = array();
2129 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2130 $p = $m[1];
2131 if ( $ns = $wgContLang->getNsIndex( $p )) {
2132 # Ordinary namespace
2133 $dbkey = $m[2];
2134 $this->mNamespace = $ns;
2135 } elseif( $this->getInterwikiLink( $p ) ) {
2136 if( !$firstPass ) {
2137 # Can't make a local interwiki link to an interwiki link.
2138 # That's just crazy!
2139 return false;
2142 # Interwiki link
2143 $dbkey = $m[2];
2144 $this->mInterwiki = $wgContLang->lc( $p );
2146 # Redundant interwiki prefix to the local wiki
2147 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2148 if( $dbkey == '' ) {
2149 # Can't have an empty self-link
2150 return false;
2152 $this->mInterwiki = '';
2153 $firstPass = false;
2154 # Do another namespace split...
2155 continue;
2158 # If there's an initial colon after the interwiki, that also
2159 # resets the default namespace
2160 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2161 $this->mNamespace = NS_MAIN;
2162 $dbkey = substr( $dbkey, 1 );
2165 # If there's no recognized interwiki or namespace,
2166 # then let the colon expression be part of the title.
2168 break;
2169 } while( true );
2171 # We already know that some pages won't be in the database!
2173 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2174 $this->mArticleID = 0;
2176 $fragment = strstr( $dbkey, '#' );
2177 if ( false !== $fragment ) {
2178 $this->setFragment( $fragment );
2179 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2180 # remove whitespace again: prevents "Foo_bar_#"
2181 # becoming "Foo_bar_"
2182 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2185 # Reject illegal characters.
2187 if( preg_match( $rxTc, $dbkey ) ) {
2188 return false;
2192 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2193 * reachable due to the way web browsers deal with 'relative' URLs.
2194 * Also, they conflict with subpage syntax. Forbid them explicitly.
2196 if ( strpos( $dbkey, '.' ) !== false &&
2197 ( $dbkey === '.' || $dbkey === '..' ||
2198 strpos( $dbkey, './' ) === 0 ||
2199 strpos( $dbkey, '../' ) === 0 ||
2200 strpos( $dbkey, '/./' ) !== false ||
2201 strpos( $dbkey, '/../' ) !== false ||
2202 substr( $dbkey, -2 ) == '/.' ||
2203 substr( $dbkey, -3 ) == '/..' ) )
2205 return false;
2209 * Magic tilde sequences? Nu-uh!
2211 if( strpos( $dbkey, '~~~' ) !== false ) {
2212 return false;
2216 * Limit the size of titles to 255 bytes.
2217 * This is typically the size of the underlying database field.
2218 * We make an exception for special pages, which don't need to be stored
2219 * in the database, and may edge over 255 bytes due to subpage syntax
2220 * for long titles, e.g. [[Special:Block/Long name]]
2222 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2223 strlen( $dbkey ) > 512 )
2225 return false;
2229 * Normally, all wiki links are forced to have
2230 * an initial capital letter so [[foo]] and [[Foo]]
2231 * point to the same place.
2233 * Don't force it for interwikis, since the other
2234 * site might be case-sensitive.
2236 $this->mUserCaseDBKey = $dbkey;
2237 if( $wgCapitalLinks && $this->mInterwiki == '') {
2238 $dbkey = $wgContLang->ucfirst( $dbkey );
2242 * Can't make a link to a namespace alone...
2243 * "empty" local links can only be self-links
2244 * with a fragment identifier.
2246 if( $dbkey == '' &&
2247 $this->mInterwiki == '' &&
2248 $this->mNamespace != NS_MAIN ) {
2249 return false;
2251 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2252 // IP names are not allowed for accounts, and can only be referring to
2253 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2254 // there are numerous ways to present the same IP. Having sp:contribs scan
2255 // them all is silly and having some show the edits and others not is
2256 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2257 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2258 IP::sanitizeIP( $dbkey ) : $dbkey;
2259 // Any remaining initial :s are illegal.
2260 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2261 return false;
2264 # Fill fields
2265 $this->mDbkeyform = $dbkey;
2266 $this->mUrlform = wfUrlencode( $dbkey );
2268 $this->mTextform = str_replace( '_', ' ', $dbkey );
2270 return true;
2274 * Set the fragment for this title. Removes the first character from the
2275 * specified fragment before setting, so it assumes you're passing it with
2276 * an initial "#".
2278 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2279 * Still in active use privately.
2281 * @param $fragment \type{\string} text
2283 public function setFragment( $fragment ) {
2284 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2288 * Get a Title object associated with the talk page of this article
2289 * @return \type{Title} the object for the talk page
2291 public function getTalkPage() {
2292 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2296 * Get a title object associated with the subject page of this
2297 * talk page
2299 * @return \type{Title} the object for the subject page
2301 public function getSubjectPage() {
2302 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2306 * Get an array of Title objects linking to this Title
2307 * Also stores the IDs in the link cache.
2309 * WARNING: do not use this function on arbitrary user-supplied titles!
2310 * On heavily-used templates it will max out the memory.
2312 * @param $options \type{\string} may be FOR UPDATE
2313 * @return \type{\arrayof{Title}} the Title objects linking here
2315 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2316 $linkCache = LinkCache::singleton();
2318 if ( $options ) {
2319 $db = wfGetDB( DB_MASTER );
2320 } else {
2321 $db = wfGetDB( DB_SLAVE );
2324 $res = $db->select( array( 'page', $table ),
2325 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2326 array(
2327 "{$prefix}_from=page_id",
2328 "{$prefix}_namespace" => $this->getNamespace(),
2329 "{$prefix}_title" => $this->getDBkey() ),
2330 __METHOD__,
2331 $options );
2333 $retVal = array();
2334 if ( $db->numRows( $res ) ) {
2335 foreach( $res as $row ) {
2336 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2337 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2338 $retVal[] = $titleObj;
2342 $db->freeResult( $res );
2343 return $retVal;
2347 * Get an array of Title objects using this Title as a template
2348 * Also stores the IDs in the link cache.
2350 * WARNING: do not use this function on arbitrary user-supplied titles!
2351 * On heavily-used templates it will max out the memory.
2353 * @param $options \type{\string} may be FOR UPDATE
2354 * @return \type{\arrayof{Title}} the Title objects linking here
2356 public function getTemplateLinksTo( $options = '' ) {
2357 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2361 * Get an array of Title objects referring to non-existent articles linked from this page
2363 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2364 * @param $options \type{\string} may be FOR UPDATE
2365 * @return \type{\arrayof{Title}} the Title objects
2367 public function getBrokenLinksFrom( $options = '' ) {
2368 if ( $this->getArticleId() == 0 ) {
2369 # All links from article ID 0 are false positives
2370 return array();
2373 if ( $options ) {
2374 $db = wfGetDB( DB_MASTER );
2375 } else {
2376 $db = wfGetDB( DB_SLAVE );
2379 $res = $db->safeQuery(
2380 "SELECT pl_namespace, pl_title
2381 FROM !
2382 LEFT JOIN !
2383 ON pl_namespace=page_namespace
2384 AND pl_title=page_title
2385 WHERE pl_from=?
2386 AND page_namespace IS NULL
2388 $db->tableName( 'pagelinks' ),
2389 $db->tableName( 'page' ),
2390 $this->getArticleId(),
2391 $options );
2393 $retVal = array();
2394 if ( $db->numRows( $res ) ) {
2395 foreach( $res as $row ) {
2396 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2399 $db->freeResult( $res );
2400 return $retVal;
2405 * Get a list of URLs to purge from the Squid cache when this
2406 * page changes
2408 * @return \type{\arrayof{\string}} the URLs
2410 public function getSquidURLs() {
2411 global $wgContLang;
2413 $urls = array(
2414 $this->getInternalURL(),
2415 $this->getInternalURL( 'action=history' )
2418 // purge variant urls as well
2419 if($wgContLang->hasVariants()){
2420 $variants = $wgContLang->getVariants();
2421 foreach($variants as $vCode){
2422 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2423 $urls[] = $this->getInternalURL('',$vCode);
2427 return $urls;
2431 * Purge all applicable Squid URLs
2433 public function purgeSquid() {
2434 global $wgUseSquid;
2435 if ( $wgUseSquid ) {
2436 $urls = $this->getSquidURLs();
2437 $u = new SquidUpdate( $urls );
2438 $u->doUpdate();
2443 * Move this page without authentication
2444 * @param &$nt \type{Title} the new page Title
2446 public function moveNoAuth( &$nt ) {
2447 return $this->moveTo( $nt, false );
2451 * Check whether a given move operation would be valid.
2452 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2453 * @param &$nt \type{Title} the new title
2454 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2455 * should be checked
2456 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2457 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2459 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2460 $errors = array();
2461 if( !$nt ) {
2462 // Normally we'd add this to $errors, but we'll get
2463 // lots of syntax errors if $nt is not an object
2464 return array(array('badtitletext'));
2466 if( $this->equals( $nt ) ) {
2467 $errors[] = array('selfmove');
2469 if( !$this->isMovable() || !$nt->isMovable() ) {
2470 $errors[] = array('immobile_namespace');
2473 $oldid = $this->getArticleID();
2474 $newid = $nt->getArticleID();
2476 if ( strlen( $nt->getDBkey() ) < 1 ) {
2477 $errors[] = array('articleexists');
2479 if ( ( '' == $this->getDBkey() ) ||
2480 ( !$oldid ) ||
2481 ( '' == $nt->getDBkey() ) ) {
2482 $errors[] = array('badarticleerror');
2485 // Image-specific checks
2486 if( $this->getNamespace() == NS_IMAGE ) {
2487 $file = wfLocalFile( $this );
2488 if( $file->exists() ) {
2489 if( $nt->getNamespace() != NS_IMAGE ) {
2490 $errors[] = array('imagenocrossnamespace');
2492 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2493 $errors[] = array('imageinvalidfilename');
2495 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2496 $errors[] = array('imagetypemismatch');
2501 if ( $auth ) {
2502 global $wgUser;
2503 $errors = array_merge($errors,
2504 $this->getUserPermissionsErrors('move', $wgUser),
2505 $this->getUserPermissionsErrors('edit', $wgUser),
2506 $nt->getUserPermissionsErrors('move', $wgUser),
2507 $nt->getUserPermissionsErrors('edit', $wgUser));
2510 $match = EditPage::matchSpamRegex( $reason );
2511 if( $match !== false ) {
2512 // This is kind of lame, won't display nice
2513 $errors[] = array('spamprotectiontext');
2516 global $wgUser;
2517 $err = null;
2518 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2519 $errors[] = array('hookaborted', $err);
2522 # The move is allowed only if (1) the target doesn't exist, or
2523 # (2) the target is a redirect to the source, and has no history
2524 # (so we can undo bad moves right after they're done).
2526 if ( 0 != $newid ) { # Target exists; check for validity
2527 if ( ! $this->isValidMoveTarget( $nt ) ) {
2528 $errors[] = array('articleexists');
2530 } else {
2531 $tp = $nt->getTitleProtection();
2532 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2533 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2534 $errors[] = array('cantmove-titleprotected');
2537 if(empty($errors))
2538 return true;
2539 return $errors;
2543 * Move a title to a new location
2544 * @param &$nt \type{Title} the new title
2545 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2546 * should be checked
2547 * @param $reason \type{\string} The reason for the move
2548 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2549 * Ignored if the user doesn't have the suppressredirect right.
2550 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2552 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2553 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2554 if( is_array( $err ) ) {
2555 return $err;
2558 $pageid = $this->getArticleID();
2559 if( $nt->exists() ) {
2560 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2561 $pageCountChange = ($createRedirect ? 0 : -1);
2562 } else { # Target didn't exist, do normal move.
2563 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2564 $pageCountChange = ($createRedirect ? 1 : 0);
2567 if( is_array( $err ) ) {
2568 return $err;
2570 $redirid = $this->getArticleID();
2572 // Category memberships include a sort key which may be customized.
2573 // If it's left as the default (the page title), we need to update
2574 // the sort key to match the new title.
2576 // Be careful to avoid resetting cl_timestamp, which may disturb
2577 // time-based lists on some sites.
2579 // Warning -- if the sort key is *explicitly* set to the old title,
2580 // we can't actually distinguish it from a default here, and it'll
2581 // be set to the new title even though it really shouldn't.
2582 // It'll get corrected on the next edit, but resetting cl_timestamp.
2583 $dbw = wfGetDB( DB_MASTER );
2584 $dbw->update( 'categorylinks',
2585 array(
2586 'cl_sortkey' => $nt->getPrefixedText(),
2587 'cl_timestamp=cl_timestamp' ),
2588 array(
2589 'cl_from' => $pageid,
2590 'cl_sortkey' => $this->getPrefixedText() ),
2591 __METHOD__ );
2593 # Update watchlists
2595 $oldnamespace = $this->getNamespace() & ~1;
2596 $newnamespace = $nt->getNamespace() & ~1;
2597 $oldtitle = $this->getDBkey();
2598 $newtitle = $nt->getDBkey();
2600 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2601 WatchedItem::duplicateEntries( $this, $nt );
2604 # Update search engine
2605 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2606 $u->doUpdate();
2607 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2608 $u->doUpdate();
2610 # Update site_stats
2611 if( $this->isContentPage() && !$nt->isContentPage() ) {
2612 # No longer a content page
2613 # Not viewed, edited, removing
2614 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2615 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2616 # Now a content page
2617 # Not viewed, edited, adding
2618 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2619 } elseif( $pageCountChange ) {
2620 # Redirect added
2621 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2622 } else {
2623 # Nothing special
2624 $u = false;
2626 if( $u )
2627 $u->doUpdate();
2628 # Update message cache for interface messages
2629 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2630 global $wgMessageCache;
2631 $oldarticle = new Article( $this );
2632 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2633 $newarticle = new Article( $nt );
2634 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2637 global $wgUser;
2638 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2639 return true;
2643 * Move page to a title which is at present a redirect to the
2644 * source page
2646 * @param &$nt \type{Title} the page to move to, which should currently
2647 * be a redirect
2648 * @param $reason \type{\string} The reason for the move
2649 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2650 * Ignored if the user doesn't have the suppressredirect right
2652 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2653 global $wgUseSquid, $wgUser;
2654 $fname = 'Title::moveOverExistingRedirect';
2655 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2657 if ( $reason ) {
2658 $comment .= ": $reason";
2661 $now = wfTimestampNow();
2662 $newid = $nt->getArticleID();
2663 $oldid = $this->getArticleID();
2664 $latest = $this->getLatestRevID();
2666 $dbw = wfGetDB( DB_MASTER );
2667 $dbw->begin();
2669 # Delete the old redirect. We don't save it to history since
2670 # by definition if we've got here it's rather uninteresting.
2671 # We have to remove it so that the next step doesn't trigger
2672 # a conflict on the unique namespace+title index...
2673 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2674 if ( !$dbw->cascadingDeletes() ) {
2675 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2676 global $wgUseTrackbacks;
2677 if ($wgUseTrackbacks)
2678 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2679 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2680 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2681 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2682 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2683 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2684 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2685 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2688 # Save a null revision in the page's history notifying of the move
2689 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2690 $nullRevId = $nullRevision->insertOn( $dbw );
2692 $article = new Article( $this );
2693 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2695 # Change the name of the target page:
2696 $dbw->update( 'page',
2697 /* SET */ array(
2698 'page_touched' => $dbw->timestamp($now),
2699 'page_namespace' => $nt->getNamespace(),
2700 'page_title' => $nt->getDBkey(),
2701 'page_latest' => $nullRevId,
2703 /* WHERE */ array( 'page_id' => $oldid ),
2704 $fname
2706 $nt->resetArticleID( $oldid );
2708 # Recreate the redirect, this time in the other direction.
2709 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2710 $mwRedir = MagicWord::get( 'redirect' );
2711 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2712 $redirectArticle = new Article( $this );
2713 $newid = $redirectArticle->insertOn( $dbw );
2714 $redirectRevision = new Revision( array(
2715 'page' => $newid,
2716 'comment' => $comment,
2717 'text' => $redirectText ) );
2718 $redirectRevision->insertOn( $dbw );
2719 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2721 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2723 # Now, we record the link from the redirect to the new title.
2724 # It should have no other outgoing links...
2725 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2726 $dbw->insert( 'pagelinks',
2727 array(
2728 'pl_from' => $newid,
2729 'pl_namespace' => $nt->getNamespace(),
2730 'pl_title' => $nt->getDBkey() ),
2731 $fname );
2732 } else {
2733 $this->resetArticleID( 0 );
2736 # Move an image if this is a file
2737 if( $this->getNamespace() == NS_IMAGE ) {
2738 $file = wfLocalFile( $this );
2739 if( $file->exists() ) {
2740 $status = $file->move( $nt );
2741 if( !$status->isOk() ) {
2742 $dbw->rollback();
2743 return $status->getErrorsArray();
2747 $dbw->commit();
2749 # Log the move
2750 $log = new LogPage( 'move' );
2751 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2753 # Purge squid
2754 if ( $wgUseSquid ) {
2755 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2756 $u = new SquidUpdate( $urls );
2757 $u->doUpdate();
2763 * Move page to non-existing title.
2764 * @param &$nt \type{Title} the new Title
2765 * @param $reason \type{\string} The reason for the move
2766 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2767 * Ignored if the user doesn't have the suppressredirect right
2769 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2770 global $wgUseSquid, $wgUser;
2771 $fname = 'MovePageForm::moveToNewTitle';
2772 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2773 if ( $reason ) {
2774 $comment .= wfMsgExt( 'colon-separator',
2775 array( 'escapenoentities', 'content' ) );
2776 $comment .= $reason;
2779 $newid = $nt->getArticleID();
2780 $oldid = $this->getArticleID();
2781 $latest = $this->getLatestRevId();
2783 $dbw = wfGetDB( DB_MASTER );
2784 $dbw->begin();
2785 $now = $dbw->timestamp();
2787 # Save a null revision in the page's history notifying of the move
2788 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2789 $nullRevId = $nullRevision->insertOn( $dbw );
2791 $article = new Article( $this );
2792 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2794 # Rename page entry
2795 $dbw->update( 'page',
2796 /* SET */ array(
2797 'page_touched' => $now,
2798 'page_namespace' => $nt->getNamespace(),
2799 'page_title' => $nt->getDBkey(),
2800 'page_latest' => $nullRevId,
2802 /* WHERE */ array( 'page_id' => $oldid ),
2803 $fname
2805 $nt->resetArticleID( $oldid );
2807 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2808 # Insert redirect
2809 $mwRedir = MagicWord::get( 'redirect' );
2810 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2811 $redirectArticle = new Article( $this );
2812 $newid = $redirectArticle->insertOn( $dbw );
2813 $redirectRevision = new Revision( array(
2814 'page' => $newid,
2815 'comment' => $comment,
2816 'text' => $redirectText ) );
2817 $redirectRevision->insertOn( $dbw );
2818 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2820 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2822 # Record the just-created redirect's linking to the page
2823 $dbw->insert( 'pagelinks',
2824 array(
2825 'pl_from' => $newid,
2826 'pl_namespace' => $nt->getNamespace(),
2827 'pl_title' => $nt->getDBkey() ),
2828 $fname );
2829 } else {
2830 $this->resetArticleID( 0 );
2833 # Move an image if this is a file
2834 if( $this->getNamespace() == NS_IMAGE ) {
2835 $file = wfLocalFile( $this );
2836 if( $file->exists() ) {
2837 $status = $file->move( $nt );
2838 if( !$status->isOk() ) {
2839 $dbw->rollback();
2840 return $status->getErrorsArray();
2844 $dbw->commit();
2846 # Log the move
2847 $log = new LogPage( 'move' );
2848 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2850 # Purge caches as per article creation
2851 Article::onArticleCreate( $nt );
2853 # Purge old title from squid
2854 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2855 $this->purgeSquid();
2860 * Checks if $this can be moved to a given Title
2861 * - Selects for update, so don't call it unless you mean business
2863 * @param &$nt \type{Title} the new title to check
2864 * @return \type{\bool} TRUE or FALSE
2866 public function isValidMoveTarget( $nt ) {
2868 $fname = 'Title::isValidMoveTarget';
2869 $dbw = wfGetDB( DB_MASTER );
2871 # Is it an existsing file?
2872 if( $nt->getNamespace() == NS_IMAGE ) {
2873 $file = wfLocalFile( $nt );
2874 if( $file->exists() ) {
2875 wfDebug( __METHOD__ . ": file exists\n" );
2876 return false;
2880 # Is it a redirect?
2881 $id = $nt->getArticleID();
2882 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2883 array( 'page_is_redirect','old_text','old_flags' ),
2884 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2885 $fname, 'FOR UPDATE' );
2887 if ( !$obj || 0 == $obj->page_is_redirect ) {
2888 # Not a redirect
2889 wfDebug( __METHOD__ . ": not a redirect\n" );
2890 return false;
2892 $text = Revision::getRevisionText( $obj );
2894 # Does the redirect point to the source?
2895 # Or is it a broken self-redirect, usually caused by namespace collisions?
2896 $m = array();
2897 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2898 $redirTitle = Title::newFromText( $m[1] );
2899 if( !is_object( $redirTitle ) ||
2900 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2901 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2902 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2903 return false;
2905 } else {
2906 # Fail safe
2907 wfDebug( __METHOD__ . ": failsafe\n" );
2908 return false;
2911 # Does the article have a history?
2912 $row = $dbw->selectRow( array( 'page', 'revision'),
2913 array( 'rev_id' ),
2914 array( 'page_namespace' => $nt->getNamespace(),
2915 'page_title' => $nt->getDBkey(),
2916 'page_id=rev_page AND page_latest != rev_id'
2917 ), $fname, 'FOR UPDATE'
2920 # Return true if there was no history
2921 return $row === false;
2925 * Can this title be added to a user's watchlist?
2927 * @return \type{\bool} TRUE or FALSE
2929 public function isWatchable() {
2930 return !$this->isExternal()
2931 && MWNamespace::isWatchable( $this->getNamespace() );
2935 * Get categories to which this Title belongs and return an array of
2936 * categories' names.
2938 * @return \type{\array} array an array of parents in the form:
2939 * $parent => $currentarticle
2941 public function getParentCategories() {
2942 global $wgContLang;
2944 $titlekey = $this->getArticleId();
2945 $dbr = wfGetDB( DB_SLAVE );
2946 $categorylinks = $dbr->tableName( 'categorylinks' );
2948 # NEW SQL
2949 $sql = "SELECT * FROM $categorylinks"
2950 ." WHERE cl_from='$titlekey'"
2951 ." AND cl_from <> '0'"
2952 ." ORDER BY cl_sortkey";
2954 $res = $dbr->query( $sql );
2956 if( $dbr->numRows( $res ) > 0 ) {
2957 foreach( $res as $row )
2958 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2959 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
2960 $dbr->freeResult( $res );
2961 } else {
2962 $data = array();
2964 return $data;
2968 * Get a tree of parent categories
2969 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2970 * @return \type{\array} Tree of parent categories
2972 public function getParentCategoryTree( $children = array() ) {
2973 $stack = array();
2974 $parents = $this->getParentCategories();
2976 if( $parents ) {
2977 foreach( $parents as $parent => $current ) {
2978 if ( array_key_exists( $parent, $children ) ) {
2979 # Circular reference
2980 $stack[$parent] = array();
2981 } else {
2982 $nt = Title::newFromText($parent);
2983 if ( $nt ) {
2984 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2988 return $stack;
2989 } else {
2990 return array();
2996 * Get an associative array for selecting this title from
2997 * the "page" table
2999 * @return \type{\array} Selection array
3001 public function pageCond() {
3002 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3006 * Get the revision ID of the previous revision
3008 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3009 * @param $flags \type{\int} GAID_FOR_UPDATE
3010 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3012 public function getPreviousRevisionID( $revId, $flags=0 ) {
3013 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3014 return $db->selectField( 'revision', 'rev_id',
3015 array(
3016 'rev_page' => $this->getArticleId($flags),
3017 'rev_id < ' . intval( $revId )
3019 __METHOD__,
3020 array( 'ORDER BY' => 'rev_id DESC' )
3025 * Get the revision ID of the next revision
3027 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3028 * @param $flags \type{\int} GAID_FOR_UPDATE
3029 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3031 public function getNextRevisionID( $revId, $flags=0 ) {
3032 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3033 return $db->selectField( 'revision', 'rev_id',
3034 array(
3035 'rev_page' => $this->getArticleId($flags),
3036 'rev_id > ' . intval( $revId )
3038 __METHOD__,
3039 array( 'ORDER BY' => 'rev_id' )
3044 * Get the number of revisions between the given revision IDs.
3045 * Used for diffs and other things that really need it.
3047 * @param $old \type{\int} Revision ID.
3048 * @param $new \type{\int} Revision ID.
3049 * @return \type{\int} Number of revisions between these IDs.
3051 public function countRevisionsBetween( $old, $new ) {
3052 $dbr = wfGetDB( DB_SLAVE );
3053 return $dbr->selectField( 'revision', 'count(*)',
3054 'rev_page = ' . intval( $this->getArticleId() ) .
3055 ' AND rev_id > ' . intval( $old ) .
3056 ' AND rev_id < ' . intval( $new ),
3057 __METHOD__,
3058 array( 'USE INDEX' => 'PRIMARY' ) );
3062 * Compare with another title.
3064 * @param \type{Title} $title
3065 * @return \type{\bool} TRUE or FALSE
3067 public function equals( Title $title ) {
3068 // Note: === is necessary for proper matching of number-like titles.
3069 return $this->getInterwiki() === $title->getInterwiki()
3070 && $this->getNamespace() == $title->getNamespace()
3071 && $this->getDBkey() === $title->getDBkey();
3075 * Callback for usort() to do title sorts by (namespace, title)
3077 static function compare( $a, $b ) {
3078 if( $a->getNamespace() == $b->getNamespace() ) {
3079 return strcmp( $a->getText(), $b->getText() );
3080 } else {
3081 return $a->getNamespace() - $b->getNamespace();
3086 * Return a string representation of this title
3088 * @return \type{\string} String representation of this title
3090 public function __toString() {
3091 return $this->getPrefixedText();
3095 * Check if page exists
3096 * @return \type{\bool} TRUE or FALSE
3098 public function exists() {
3099 return $this->getArticleId() != 0;
3103 * Do we know that this title definitely exists, or should we otherwise
3104 * consider that it exists?
3106 * @return \type{\bool} TRUE or FALSE
3108 public function isAlwaysKnown() {
3109 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3110 // the full l10n of that language to be loaded. That takes much memory and
3111 // isn't needed. So we strip the language part away.
3112 // Also, extension messages which are not loaded, are shown as red, because
3113 // we don't call MessageCache::loadAllMessages.
3114 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3115 return $this->isExternal()
3116 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3117 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3121 * Update page_touched timestamps and send squid purge messages for
3122 * pages linking to this title. May be sent to the job queue depending
3123 * on the number of links. Typically called on create and delete.
3125 public function touchLinks() {
3126 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3127 $u->doUpdate();
3129 if ( $this->getNamespace() == NS_CATEGORY ) {
3130 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3131 $u->doUpdate();
3136 * Get the last touched timestamp
3137 * @param Database $db, optional db
3138 * @return \type{\string} Last touched timestamp
3140 public function getTouched( $db = NULL ) {
3141 $db = isset($db) ? $db : wfGetDB( DB_SLAVE );
3142 $touched = $db->selectField( 'page', 'page_touched',
3143 array(
3144 'page_namespace' => $this->getNamespace(),
3145 'page_title' => $this->getDBkey()
3146 ), __METHOD__
3148 return $touched;
3152 * Get the trackback URL for this page
3153 * @return \type{\string} Trackback URL
3155 public function trackbackURL() {
3156 global $wgTitle, $wgScriptPath, $wgServer;
3158 return "$wgServer$wgScriptPath/trackback.php?article="
3159 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3163 * Get the trackback RDF for this page
3164 * @return \type{\string} Trackback RDF
3166 public function trackbackRDF() {
3167 $url = htmlspecialchars($this->getFullURL());
3168 $title = htmlspecialchars($this->getText());
3169 $tburl = $this->trackbackURL();
3171 // Autodiscovery RDF is placed in comments so HTML validator
3172 // won't barf. This is a rather icky workaround, but seems
3173 // frequently used by this kind of RDF thingy.
3175 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3176 return "<!--
3177 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3178 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3179 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3180 <rdf:Description
3181 rdf:about=\"$url\"
3182 dc:identifier=\"$url\"
3183 dc:title=\"$title\"
3184 trackback:ping=\"$tburl\" />
3185 </rdf:RDF>
3186 -->";
3190 * Generate strings used for xml 'id' names in monobook tabs
3191 * @return \type{\string} XML 'id' name
3193 public function getNamespaceKey() {
3194 global $wgContLang;
3195 switch ($this->getNamespace()) {
3196 case NS_MAIN:
3197 case NS_TALK:
3198 return 'nstab-main';
3199 case NS_USER:
3200 case NS_USER_TALK:
3201 return 'nstab-user';
3202 case NS_MEDIA:
3203 return 'nstab-media';
3204 case NS_SPECIAL:
3205 return 'nstab-special';
3206 case NS_PROJECT:
3207 case NS_PROJECT_TALK:
3208 return 'nstab-project';
3209 case NS_IMAGE:
3210 case NS_IMAGE_TALK:
3211 return 'nstab-image';
3212 case NS_MEDIAWIKI:
3213 case NS_MEDIAWIKI_TALK:
3214 return 'nstab-mediawiki';
3215 case NS_TEMPLATE:
3216 case NS_TEMPLATE_TALK:
3217 return 'nstab-template';
3218 case NS_HELP:
3219 case NS_HELP_TALK:
3220 return 'nstab-help';
3221 case NS_CATEGORY:
3222 case NS_CATEGORY_TALK:
3223 return 'nstab-category';
3224 default:
3225 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3230 * Returns true if this title resolves to the named special page
3231 * @param $name \type{\string} The special page name
3233 public function isSpecial( $name ) {
3234 if ( $this->getNamespace() == NS_SPECIAL ) {
3235 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3236 if ( $name == $thisName ) {
3237 return true;
3240 return false;
3244 * If the Title refers to a special page alias which is not the local default,
3245 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3247 public function fixSpecialName() {
3248 if ( $this->getNamespace() == NS_SPECIAL ) {
3249 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3250 if ( $canonicalName ) {
3251 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3252 if ( $localName != $this->mDbkeyform ) {
3253 return Title::makeTitle( NS_SPECIAL, $localName );
3257 return $this;
3261 * Is this Title in a namespace which contains content?
3262 * In other words, is this a content page, for the purposes of calculating
3263 * statistics, etc?
3265 * @return \type{\bool} TRUE or FALSE
3267 public function isContentPage() {
3268 return MWNamespace::isContent( $this->getNamespace() );
3272 * Get all extant redirects to this Title
3274 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3275 * NULL to consider all namespaces
3276 * @return \type{\arrayof{Title}} Redirects to this title
3278 public function getRedirectsHere( $ns = null ) {
3279 $redirs = array();
3281 $dbr = wfGetDB( DB_SLAVE );
3282 $where = array(
3283 'rd_namespace' => $this->getNamespace(),
3284 'rd_title' => $this->getDBkey(),
3285 'rd_from = page_id'
3287 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3289 $res = $dbr->select(
3290 array( 'redirect', 'page' ),
3291 array( 'page_namespace', 'page_title' ),
3292 $where,
3293 __METHOD__
3297 foreach( $res as $row ) {
3298 $redirs[] = self::newFromRow( $row );
3300 return $redirs;