fixed potential XSS vulnerability
[mediawiki.git] / includes / Title.php
blobf663096094b69708a986eba5599b4de0d8ca8829
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
8 require_once( 'normal/UtfNormal.php' );
10 $wgTitleInterwikiCache = array();
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
17 # reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
20 /**
21 * Title class
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
25 * @package MediaWiki
27 class Title {
28 /**
29 * All member variables should be considered private
30 * Please use the accessor functions
33 /**#@+
34 * @access private
37 var $mTextform; # Text form (spaces not underscores) of the main part
38 var $mUrlform; # URL-encoded form of the main part
39 var $mDbkeyform; # Main part with underscores
40 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
41 var $mInterwiki; # Interwiki prefix (or null string)
42 var $mFragment; # Title fragment (i.e. the bit after the #)
43 var $mArticleID; # Article ID, fetched from the link cache on demand
44 var $mRestrictions; # Array of groups allowed to edit this article
45 # Only null or "sysop" are supported
46 var $mRestrictionsLoaded; # Boolean for initialisation on demand
47 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
48 var $mDefaultNamespace; # Namespace index when there is no namespace
49 # Zero except in {{transclusion}} tags
50 /**#@-*/
53 /**
54 * Constructor
55 * @access private
57 /* private */ function Title() {
58 $this->mInterwiki = $this->mUrlform =
59 $this->mTextform = $this->mDbkeyform = '';
60 $this->mArticleID = -1;
61 $this->mNamespace = NS_MAIN;
62 $this->mRestrictionsLoaded = false;
63 $this->mRestrictions = array();
64 # Dont change the following, NS_MAIN is hardcoded in several place
65 # See bug #696
66 $this->mDefaultNamespace = NS_MAIN;
69 /**
70 * Create a new Title from a prefixed DB key
71 * @param string $key The database key, which has underscores
72 * instead of spaces, possibly including namespace and
73 * interwiki prefixes
74 * @return Title the new object, or NULL on an error
75 * @static
76 * @access public
78 /* static */ function newFromDBkey( $key ) {
79 $t = new Title();
80 $t->mDbkeyform = $key;
81 if( $t->secureAndSplit() )
82 return $t;
83 else
84 return NULL;
87 /**
88 * Create a new Title from text, such as what one would
89 * find in a link. Decodes any HTML entities in the text.
91 * @param string $text the link text; spaces, prefixes,
92 * and an initial ':' indicating the main namespace
93 * are accepted
94 * @param int $defaultNamespace the namespace to use if
95 * none is specified by a prefix
96 * @return Title the new object, or NULL on an error
97 * @static
98 * @access public
100 function &newFromText( $text, $defaultNamespace = NS_MAIN ) {
101 $fname = 'Title::newFromText';
102 wfProfileIn( $fname );
104 if( is_object( $text ) ) {
105 wfDebugDieBacktrace( 'Title::newFromText given an object' );
109 * Wiki pages often contain multiple links to the same page.
110 * Title normalization and parsing can become expensive on
111 * pages with many links, so we can save a little time by
112 * caching them.
114 * In theory these are value objects and won't get changed...
116 static $titleCache = array();
117 if( $defaultNamespace == NS_MAIN && isset( $titleCache[$text] ) ) {
118 wfProfileOut( $fname );
119 return $titleCache[$text];
123 * Convert things like &eacute; into real text...
125 global $wgInputEncoding;
126 $filteredText = do_html_entity_decode( $text, ENT_COMPAT, $wgInputEncoding );
129 * Convert things like &#257; or &#x3017; into real text...
130 * WARNING: Not friendly to internal links on a latin-1 wiki.
132 $filteredText = wfMungeToUtf8( $filteredText );
134 # What was this for? TS 2004-03-03
135 # $text = urldecode( $text );
137 $t =& new Title();
138 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
139 $t->mDefaultNamespace = $defaultNamespace;
141 if( $t->secureAndSplit() ) {
142 if( $defaultNamespace == NS_MAIN ) {
143 if( count( $titleCache ) >= MW_TITLECACHE_MAX ) {
144 # Avoid memory leaks on mass operations...
145 $titleCache = array();
147 $titleCache[$text] =& $t;
149 wfProfileOut( $fname );
150 return $t;
151 } else {
152 wfProfileOut( $fname );
153 return NULL;
158 * Create a new Title from URL-encoded text. Ensures that
159 * the given title's length does not exceed the maximum.
160 * @param string $url the title, as might be taken from a URL
161 * @return Title the new object, or NULL on an error
162 * @static
163 * @access public
165 function newFromURL( $url ) {
166 global $wgLang, $wgServer;
167 $t = new Title();
169 # For compatibility with old buggy URLs. "+" is not valid in titles,
170 # but some URLs used it as a space replacement and they still come
171 # from some external search tools.
172 $s = str_replace( '+', ' ', $url );
174 $t->mDbkeyform = str_replace( ' ', '_', $s );
175 if( $t->secureAndSplit() ) {
176 return $t;
177 } else {
178 return NULL;
183 * Create a new Title from an article ID
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
190 * @access public
191 * @static
193 function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE );
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
200 } else {
201 $title = NULL;
203 return $title;
207 * Create a new Title from a namespace index and a DB key.
208 * It's assumed that $ns and $title are *valid*, for instance when
209 * they came directly from the database or a special page name.
210 * For convenience, spaces are converted to underscores so that
211 * eg user_text fields can be used directly.
213 * @param int $ns the namespace of the article
214 * @param string $title the unprefixed database key form
215 * @return Title the new object
216 * @static
217 * @access public
219 function &makeTitle( $ns, $title ) {
220 $t =& new Title();
221 $t->mInterwiki = '';
222 $t->mFragment = '';
223 $t->mNamespace = IntVal( $ns );
224 $t->mDbkeyform = str_replace( ' ', '_', $title );
225 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
226 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
227 $t->mTextform = str_replace( '_', ' ', $title );
228 return $t;
232 * Create a new Title frrom a namespace index and a DB key.
233 * The parameters will be checked for validity, which is a bit slower
234 * than makeTitle() but safer for user-provided data.
236 * @param int $ns the namespace of the article
237 * @param string $title the database key form
238 * @return Title the new object, or NULL on an error
239 * @static
240 * @access public
242 function makeTitleSafe( $ns, $title ) {
243 $t = new Title();
244 $t->mDbkeyform = Title::makeName( $ns, $title );
245 if( $t->secureAndSplit() ) {
246 return $t;
247 } else {
248 return NULL;
253 * Create a new Title for the Main Page
255 * @static
256 * @return Title the new object
257 * @access public
259 function newMainPage() {
260 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
264 * Create a new Title for a redirect
265 * @param string $text the redirect title text
266 * @return Title the new object, or NULL if the text is not a
267 * valid redirect
268 * @static
269 * @access public
271 function newFromRedirect( $text ) {
272 global $wgMwRedir;
273 $rt = NULL;
274 if ( $wgMwRedir->matchStart( $text ) ) {
275 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
276 # categories are escaped using : for example one can enter:
277 # #REDIRECT [[:Category:Music]]. Need to remove it.
278 if ( substr($m[1],0,1) == ':') {
279 # We don't want to keep the ':'
280 $m[1] = substr( $m[1], 1 );
283 $rt = Title::newFromText( $m[1] );
284 # Disallow redirects to Special:Userlogout
285 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
286 $rt = NULL;
290 return $rt;
293 #----------------------------------------------------------------------------
294 # Static functions
295 #----------------------------------------------------------------------------
298 * Get the prefixed DB key associated with an ID
299 * @param int $id the page_id of the article
300 * @return Title an object representing the article, or NULL
301 * if no such article was found
302 * @static
303 * @access public
305 function nameOf( $id ) {
306 $fname = 'Title::nameOf';
307 $dbr =& wfGetDB( DB_SLAVE );
309 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
310 if ( $s === false ) { return NULL; }
312 $n = Title::makeName( $s->page_namespace, $s->page_title );
313 return $n;
317 * Get a regex character class describing the legal characters in a link
318 * @return string the list of characters, not delimited
319 * @static
320 * @access public
322 /* static */ function legalChars() {
323 # Missing characters:
324 # * []|# Needed for link syntax
325 # * % and + are corrupted by Apache when they appear in the path
327 # % seems to work though
329 # The problem with % is that URLs are double-unescaped: once by Apache's
330 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
331 # Our code does not double-escape to compensate for this, indeed double escaping
332 # would break if the double-escaped title was passed in the query string
333 # rather than the path. This is a minor security issue because articles can be
334 # created such that they are hard to view or edit. -- TS
336 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
337 # this breaks interlanguage links
339 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
340 return $set;
344 * Get a string representation of a title suitable for
345 * including in a search index
347 * @param int $ns a namespace index
348 * @param string $title text-form main part
349 * @return string a stripped-down title string ready for the
350 * search index
352 /* static */ function indexTitle( $ns, $title ) {
353 global $wgDBminWordLen, $wgContLang;
354 require_once( 'SearchEngine.php' );
356 $lc = SearchEngine::legalSearchChars() . '&#;';
357 $t = $wgContLang->stripForSearch( $title );
358 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
359 $t = strtolower( $t );
361 # Handle 's, s'
362 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
363 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
365 $t = preg_replace( "/\\s+/", ' ', $t );
367 if ( $ns == NS_IMAGE ) {
368 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
370 return trim( $t );
374 * Make a prefixed DB key from a DB key and a namespace index
375 * @param int $ns numerical representation of the namespace
376 * @param string $title the DB key form the title
377 * @return string the prefixed form of the title
379 /* static */ function makeName( $ns, $title ) {
380 global $wgContLang;
382 $n = $wgContLang->getNsText( $ns );
383 return $n == '' ? $title : "$n:$title";
387 * Returns the URL associated with an interwiki prefix
388 * @param string $key the interwiki prefix (e.g. "MeatBall")
389 * @return the associated URL, containing "$1", which should be
390 * replaced by an article title
391 * @static (arguably)
392 * @access public
394 function getInterwikiLink( $key ) {
395 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
396 $fname = 'Title::getInterwikiLink';
398 wfProfileIn( $fname );
400 $k = $wgDBname.':interwiki:'.$key;
401 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
402 wfProfileOut( $fname );
403 return $wgTitleInterwikiCache[$k]->iw_url;
406 $s = $wgMemc->get( $k );
407 # Ignore old keys with no iw_local
408 if( $s && isset( $s->iw_local ) ) {
409 $wgTitleInterwikiCache[$k] = $s;
410 wfProfileOut( $fname );
411 return $s->iw_url;
414 $dbr =& wfGetDB( DB_SLAVE );
415 $res = $dbr->select( 'interwiki',
416 array( 'iw_url', 'iw_local' ),
417 array( 'iw_prefix' => $key ), $fname );
418 if( !$res ) {
419 wfProfileOut( $fname );
420 return '';
423 $s = $dbr->fetchObject( $res );
424 if( !$s ) {
425 # Cache non-existence: create a blank object and save it to memcached
426 $s = (object)false;
427 $s->iw_url = '';
428 $s->iw_local = 0;
430 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
431 $wgTitleInterwikiCache[$k] = $s;
433 wfProfileOut( $fname );
434 return $s->iw_url;
438 * Determine whether the object refers to a page within
439 * this project.
441 * @return bool TRUE if this is an in-project interwiki link
442 * or a wikilink, FALSE otherwise
443 * @access public
445 function isLocal() {
446 global $wgTitleInterwikiCache, $wgDBname;
448 if ( $this->mInterwiki != '' ) {
449 # Make sure key is loaded into cache
450 $this->getInterwikiLink( $this->mInterwiki );
451 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
452 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
453 } else {
454 return true;
459 * Update the page_touched field for an array of title objects
460 * @todo Inefficient unless the IDs are already loaded into the
461 * link cache
462 * @param array $titles an array of Title objects to be touched
463 * @param string $timestamp the timestamp to use instead of the
464 * default current time
465 * @static
466 * @access public
468 function touchArray( $titles, $timestamp = '' ) {
469 if ( count( $titles ) == 0 ) {
470 return;
472 $dbw =& wfGetDB( DB_MASTER );
473 if ( $timestamp == '' ) {
474 $timestamp = $dbw->timestamp();
476 $page = $dbw->tableName( 'page' );
477 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
478 $first = true;
480 foreach ( $titles as $title ) {
481 if ( ! $first ) {
482 $sql .= ',';
484 $first = false;
485 $sql .= $title->getArticleID();
487 $sql .= ')';
488 if ( ! $first ) {
489 $dbw->query( $sql, 'Title::touchArray' );
493 #----------------------------------------------------------------------------
494 # Other stuff
495 #----------------------------------------------------------------------------
497 /** Simple accessors */
499 * Get the text form (spaces not underscores) of the main part
500 * @return string
501 * @access public
503 function getText() { return $this->mTextform; }
505 * Get the URL-encoded form of the main part
506 * @return string
507 * @access public
509 function getPartialURL() { return $this->mUrlform; }
511 * Get the main part with underscores
512 * @return string
513 * @access public
515 function getDBkey() { return $this->mDbkeyform; }
517 * Get the namespace index, i.e. one of the NS_xxxx constants
518 * @return int
519 * @access public
521 function getNamespace() { return $this->mNamespace; }
523 * Get the interwiki prefix (or null string)
524 * @return string
525 * @access public
527 function getInterwiki() { return $this->mInterwiki; }
529 * Get the Title fragment (i.e. the bit after the #)
530 * @return string
531 * @access public
533 function getFragment() { return $this->mFragment; }
535 * Get the default namespace index, for when there is no namespace
536 * @return int
537 * @access public
539 function getDefaultNamespace() { return $this->mDefaultNamespace; }
542 * Get title for search index
543 * @return string a stripped-down title string ready for the
544 * search index
546 function getIndexTitle() {
547 return Title::indexTitle( $this->mNamespace, $this->mTextform );
551 * Get the prefixed database key form
552 * @return string the prefixed title, with underscores and
553 * any interwiki and namespace prefixes
554 * @access public
556 function getPrefixedDBkey() {
557 $s = $this->prefix( $this->mDbkeyform );
558 $s = str_replace( ' ', '_', $s );
559 return $s;
563 * Get the prefixed title with spaces.
564 * This is the form usually used for display
565 * @return string the prefixed title, with spaces
566 * @access public
568 function getPrefixedText() {
569 global $wgContLang;
570 if ( empty( $this->mPrefixedText ) ) {
571 $s = $this->prefix( $this->mTextform );
572 $s = str_replace( '_', ' ', $s );
573 $this->mPrefixedText = $s;
575 return $this->mPrefixedText;
579 * Get the prefixed title with spaces, plus any fragment
580 * (part beginning with '#')
581 * @return string the prefixed title, with spaces and
582 * the fragment, including '#'
583 * @access public
585 function getFullText() {
586 global $wgContLang;
587 $text = $this->getPrefixedText();
588 if( '' != $this->mFragment ) {
589 $text .= '#' . $this->mFragment;
591 return $text;
595 * Get a URL-encoded title (not an actual URL) including interwiki
596 * @return string the URL-encoded form
597 * @access public
599 function getPrefixedURL() {
600 $s = $this->prefix( $this->mDbkeyform );
601 $s = str_replace( ' ', '_', $s );
603 $s = wfUrlencode ( $s ) ;
605 # Cleaning up URL to make it look nice -- is this safe?
606 $s = str_replace( '%28', '(', $s );
607 $s = str_replace( '%29', ')', $s );
609 return $s;
613 * Get a real URL referring to this title, with interwiki link and
614 * fragment
616 * @param string $query an optional query string, not used
617 * for interwiki links
618 * @return string the URL
619 * @access public
621 function getFullURL( $query = '' ) {
622 global $wgContLang, $wgServer, $wgScript;
624 if ( '' == $this->mInterwiki ) {
625 return $wgServer . $this->getLocalUrl( $query );
626 } else {
627 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
628 $namespace = $wgContLang->getNsText( $this->mNamespace );
629 if ( '' != $namespace ) {
630 # Can this actually happen? Interwikis shouldn't be parsed.
631 $namepace .= ':';
633 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
634 if( $query != '' ) {
635 if( false === strpos( $url, '?' ) ) {
636 $url .= '?';
637 } else {
638 $url .= '&';
640 $url .= $query;
642 if ( '' != $this->mFragment ) {
643 $url .= '#' . $this->mFragment;
645 return $url;
649 /**
650 * Get a relative directory for putting an HTML version of this article into
652 function getHashedDirectory() {
653 $dbkey = $this->getPrefixedDBkey();
654 if ( strlen( $dbkey ) < 2 ) {
655 $dbkey = sprintf( "%2s", $dbkey );
657 $dir = '';
658 for ( $i=0; $i<=1; $i++ ) {
659 if ( $i ) {
660 $dir .= '/';
662 if ( ord( $dbkey{$i} ) < 128 && ord( $dbkey{$i} ) > 32 ) {
663 $dir .= strtolower( $dbkey{$i} );
664 } else {
665 $dir .= sprintf( "%02X", ord( $dbkey{$i} ) );
668 return $dir;
671 function getHashedFilename() {
672 $dbkey = $this->getPrefixedDBkey();
673 $dir = $this->getHashedDirectory();
674 $friendlyName = strtr( $dbkey, '/\\:*?"<>|', '_________' );
675 return "$dir/$friendlyName.html";
679 * Get a URL with no fragment or server name
680 * @param string $query an optional query string; if not specified,
681 * $wgArticlePath will be used.
682 * @return string the URL
683 * @access public
685 function getLocalURL( $query = '' ) {
686 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks;
688 if ( $this->isExternal() ) {
689 return $this->getFullURL();
692 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
693 if ( $wgMakeDumpLinks ) {
694 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
695 } elseif ( $query == '' ) {
696 $url = str_replace( '$1', $dbkey, $wgArticlePath );
697 } else {
698 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
699 global $wgActionPaths;
700 $action = urldecode( $matches[2] );
701 if( isset( $wgActionPaths[$action] ) ) {
702 $query = $matches[1];
703 if( isset( $matches[4] ) ) $query .= $matches[4];
704 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
705 if( $query != '' ) $url .= '?' . $query;
706 return $url;
709 if ( $query == '-' ) {
710 $query = '';
712 $url = "{$wgScript}?title={$dbkey}&{$query}";
714 return $url;
718 * Get an HTML-escaped version of the URL form, suitable for
719 * using in a link, without a server name or fragment
720 * @param string $query an optional query string
721 * @return string the URL
722 * @access public
724 function escapeLocalURL( $query = '' ) {
725 return htmlspecialchars( $this->getLocalURL( $query ) );
729 * Get an HTML-escaped version of the URL form, suitable for
730 * using in a link, including the server name and fragment
732 * @return string the URL
733 * @param string $query an optional query string
734 * @access public
736 function escapeFullURL( $query = '' ) {
737 return htmlspecialchars( $this->getFullURL( $query ) );
740 /**
741 * Get the URL form for an internal link.
742 * - Used in various Squid-related code, in case we have a different
743 * internal hostname for the server from the exposed one.
745 * @param string $query an optional query string
746 * @return string the URL
747 * @access public
749 function getInternalURL( $query = '' ) {
750 global $wgInternalServer;
751 return $wgInternalServer . $this->getLocalURL( $query );
755 * Get the edit URL for this Title
756 * @return string the URL, or a null string if this is an
757 * interwiki link
758 * @access public
760 function getEditURL() {
761 global $wgServer, $wgScript;
763 if ( '' != $this->mInterwiki ) { return ''; }
764 $s = $this->getLocalURL( 'action=edit' );
766 return $s;
770 * Get the HTML-escaped displayable text form.
771 * Used for the title field in <a> tags.
772 * @return string the text, including any prefixes
773 * @access public
775 function getEscapedText() {
776 return htmlspecialchars( $this->getPrefixedText() );
780 * Is this Title interwiki?
781 * @return boolean
782 * @access public
784 function isExternal() { return ( '' != $this->mInterwiki ); }
787 * Does the title correspond to a protected article?
788 * @param string $what the action the page is protected from,
789 * by default checks move and edit
790 * @return boolean
791 * @access public
793 function isProtected($action = '') {
794 if ( -1 == $this->mNamespace ) { return true; }
795 if($action == 'edit' || $action == '') {
796 $a = $this->getRestrictions("edit");
797 if ( in_array( 'sysop', $a ) ) { return true; }
799 if($action == 'move' || $action == '') {
800 $a = $this->getRestrictions("move");
801 if ( in_array( 'sysop', $a ) ) { return true; }
803 return false;
807 * Is $wgUser is watching this page?
808 * @return boolean
809 * @access public
811 function userIsWatching() {
812 global $wgUser;
814 if ( -1 == $this->mNamespace ) { return false; }
815 if ( 0 == $wgUser->getID() ) { return false; }
817 return $wgUser->isWatched( $this );
821 * Is $wgUser perform $action this page?
822 * @param string $action action that permission needs to be checked for
823 * @return boolean
824 * @access private
826 function userCan($action) {
827 $fname = 'Title::userCanEdit';
828 wfProfileIn( $fname );
830 global $wgUser;
831 if( NS_SPECIAL == $this->mNamespace ) {
832 wfProfileOut( $fname );
833 return false;
835 if( NS_MEDIAWIKI == $this->mNamespace &&
836 !$wgUser->isAllowed('editinterface') ) {
837 wfProfileOut( $fname );
838 return false;
840 if( $this->mDbkeyform == '_' ) {
841 # FIXME: Is this necessary? Shouldn't be allowed anyway...
842 wfProfileOut( $fname );
843 return false;
846 # protect global styles and js
847 if ( NS_MEDIAWIKI == $this->mNamespace
848 && preg_match("/\\.(css|js)$/", $this->mTextform )
849 && !$wgUser->isAllowed('editinterface') ) {
850 wfProfileOut( $fname );
851 return false;
854 # protect css/js subpages of user pages
855 # XXX: this might be better using restrictions
856 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
857 if( NS_USER == $this->mNamespace
858 && preg_match("/\\.(css|js)$/", $this->mTextform )
859 && !$wgUser->isAllowed('editinterface')
860 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
861 wfProfileOut( $fname );
862 return false;
865 foreach( $this->getRestrictions($action) as $right ) {
866 // Backwards compatibility, rewrite sysop -> protect
867 if ( $right == 'sysop' ) {
868 $right = 'protect';
870 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
871 wfProfileOut( $fname );
872 return false;
876 if( $action == 'move' && !$this->isMovable() ) {
877 wfProfileOut( $fname );
878 return false;
881 wfProfileOut( $fname );
882 return true;
886 * Can $wgUser edit this page?
887 * @return boolean
888 * @access public
890 function userCanEdit() {
891 return $this->userCan('edit');
895 * Can $wgUser move this page?
896 * @return boolean
897 * @access public
899 function userCanMove() {
900 return $this->userCan('move');
904 * Would anybody with sufficient privileges be able to move this page?
905 * Some pages just aren't movable.
907 * @return boolean
908 * @access public
910 function isMovable() {
911 return Namespace::isMovable( $this->getNamespace() )
912 && $this->getInterwiki() == '';
916 * Can $wgUser read this page?
917 * @return boolean
918 * @access public
920 function userCanRead() {
921 global $wgUser;
923 if( $wgUser->isAllowed('read') ) {
924 return true;
925 } else {
926 global $wgWhitelistRead;
928 /** If anon users can create an account,
929 they need to reach the login page first! */
930 if( $wgUser->isAllowed( 'createaccount' )
931 && $this->mId == NS_SPECIAL
932 && $this->getText() == 'Userlogin' ) {
933 return true;
936 /** some pages are explicitly allowed */
937 $name = $this->getPrefixedText();
938 if( in_array( $name, $wgWhitelistRead ) ) {
939 return true;
942 # Compatibility with old settings
943 if( $this->getNamespace() == NS_MAIN ) {
944 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
945 return true;
949 return false;
953 * Is this a talk page of some sort?
954 * @return bool
955 * @access public
957 function isTalkPage() {
958 return Namespace::isTalk( $this->getNamespace() );
962 * Is this a .css or .js subpage of a user page?
963 * @return bool
964 * @access public
966 function isCssJsSubpage() {
967 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
970 * Is this a .css subpage of a user page?
971 * @return bool
972 * @access public
974 function isCssSubpage() {
975 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
978 * Is this a .js subpage of a user page?
979 * @return bool
980 * @access public
982 function isJsSubpage() {
983 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
986 * Protect css/js subpages of user pages: can $wgUser edit
987 * this page?
989 * @return boolean
990 * @todo XXX: this might be better using restrictions
991 * @access public
993 function userCanEditCssJsSubpage() {
994 global $wgUser;
995 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
999 * Loads a string into mRestrictions array
1000 * @param string $res restrictions in string format
1001 * @access public
1003 function loadRestrictions( $res ) {
1004 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1005 $temp = explode( '=', trim( $restrict ) );
1006 if(count($temp) == 1) {
1007 // old format should be treated as edit/move restriction
1008 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1009 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1010 } else {
1011 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1014 $this->mRestrictionsLoaded = true;
1018 * Accessor/initialisation for mRestrictions
1019 * @param string $action action that permission needs to be checked for
1020 * @return array the array of groups allowed to edit this article
1021 * @access public
1023 function getRestrictions($action) {
1024 $id = $this->getArticleID();
1025 if ( 0 == $id ) { return array(); }
1027 if ( ! $this->mRestrictionsLoaded ) {
1028 $dbr =& wfGetDB( DB_SLAVE );
1029 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1030 $this->loadRestrictions( $res );
1032 if( isset( $this->mRestrictions[$action] ) ) {
1033 return $this->mRestrictions[$action];
1035 return array();
1039 * Is there a version of this page in the deletion archive?
1040 * @return int the number of archived revisions
1041 * @access public
1043 function isDeleted() {
1044 $fname = 'Title::isDeleted';
1045 $dbr =& wfGetDB( DB_SLAVE );
1046 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1047 'ar_title' => $this->getDBkey() ), $fname );
1048 return (int)$n;
1052 * Get the article ID for this Title from the link cache,
1053 * adding it if necessary
1054 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1055 * for update
1056 * @return int the ID
1057 * @access public
1059 function getArticleID( $flags = 0 ) {
1060 global $wgLinkCache;
1062 if ( $flags & GAID_FOR_UPDATE ) {
1063 $oldUpdate = $wgLinkCache->forUpdate( true );
1064 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1065 $wgLinkCache->forUpdate( $oldUpdate );
1066 } else {
1067 if ( -1 == $this->mArticleID ) {
1068 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1071 return $this->mArticleID;
1075 * This clears some fields in this object, and clears any associated
1076 * keys in the "bad links" section of $wgLinkCache.
1078 * - This is called from Article::insertNewArticle() to allow
1079 * loading of the new page_id. It's also called from
1080 * Article::doDeleteArticle()
1082 * @param int $newid the new Article ID
1083 * @access public
1085 function resetArticleID( $newid ) {
1086 global $wgLinkCache;
1087 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1089 if ( 0 == $newid ) { $this->mArticleID = -1; }
1090 else { $this->mArticleID = $newid; }
1091 $this->mRestrictionsLoaded = false;
1092 $this->mRestrictions = array();
1096 * Updates page_touched for this page; called from LinksUpdate.php
1097 * @return bool true if the update succeded
1098 * @access public
1100 function invalidateCache() {
1101 if ( wfReadOnly() ) {
1102 return;
1105 $now = wfTimestampNow();
1106 $dbw =& wfGetDB( DB_MASTER );
1107 $success = $dbw->update( 'page',
1108 array( /* SET */
1109 'page_touched' => $dbw->timestamp()
1110 ), array( /* WHERE */
1111 'page_namespace' => $this->getNamespace() ,
1112 'page_title' => $this->getDBkey()
1113 ), 'Title::invalidateCache'
1115 return $success;
1119 * Prefix some arbitrary text with the namespace or interwiki prefix
1120 * of this object
1122 * @param string $name the text
1123 * @return string the prefixed text
1124 * @access private
1126 /* private */ function prefix( $name ) {
1127 global $wgContLang;
1129 $p = '';
1130 if ( '' != $this->mInterwiki ) {
1131 $p = $this->mInterwiki . ':';
1133 if ( 0 != $this->mNamespace ) {
1134 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1136 return $p . $name;
1140 * Secure and split - main initialisation function for this object
1142 * Assumes that mDbkeyform has been set, and is urldecoded
1143 * and uses underscores, but not otherwise munged. This function
1144 * removes illegal characters, splits off the interwiki and
1145 * namespace prefixes, sets the other forms, and canonicalizes
1146 * everything.
1147 * @return bool true on success
1148 * @access private
1150 /* private */ function secureAndSplit() {
1151 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1152 $fname = 'Title::secureAndSplit';
1153 wfProfileIn( $fname );
1155 # Initialisation
1156 static $rxTc = false;
1157 if( !$rxTc ) {
1158 # % is needed as well
1159 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1162 $this->mInterwiki = $this->mFragment = '';
1163 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1165 # Clean up whitespace
1167 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1168 $t = trim( $t, '_' );
1170 if ( '' == $t ) {
1171 wfProfileOut( $fname );
1172 return false;
1175 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1176 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1177 wfProfileOut( $fname );
1178 return false;
1181 $this->mDbkeyform = $t;
1183 # Initial colon indicating main namespace
1184 if ( ':' == $t{0} ) {
1185 $r = substr( $t, 1 );
1186 $this->mNamespace = NS_MAIN;
1187 } else {
1188 # Namespace or interwiki prefix
1189 $firstPass = true;
1190 do {
1191 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1192 $p = $m[1];
1193 $lowerNs = strtolower( $p );
1194 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1195 # Canonical namespace
1196 $t = $m[2];
1197 $this->mNamespace = $ns;
1198 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1199 # Ordinary namespace
1200 $t = $m[2];
1201 $this->mNamespace = $ns;
1202 } elseif( $this->getInterwikiLink( $p ) ) {
1203 if( !$firstPass ) {
1204 # Can't make a local interwiki link to an interwiki link.
1205 # That's just crazy!
1206 wfProfileOut( $fname );
1207 return false;
1210 # Interwiki link
1211 $t = $m[2];
1212 $this->mInterwiki = $p;
1214 # Redundant interwiki prefix to the local wiki
1215 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1216 if( $t == '' ) {
1217 # Can't have an empty self-link
1218 wfProfileOut( $fname );
1219 return false;
1221 $this->mInterwiki = '';
1222 $firstPass = false;
1223 # Do another namespace split...
1224 continue;
1227 # If there's no recognized interwiki or namespace,
1228 # then let the colon expression be part of the title.
1230 break;
1231 } while( true );
1232 $r = $t;
1235 # We already know that some pages won't be in the database!
1237 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1238 $this->mArticleID = 0;
1240 $f = strstr( $r, '#' );
1241 if ( false !== $f ) {
1242 $this->mFragment = substr( $f, 1 );
1243 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1244 # remove whitespace again: prevents "Foo_bar_#"
1245 # becoming "Foo_bar_"
1246 $r = preg_replace( '/_*$/', '', $r );
1249 # Reject illegal characters.
1251 if( preg_match( $rxTc, $r ) ) {
1252 wfProfileOut( $fname );
1253 return false;
1257 * Pages with "/./" or "/../" appearing in the URLs will
1258 * often be unreachable due to the way web browsers deal
1259 * with 'relative' URLs. Forbid them explicitly.
1261 if ( strpos( $r, '.' ) !== false &&
1262 ( $r === '.' || $r === '..' ||
1263 strpos( $r, './' ) === 0 ||
1264 strpos( $r, '../' ) === 0 ||
1265 strpos( $r, '/./' ) !== false ||
1266 strpos( $r, '/../' ) !== false ) )
1268 wfProfileOut( $fname );
1269 return false;
1272 # We shouldn't need to query the DB for the size.
1273 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1274 if ( strlen( $r ) > 255 ) {
1275 wfProfileOut( $fname );
1276 return false;
1280 * Normally, all wiki links are forced to have
1281 * an initial capital letter so [[foo]] and [[Foo]]
1282 * point to the same place.
1284 * Don't force it for interwikis, since the other
1285 * site might be case-sensitive.
1287 if( $wgCapitalLinks && $this->mInterwiki == '') {
1288 $t = $wgContLang->ucfirst( $r );
1289 } else {
1290 $t = $r;
1294 * Can't make a link to a namespace alone...
1295 * "empty" local links can only be self-links
1296 * with a fragment identifier.
1298 if( $t == '' &&
1299 $this->mInterwiki == '' &&
1300 $this->mNamespace != NS_MAIN ) {
1301 wfProfileOut( $fname );
1302 return false;
1305 # Fill fields
1306 $this->mDbkeyform = $t;
1307 $this->mUrlform = wfUrlencode( $t );
1309 $this->mTextform = str_replace( '_', ' ', $t );
1311 wfProfileOut( $fname );
1312 return true;
1316 * Get a Title object associated with the talk page of this article
1317 * @return Title the object for the talk page
1318 * @access public
1320 function getTalkPage() {
1321 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1325 * Get a title object associated with the subject page of this
1326 * talk page
1328 * @return Title the object for the subject page
1329 * @access public
1331 function getSubjectPage() {
1332 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1336 * Get an array of Title objects linking to this Title
1337 * Also stores the IDs in the link cache.
1339 * @param string $options may be FOR UPDATE
1340 * @return array the Title objects linking here
1341 * @access public
1343 function getLinksTo( $options = '' ) {
1344 global $wgLinkCache;
1345 $id = $this->getArticleID();
1347 if ( $options ) {
1348 $db =& wfGetDB( DB_MASTER );
1349 } else {
1350 $db =& wfGetDB( DB_SLAVE );
1352 $page = $db->tableName( 'page' );
1353 $links = $db->tableName( 'links' );
1355 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$links WHERE l_from=page_id AND l_to={$id} $options";
1356 $res = $db->query( $sql, 'Title::getLinksTo' );
1357 $retVal = array();
1358 if ( $db->numRows( $res ) ) {
1359 while ( $row = $db->fetchObject( $res ) ) {
1360 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1361 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1362 $retVal[] = $titleObj;
1366 $db->freeResult( $res );
1367 return $retVal;
1371 * Get an array of Title objects linking to this non-existent title.
1372 * - Also stores the IDs in the link cache.
1374 * @param string $options may be FOR UPDATE
1375 * @return array the Title objects linking here
1376 * @access public
1378 function getBrokenLinksTo( $options = '' ) {
1379 global $wgLinkCache;
1381 if ( $options ) {
1382 $db =& wfGetDB( DB_MASTER );
1383 } else {
1384 $db =& wfGetDB( DB_SLAVE );
1386 $page = $db->tableName( 'page' );
1387 $brokenlinks = $db->tableName( 'brokenlinks' );
1388 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1390 $sql = "SELECT page_namespace,page_title,page_id FROM $brokenlinks,$page " .
1391 "WHERE bl_from=page_id AND bl_to='$encTitle' $options";
1392 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1393 $retVal = array();
1394 if ( $db->numRows( $res ) ) {
1395 while ( $row = $db->fetchObject( $res ) ) {
1396 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
1397 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1398 $retVal[] = $titleObj;
1401 $db->freeResult( $res );
1402 return $retVal;
1407 * Get an array of Title objects referring to non-existent articles linked from this page
1409 * @param string $options may be FOR UPDATE
1410 * @return array the Title objects
1411 * @access public
1413 function getBrokenLinksFrom( $options = '' ) {
1414 global $wgLinkCache;
1416 if ( $options ) {
1417 $db =& wfGetDB( DB_MASTER );
1418 } else {
1419 $db =& wfGetDB( DB_SLAVE );
1421 $page = $db->tableName( 'page' );
1422 $brokenlinks = $db->tableName( 'brokenlinks' );
1423 $id = $this->getArticleID();
1425 $sql = "SELECT bl_to FROM $brokenlinks WHERE bl_from=$id $options";
1426 $res = $db->query( $sql, "Title::getBrokenLinksFrom" );
1427 $retVal = array();
1428 if ( $db->numRows( $res ) ) {
1429 while ( $row = $db->fetchObject( $res ) ) {
1430 $retVal[] = Title::newFromText( $row->bl_to );
1433 $db->freeResult( $res );
1434 return $retVal;
1439 * Get a list of URLs to purge from the Squid cache when this
1440 * page changes
1442 * @return array the URLs
1443 * @access public
1445 function getSquidURLs() {
1446 return array(
1447 $this->getInternalURL(),
1448 $this->getInternalURL( 'action=history' )
1453 * Move this page without authentication
1454 * @param Title &$nt the new page Title
1455 * @access public
1457 function moveNoAuth( &$nt ) {
1458 return $this->moveTo( $nt, false );
1462 * Check whether a given move operation would be valid.
1463 * Returns true if ok, or a message key string for an error message
1464 * if invalid. (Scarrrrry ugly interface this.)
1465 * @param Title &$nt the new title
1466 * @param bool $auth indicates whether $wgUser's permissions
1467 * should be checked
1468 * @return mixed true on success, message name on failure
1469 * @access public
1471 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1472 global $wgUser;
1473 if( !$this or !$nt ) {
1474 return 'badtitletext';
1476 if( $this->equals( $nt ) ) {
1477 return 'selfmove';
1479 if( !$this->isMovable() || !$nt->isMovable() ) {
1480 return 'immobile_namespace';
1483 $fname = 'Title::move';
1484 $oldid = $this->getArticleID();
1485 $newid = $nt->getArticleID();
1487 if ( strlen( $nt->getDBkey() ) < 1 ) {
1488 return 'articleexists';
1490 if ( ( '' == $this->getDBkey() ) ||
1491 ( !$oldid ) ||
1492 ( '' == $nt->getDBkey() ) ) {
1493 return 'badarticleerror';
1496 if ( $auth && (
1497 !$this->userCanEdit() || !$nt->userCanEdit() ||
1498 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1499 return 'protectedpage';
1502 # The move is allowed only if (1) the target doesn't exist, or
1503 # (2) the target is a redirect to the source, and has no history
1504 # (so we can undo bad moves right after they're done).
1506 if ( 0 != $newid ) { # Target exists; check for validity
1507 if ( ! $this->isValidMoveTarget( $nt ) ) {
1508 return 'articleexists';
1511 return true;
1515 * Move a title to a new location
1516 * @param Title &$nt the new title
1517 * @param bool $auth indicates whether $wgUser's permissions
1518 * should be checked
1519 * @return mixed true on success, message name on failure
1520 * @access public
1522 function moveTo( &$nt, $auth = true, $reason = '' ) {
1523 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1524 if( is_string( $err ) ) {
1525 return $err;
1527 if( $nt->exists() ) {
1528 $this->moveOverExistingRedirect( $nt, $reason );
1529 } else { # Target didn't exist, do normal move.
1530 $this->moveToNewTitle( $nt, $newid, $reason );
1533 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1535 $dbw =& wfGetDB( DB_MASTER );
1536 $categorylinks = $dbw->tableName( 'categorylinks' );
1537 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1538 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1539 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1540 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1542 # Update watchlists
1544 $oldnamespace = $this->getNamespace() & ~1;
1545 $newnamespace = $nt->getNamespace() & ~1;
1546 $oldtitle = $this->getDBkey();
1547 $newtitle = $nt->getDBkey();
1549 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1550 WatchedItem::duplicateEntries( $this, $nt );
1553 # Update search engine
1554 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1555 $u->doUpdate();
1556 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1557 $u->doUpdate();
1559 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1560 return true;
1564 * Move page to a title which is at present a redirect to the
1565 * source page
1567 * @param Title &$nt the page to move to, which should currently
1568 * be a redirect
1569 * @access private
1571 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1572 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1573 $fname = 'Title::moveOverExistingRedirect';
1574 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1576 if ( $reason ) {
1577 $comment .= ": $reason";
1580 $now = wfTimestampNow();
1581 $rand = wfRandom();
1582 $newid = $nt->getArticleID();
1583 $oldid = $this->getArticleID();
1584 $dbw =& wfGetDB( DB_MASTER );
1585 $links = $dbw->tableName( 'links' );
1587 # Delete the old redirect. We don't save it to history since
1588 # by definition if we've got here it's rather uninteresting.
1589 # We have to remove it so that the next step doesn't trigger
1590 # a conflict on the unique namespace+title index...
1591 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1593 # Save a null revision in the page's history notifying of the move
1594 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1595 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1596 true );
1597 $nullRevId = $nullRevision->insertOn( $dbw );
1599 # Change the name of the target page:
1600 $dbw->update( 'page',
1601 /* SET */ array(
1602 'page_touched' => $dbw->timestamp($now),
1603 'page_namespace' => $nt->getNamespace(),
1604 'page_title' => $nt->getDBkey(),
1605 'page_latest' => $nullRevId,
1607 /* WHERE */ array( 'page_id' => $oldid ),
1608 $fname
1610 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1612 # Recreate the redirect, this time in the other direction.
1613 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1614 $redirectArticle = new Article( $this );
1615 $newid = $redirectArticle->insertOn( $dbw );
1616 $redirectRevision = new Revision( array(
1617 'page' => $newid,
1618 'comment' => $comment,
1619 'text' => $redirectText ) );
1620 $revid = $redirectRevision->insertOn( $dbw );
1621 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1622 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1624 # Log the move
1625 $log = new LogPage( 'move' );
1626 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1628 # Swap links
1630 # Load titles and IDs
1631 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1632 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1634 # Delete them all
1635 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1636 $dbw->query( $sql, $fname );
1638 # Reinsert
1639 if ( count( $linksToOld ) || count( $linksToNew )) {
1640 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1641 $first = true;
1643 # Insert links to old title
1644 foreach ( $linksToOld as $linkTitle ) {
1645 if ( $first ) {
1646 $first = false;
1647 } else {
1648 $sql .= ',';
1650 $id = $linkTitle->getArticleID();
1651 $sql .= "($id,$newid)";
1654 # Insert links to new title
1655 foreach ( $linksToNew as $linkTitle ) {
1656 if ( $first ) {
1657 $first = false;
1658 } else {
1659 $sql .= ',';
1661 $id = $linkTitle->getArticleID();
1662 $sql .= "($id, $oldid)";
1665 $dbw->query( $sql, $fname );
1668 # Now, we record the link from the redirect to the new title.
1669 # It should have no other outgoing links...
1670 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1671 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1673 # Clear linkscc
1674 LinkCache::linksccClearLinksTo( $oldid );
1675 LinkCache::linksccClearLinksTo( $newid );
1677 # Purge squid
1678 if ( $wgUseSquid ) {
1679 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1680 $u = new SquidUpdate( $urls );
1681 $u->doUpdate();
1686 * Move page to non-existing title.
1687 * @param Title &$nt the new Title
1688 * @param int &$newid set to be the new article ID
1689 * @access private
1691 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1692 global $wgUser, $wgLinkCache, $wgUseSquid;
1693 global $wgMwRedir;
1694 $fname = 'MovePageForm::moveToNewTitle';
1695 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1696 if ( $reason ) {
1697 $comment .= ": $reason";
1700 $newid = $nt->getArticleID();
1701 $oldid = $this->getArticleID();
1702 $dbw =& wfGetDB( DB_MASTER );
1703 $now = $dbw->timestamp();
1704 wfSeedRandom();
1705 $rand = wfRandom();
1707 # Save a null revision in the page's history notifying of the move
1708 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1709 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1710 true );
1711 $nullRevId = $nullRevision->insertOn( $dbw );
1713 # Rename cur entry
1714 $dbw->update( 'page',
1715 /* SET */ array(
1716 'page_touched' => $now,
1717 'page_namespace' => $nt->getNamespace(),
1718 'page_title' => $nt->getDBkey(),
1719 'page_latest' => $nullRevId,
1721 /* WHERE */ array( 'page_id' => $oldid ),
1722 $fname
1725 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1727 # Insert redirect
1728 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1729 $redirectArticle = new Article( $this );
1730 $newid = $redirectArticle->insertOn( $dbw );
1731 $redirectRevision = new Revision( array(
1732 'page' => $newid,
1733 'comment' => $comment,
1734 'text' => $redirectText ) );
1735 $revid = $redirectRevision->insertOn( $dbw );
1736 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1737 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1739 # Log the move
1740 $log = new LogPage( 'move' );
1741 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1743 # Purge squid and linkscc as per article creation
1744 Article::onArticleCreate( $nt );
1746 # Any text links to the old title must be reassigned to the redirect
1747 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1748 LinkCache::linksccClearLinksTo( $oldid );
1750 # Record the just-created redirect's linking to the page
1751 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1753 # Non-existent target may have had broken links to it; these must
1754 # now be removed and made into good links.
1755 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1756 $update->fixBrokenLinks();
1758 # Purge old title from squid
1759 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1760 $titles = $nt->getLinksTo();
1761 if ( $wgUseSquid ) {
1762 $urls = $this->getSquidURLs();
1763 foreach ( $titles as $linkTitle ) {
1764 $urls[] = $linkTitle->getInternalURL();
1766 $u = new SquidUpdate( $urls );
1767 $u->doUpdate();
1772 * Checks if $this can be moved to a given Title
1773 * - Selects for update, so don't call it unless you mean business
1775 * @param Title &$nt the new title to check
1776 * @access public
1778 function isValidMoveTarget( $nt ) {
1780 $fname = 'Title::isValidMoveTarget';
1781 $dbw =& wfGetDB( DB_MASTER );
1783 # Is it a redirect?
1784 $id = $nt->getArticleID();
1785 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1786 array( 'page_is_redirect','old_text' ),
1787 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1788 $fname, 'FOR UPDATE' );
1790 if ( !$obj || 0 == $obj->page_is_redirect ) {
1791 # Not a redirect
1792 return false;
1795 # Does the redirect point to the source?
1796 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1797 $redirTitle = Title::newFromText( $m[1] );
1798 if( !is_object( $redirTitle ) ||
1799 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1800 return false;
1804 # Does the article have a history?
1805 $row = $dbw->selectRow( array( 'page', 'revision'),
1806 array( 'rev_id' ),
1807 array( 'page_namespace' => $nt->getNamespace(),
1808 'page_title' => $nt->getDBkey(),
1809 'page_id=rev_page AND page_latest != rev_id'
1810 ), $fname, 'FOR UPDATE'
1813 # Return true if there was no history
1814 return $row === false;
1818 * Create a redirect; fails if the title already exists; does
1819 * not notify RC
1821 * @param Title $dest the destination of the redirect
1822 * @param string $comment the comment string describing the move
1823 * @return bool true on success
1824 * @access public
1826 function createRedirect( $dest, $comment ) {
1827 global $wgUser;
1828 if ( $this->getArticleID() ) {
1829 return false;
1832 $fname = 'Title::createRedirect';
1833 $dbw =& wfGetDB( DB_MASTER );
1835 $article = new Article( $this );
1836 $newid = $article->insertOn( $dbw );
1837 $revision = new Revision( array(
1838 'page' => $newid,
1839 'comment' => $comment,
1840 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1841 ) );
1842 $revisionId = $revision->insertOn( $dbw );
1843 $article->updateRevisionOn( $dbw, $revision, 0 );
1845 # Link table
1846 if ( $dest->getArticleID() ) {
1847 $dbw->insert( 'links',
1848 array(
1849 'l_to' => $dest->getArticleID(),
1850 'l_from' => $newid
1851 ), $fname
1853 } else {
1854 $dbw->insert( 'brokenlinks',
1855 array(
1856 'bl_to' => $dest->getPrefixedDBkey(),
1857 'bl_from' => $newid
1858 ), $fname
1862 Article::onArticleCreate( $this );
1863 return true;
1867 * Get categories to which this Title belongs and return an array of
1868 * categories' names.
1870 * @return array an array of parents in the form:
1871 * $parent => $currentarticle
1872 * @access public
1874 function getParentCategories() {
1875 global $wgContLang,$wgUser;
1877 $titlekey = $this->getArticleId();
1878 $sk =& $wgUser->getSkin();
1879 $parents = array();
1880 $dbr =& wfGetDB( DB_SLAVE );
1881 $categorylinks = $dbr->tableName( 'categorylinks' );
1883 # NEW SQL
1884 $sql = "SELECT * FROM $categorylinks"
1885 ." WHERE cl_from='$titlekey'"
1886 ." AND cl_from <> '0'"
1887 ." ORDER BY cl_sortkey";
1889 $res = $dbr->query ( $sql ) ;
1891 if($dbr->numRows($res) > 0) {
1892 while ( $x = $dbr->fetchObject ( $res ) )
1893 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1894 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1895 $dbr->freeResult ( $res ) ;
1896 } else {
1897 $data = '';
1899 return $data;
1903 * Get a tree of parent categories
1904 * @param array $children an array with the children in the keys, to check for circular refs
1905 * @return array
1906 * @access public
1908 function getParentCategoryTree( $children = array() ) {
1909 $parents = $this->getParentCategories();
1911 if($parents != '') {
1912 foreach($parents as $parent => $current)
1914 if ( array_key_exists( $parent, $children ) ) {
1915 # Circular reference
1916 $stack[$parent] = array();
1917 } else {
1918 $nt = Title::newFromText($parent);
1919 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1922 return $stack;
1923 } else {
1924 return array();
1930 * Get an associative array for selecting this title from
1931 * the "cur" table
1933 * @return array
1934 * @access public
1936 function curCond() {
1937 wfDebugDieBacktrace( 'curCond called' );
1938 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1942 * Get an associative array for selecting this title from the
1943 * "old" table
1945 * @return array
1946 * @access public
1948 function oldCond() {
1949 wfDebugDieBacktrace( 'oldCond called' );
1950 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1954 * Get the revision ID of the previous revision
1956 * @param integer $revision Revision ID. Get the revision that was before this one.
1957 * @return interger $oldrevision|false
1959 function getPreviousRevisionID( $revision ) {
1960 $dbr =& wfGetDB( DB_SLAVE );
1961 return $dbr->selectField( 'revision', 'rev_id',
1962 'rev_page=' . IntVal( $this->getArticleId() ) .
1963 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1967 * Get the revision ID of the next revision
1969 * @param integer $revision Revision ID. Get the revision that was after this one.
1970 * @return interger $oldrevision|false
1972 function getNextRevisionID( $revision ) {
1973 $dbr =& wfGetDB( DB_SLAVE );
1974 return $dbr->selectField( 'revision', 'rev_id',
1975 'rev_page=' . IntVal( $this->getArticleId() ) .
1976 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1980 * Compare with another title.
1982 * @param Title $title
1983 * @return bool
1985 function equals( &$title ) {
1986 return $this->getInterwiki() == $title->getInterwiki()
1987 && $this->getNamespace() == $title->getNamespace()
1988 && $this->getDbkey() == $title->getDbkey();
1992 * Check if page exists
1993 * @return bool
1995 function exists() {
1996 return $this->getArticleId() != 0;
2000 * Should a link should be displayed as a known link, just based on its title?
2002 * Currently, a self-link with a fragment, special pages and image pages are in
2003 * this category. Special pages never exist in the database. Some images do not
2004 * have description pages in the database, but the description page contains
2005 * useful history information that the user may want to link to.
2008 function isAlwaysKnown() {
2009 return ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2010 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;