Fixed quoting in contributors query.
[mediawiki.git] / includes / Title.php
blobcd55e7420ea81ca01803b06e114b1e901a9483b1
1 <?php
2 # See title.doc
4 /* private static */ $title_interwiki_cache = array();
6 # Title class
7 #
8 # * Represents a title, which may contain an interwiki designation or namespace
9 # * Can fetch various kinds of data from the database, albeit inefficiently.
11 class Title {
12 # All member variables should be considered private
13 # Please use the accessor functions
15 var $mTextform; # Text form (spaces not underscores) of the main part
16 var $mUrlform; # URL-encoded form of the main part
17 var $mDbkeyform; # Main part with underscores
18 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
19 var $mInterwiki; # Interwiki prefix (or null string)
20 var $mFragment; # Title fragment (i.e. the bit after the #)
21 var $mArticleID; # Article ID, fetched from the link cache on demand
22 var $mRestrictions; # Array of groups allowed to edit this article
23 # Only null or "sysop" are supported
24 var $mRestrictionsLoaded; # Boolean for initialisation on demand
25 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
26 var $mDefaultNamespace; # Namespace index when there is no namespace
27 # Zero except in {{transclusion}} tags
29 #----------------------------------------------------------------------------
30 # Construction
31 #----------------------------------------------------------------------------
33 /* private */ function Title()
35 $this->mInterwiki = $this->mUrlform =
36 $this->mTextform = $this->mDbkeyform = "";
37 $this->mArticleID = -1;
38 $this->mNamespace = 0;
39 $this->mRestrictionsLoaded = false;
40 $this->mRestrictions = array();
41 $this->mDefaultNamespace = 0;
44 # From a prefixed DB key
45 /* static */ function newFromDBkey( $key )
47 $t = new Title();
48 $t->mDbkeyform = $key;
49 if( $t->secureAndSplit() )
50 return $t;
51 else
52 return NULL;
55 # From text, such as what you would find in a link
56 /* static */ function newFromText( $text, $defaultNamespace = 0 )
58 static $trans;
59 $fname = "Title::newFromText";
60 wfProfileIn( $fname );
62 # Note - mixing latin1 named entities and unicode numbered
63 # ones will result in a bad link.
64 if( !isset( $trans ) ) {
65 global $wgInputEncoding;
66 $trans = array_flip( get_html_translation_table( HTML_ENTITIES ) );
67 if( strcasecmp( "utf-8", $wgInputEncoding ) == 0 ) {
68 $trans = array_map( "utf8_encode", $trans );
72 if( is_object( $text ) ) {
73 wfDebugDieBacktrace( "Called with object instead of string." );
75 $text = strtr( $text, $trans );
77 $text = wfMungeToUtf8( $text );
80 # What was this for? TS 2004-03-03
81 # $text = urldecode( $text );
83 $t = new Title();
84 $t->mDbkeyform = str_replace( " ", "_", $text );
85 $t->mDefaultNamespace = $defaultNamespace;
87 wfProfileOut( $fname );
88 if ( !is_object( $t ) ) {
89 var_dump( debug_backtrace() );
91 if( $t->secureAndSplit() ) {
92 return $t;
93 } else {
94 return NULL;
98 # From a URL-encoded title
99 /* static */ function newFromURL( $url )
101 global $wgLang, $wgServer;
102 $t = new Title();
103 $s = urldecode( $url ); # This is technically wrong, as anything
104 # we've gotten is already decoded by PHP.
105 # Kept for backwards compatibility with
106 # buggy URLs we had for a while...
107 $s = $url;
109 # For links that came from outside, check for alternate/legacy
110 # character encoding.
111 wfDebug( "Servr: $wgServer\n" );
112 if( empty( $_SERVER["HTTP_REFERER"] ) ||
113 strncmp($wgServer, $_SERVER["HTTP_REFERER"], strlen( $wgServer ) ) )
115 $s = $wgLang->checkTitleEncoding( $s );
116 } else {
117 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
120 $t->mDbkeyform = str_replace( " ", "_", $s );
121 if( $t->secureAndSplit() ) {
123 # check that lenght of title is < cur_title size
124 $sql = "SHOW COLUMNS FROM cur LIKE \"cur_title\";";
125 $cur_title_object = wfFetchObject(wfQuery( $sql, DB_READ ));
127 preg_match( "/\((.*)\)/", $cur_title_object->Type, $cur_title_size);
129 if (strlen($t->mDbkeyform) > $cur_title_size[1] ) {
130 return NULL;
133 return $t;
134 } else {
135 return NULL;
139 # From a cur_id
140 # This is inefficiently implemented, the cur row is requested but not
141 # used for anything else
142 /* static */ function newFromID( $id )
144 $fname = "Title::newFromID";
145 $row = wfGetArray( "cur", array( "cur_namespace", "cur_title" ),
146 array( "cur_id" => $id ), $fname );
147 if ( $row !== false ) {
148 $title = Title::makeTitle( $row->cur_namespace, $row->cur_title );
149 } else {
150 $title = NULL;
152 return $title;
155 # From a namespace index and a DB key
156 /* static */ function makeTitle( $ns, $title )
158 $t = new Title();
159 $t->mDbkeyform = Title::makeName( $ns, $title );
160 if( $t->secureAndSplit() ) {
161 return $t;
162 } else {
163 return NULL;
167 function newMainPage()
169 return Title::newFromText( wfMsg( "mainpage" ) );
172 #----------------------------------------------------------------------------
173 # Static functions
174 #----------------------------------------------------------------------------
176 # Get the prefixed DB key associated with an ID
177 /* static */ function nameOf( $id )
179 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
180 "cur_id={$id}";
181 $res = wfQuery( $sql, DB_READ, "Article::nameOf" );
182 if ( 0 == wfNumRows( $res ) ) { return NULL; }
184 $s = wfFetchObject( $res );
185 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
186 return $n;
189 # Get a regex character class describing the legal characters in a link
190 /* static */ function legalChars()
192 # Missing characters:
193 # * []|# Needed for link syntax
194 # * % and + are corrupted by Apache when they appear in the path
196 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
197 # this breaks interlanguage links
199 $set = " !\"$&'()*,\\-.\\/0-9:;<=>?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
200 return $set;
203 # Returns a stripped-down a title string ready for the search index
204 # Takes a namespace index and a text-form main part
205 /* static */ function indexTitle( $ns, $title )
207 global $wgDBminWordLen, $wgLang;
209 $lc = SearchEngine::legalSearchChars() . "&#;";
210 $t = $wgLang->stripForSearch( $title );
211 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
212 $t = strtolower( $t );
214 # Handle 's, s'
215 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
216 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
218 $t = preg_replace( "/\\s+/", " ", $t );
220 if ( $ns == Namespace::getImage() ) {
221 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
223 return trim( $t );
226 # Make a prefixed DB key from a DB key and a namespace index
227 /* static */ function makeName( $ns, $title )
229 global $wgLang;
231 $n = $wgLang->getNsText( $ns );
232 if ( "" == $n ) { return $title; }
233 else { return "{$n}:{$title}"; }
236 # Arguably static
237 # Returns the URL associated with an interwiki prefix
238 # The URL contains $1, which is replaced by the title
239 function getInterwikiLink( $key )
241 global $wgMemc, $wgDBname;
242 static $title_interwiki_cache = array();
244 $k = "$wgDBname:interwiki:$key";
246 if( array_key_exists( $k, $title_interwiki_cache ) )
247 return $title_interwiki_cache[$k]->iw_url;
249 $s = $wgMemc->get( $k );
250 if( $s ) {
251 $title_interwiki_cache[$k] = $s;
252 return $s->iw_url;
254 $dkey = wfStrencode( $key );
255 $query = "SELECT iw_url FROM interwiki WHERE iw_prefix='$dkey'";
256 $res = wfQuery( $query, DB_READ, "Title::getInterwikiLink" );
257 if(!$res) return "";
259 $s = wfFetchObject( $res );
260 if(!$s) {
261 $s = (object)false;
262 $s->iw_url = "";
264 $wgMemc->set( $k, $s );
265 $title_interwiki_cache[$k] = $s;
266 return $s->iw_url;
269 # Update the cur_touched field for an array of title objects
270 # Inefficient unless the IDs are already loaded into the link cache
271 /* static */ function touchArray( $titles, $timestamp = "" ) {
272 if ( count( $titles ) == 0 ) {
273 return;
275 if ( $timestamp == "" ) {
276 $timestamp = wfTimestampNow();
278 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
279 $first = true;
281 foreach ( $titles as $title ) {
282 if ( ! $first ) {
283 $sql .= ",";
286 $first = false;
287 $sql .= $title->getArticleID();
289 $sql .= ")";
290 if ( ! $first ) {
291 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
295 #----------------------------------------------------------------------------
296 # Other stuff
297 #----------------------------------------------------------------------------
299 # Simple accessors
300 # See the definitions at the top of this file
302 function getText() { return $this->mTextform; }
303 function getPartialURL() { return $this->mUrlform; }
304 function getDBkey() { return $this->mDbkeyform; }
305 function getNamespace() { return $this->mNamespace; }
306 function setNamespace( $n ) { $this->mNamespace = $n; }
307 function getInterwiki() { return $this->mInterwiki; }
308 function getFragment() { return $this->mFragment; }
309 function getDefaultNamespace() { return $this->mDefaultNamespace; }
311 # Get title for search index
312 function getIndexTitle()
314 return Title::indexTitle( $this->mNamespace, $this->mTextform );
317 # Get prefixed title with underscores
318 function getPrefixedDBkey()
320 $s = $this->prefix( $this->mDbkeyform );
321 $s = str_replace( " ", "_", $s );
322 return $s;
325 # Get prefixed title with spaces
326 # This is the form usually used for display
327 function getPrefixedText()
329 if ( empty( $this->mPrefixedText ) ) {
330 $s = $this->prefix( $this->mTextform );
331 $s = str_replace( "_", " ", $s );
332 $this->mPrefixedText = $s;
334 return $this->mPrefixedText;
337 # Get a URL-encoded title (not an actual URL) including interwiki
338 function getPrefixedURL()
340 $s = $this->prefix( $this->mDbkeyform );
341 $s = str_replace( " ", "_", $s );
343 $s = wfUrlencode ( $s ) ;
345 # Cleaning up URL to make it look nice -- is this safe?
346 $s = preg_replace( "/%3[Aa]/", ":", $s );
347 $s = preg_replace( "/%2[Ff]/", "/", $s );
348 $s = str_replace( "%28", "(", $s );
349 $s = str_replace( "%29", ")", $s );
351 return $s;
354 # Get a real URL referring to this title, with interwiki link and fragment
355 function getFullURL( $query = "" )
357 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
359 if ( "" == $this->mInterwiki ) {
360 $p = $wgArticlePath;
361 return $wgServer . $this->getLocalUrl( $query );
364 $p = $this->getInterwikiLink( $this->mInterwiki );
365 $n = $wgLang->getNsText( $this->mNamespace );
366 if ( "" != $n ) { $n .= ":"; }
367 $u = str_replace( "$1", $n . $this->mUrlform, $p );
368 if ( "" != $this->mFragment ) {
369 $u .= "#" . wfUrlencode( $this->mFragment );
371 return $u;
374 # Get a URL with an optional query string, no fragment
375 # * If $query=="", it will use $wgArticlePath
376 # * Returns a full for an interwiki link, loses any query string
377 # * Optionally adds the server and escapes for HTML
378 # * Setting $query to "-" makes an old-style URL with nothing in the
379 # query except a title
381 function getURL() {
382 die( "Call to obsolete obsolete function Title::getURL()" );
385 function getLocalURL( $query = "" )
387 global $wgLang, $wgArticlePath, $wgScript;
389 if ( $this->isExternal() ) {
390 return $this->getFullURL();
393 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
394 if ( $query == "" ) {
395 $url = str_replace( "$1", $dbkey, $wgArticlePath );
396 } else {
397 if ( $query == "-" ) {
398 $query = "";
400 if ( $wgScript != "" ) {
401 $url = "{$wgScript}?title={$dbkey}&{$query}";
402 } else {
403 # Top level wiki
404 $url = "/{$dbkey}?{$query}";
407 return $url;
410 function escapeLocalURL( $query = "" ) {
411 return wfEscapeHTML( $this->getLocalURL( $query ) );
414 function escapeFullURL( $query = "" ) {
415 return wfEscapeHTML( $this->getFullURL( $query ) );
418 function getInternalURL( $query = "" ) {
419 # Used in various Squid-related code, in case we have a different
420 # internal hostname for the server than the exposed one.
421 global $wgInternalServer;
422 return $wgInternalServer . $this->getLocalURL( $query );
425 # Get the edit URL, or a null string if it is an interwiki link
426 function getEditURL()
428 global $wgServer, $wgScript;
430 if ( "" != $this->mInterwiki ) { return ""; }
431 $s = $this->getLocalURL( "action=edit" );
433 return $s;
436 # Get HTML-escaped displayable text
437 # For the title field in <a> tags
438 function getEscapedText()
440 return wfEscapeHTML( $this->getPrefixedText() );
443 # Is the title interwiki?
444 function isExternal() { return ( "" != $this->mInterwiki ); }
446 # Does the title correspond to a protected article?
447 function isProtected()
449 if ( -1 == $this->mNamespace ) { return true; }
450 $a = $this->getRestrictions();
451 if ( in_array( "sysop", $a ) ) { return true; }
452 return false;
455 # Is the page a log page, i.e. one where the history is messed up by
456 # LogPage.php? This used to be used for suppressing diff links in recent
457 # changes, but now that's done by setting a flag in the recentchanges
458 # table. Hence, this probably is no longer used.
459 function isLog()
461 if ( $this->mNamespace != Namespace::getWikipedia() ) {
462 return false;
464 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
465 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
466 return true;
468 return false;
471 # Is $wgUser is watching this page?
472 function userIsWatching()
474 global $wgUser;
476 if ( -1 == $this->mNamespace ) { return false; }
477 if ( 0 == $wgUser->getID() ) { return false; }
479 return $wgUser->isWatched( $this );
482 # Can $wgUser edit this page?
483 function userCanEdit()
485 global $wgUser;
487 if ( -1 == $this->mNamespace ) { return false; }
488 # if ( 0 == $this->getArticleID() ) { return false; }
489 if ( $this->mDbkeyform == "_" ) { return false; }
490 # protect css/js subpages of user pages
491 # XXX: this might be better using restrictions
492 if( Namespace::getUser() == $this->mNamespace
493 and preg_match("/\\.(css|js)$/", $this->mTextform )
494 and !$wgUser->isSysop()
495 and !preg_match("/^".$wgUser->getName()."/", $this->mTextform) )
496 { return false; }
498 $ur = $wgUser->getRights();
499 foreach ( $this->getRestrictions() as $r ) {
500 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
501 return false;
504 return true;
507 # Accessor/initialisation for mRestrictions
508 function getRestrictions()
510 $id = $this->getArticleID();
511 if ( 0 == $id ) { return array(); }
513 if ( ! $this->mRestrictionsLoaded ) {
514 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
515 $this->mRestrictions = explode( ",", trim( $res ) );
516 $this->mRestrictionsLoaded = true;
518 return $this->mRestrictions;
521 # Is there a version of this page in the deletion archive?
522 function isDeleted() {
523 $ns = $this->getNamespace();
524 $t = wfStrencode( $this->getDBkey() );
525 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
526 if( $res = wfQuery( $sql, DB_READ ) ) {
527 $s = wfFetchObject( $res );
528 return $s->n;
530 return 0;
533 # Get the article ID from the link cache
534 # Used very heavily, e.g. in Parser::replaceInternalLinks()
535 function getArticleID()
537 global $wgLinkCache;
539 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
540 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
541 return $this->mArticleID;
544 # This clears some fields in this object, and clears any associated keys in the
545 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
546 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
547 function resetArticleID( $newid )
549 global $wgLinkCache;
550 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
552 if ( 0 == $newid ) { $this->mArticleID = -1; }
553 else { $this->mArticleID = $newid; }
554 $this->mRestrictionsLoaded = false;
555 $this->mRestrictions = array();
558 # Updates cur_touched
559 # Called from LinksUpdate.php
560 function invalidateCache() {
561 $now = wfTimestampNow();
562 $ns = $this->getNamespace();
563 $ti = wfStrencode( $this->getDBkey() );
564 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
565 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
568 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
569 /* private */ function prefix( $name )
571 global $wgLang;
573 $p = "";
574 if ( "" != $this->mInterwiki ) {
575 $p = $this->mInterwiki . ":";
577 if ( 0 != $this->mNamespace ) {
578 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
580 return $p . $name;
583 # Secure and split - main initialisation function for this object
585 # Assumes that mDbkeyform has been set, and is urldecoded
586 # and uses undersocres, but not otherwise munged. This function
587 # removes illegal characters, splits off the winterwiki and
588 # namespace prefixes, sets the other forms, and canonicalizes
589 # everything.
591 /* private */ function secureAndSplit()
593 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
594 $fname = "Title::secureAndSplit";
595 wfProfileIn( $fname );
597 static $imgpre = false;
598 static $rxTc = false;
600 # Initialisation
601 if ( $imgpre === false ) {
602 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
603 $rxTc = "/[^" . Title::legalChars() . "]/";
606 $this->mInterwiki = $this->mFragment = "";
607 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
609 # Clean up whitespace
611 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
612 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
614 if ( "" == $t ) {
615 wfProfileOut( $fname );
616 return false;
619 $this->mDbkeyform = $t;
620 $done = false;
622 # :Image: namespace
623 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
624 $t = substr( $t, 1 );
627 # Initial colon indicating main namespace
628 if ( ":" == $t{0} ) {
629 $r = substr( $t, 1 );
630 $this->mNamespace = NS_MAIN;
631 } else {
632 # Namespace or interwiki prefix
633 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
634 #$p = strtolower( $m[1] );
635 $p = $m[1];
636 $lowerNs = strtolower( $p );
637 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
638 # Canonical namespace
639 $t = $m[2];
640 $this->mNamespace = $ns;
641 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
642 # Ordinary namespace
643 $t = $m[2];
644 $this->mNamespace = $ns;
645 } elseif ( $this->getInterwikiLink( $p ) ) {
646 # Interwiki link
647 $t = $m[2];
648 $this->mInterwiki = $p;
650 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
651 $done = true;
652 } elseif($this->mInterwiki != $wgLocalInterwiki) {
653 $done = true;
657 $r = $t;
660 # Redundant interwiki prefix to the local wiki
661 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
662 $this->mInterwiki = "";
664 # We already know that some pages won't be in the database!
666 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
667 $this->mArticleID = 0;
669 $f = strstr( $r, "#" );
670 if ( false !== $f ) {
671 $this->mFragment = substr( $f, 1 );
672 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
675 # Reject illegal characters.
677 if( preg_match( $rxTc, $r ) ) {
678 return false;
681 # "." and ".." conflict with the directories of those names
682 if ( $r === "." || $r === ".." ) {
683 return false;
686 # Initial capital letter
687 if( $wgCapitalLinks && $this->mInterwiki == "") {
688 $t = $wgLang->ucfirst( $r );
691 # Fill fields
692 $this->mDbkeyform = $t;
693 $this->mUrlform = wfUrlencode( $t );
695 $this->mTextform = str_replace( "_", " ", $t );
697 wfProfileOut( $fname );
698 return true;
701 # Get a title object associated with the talk page of this article
702 function getTalkPage() {
703 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
706 # Get a title object associated with the subject page of this talk page
707 function getSubjectPage() {
708 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
711 # Get an array of Title objects linking to this title
712 # Also stores the IDs in the link cache
713 function getLinksTo() {
714 global $wgLinkCache;
715 $id = $this->getArticleID();
716 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
717 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
718 $retVal = array();
719 if ( wfNumRows( $res ) ) {
720 while ( $row = wfFetchObject( $res ) ) {
721 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
722 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
723 $retVal[] = $titleObj;
726 wfFreeResult( $res );
727 return $retVal;
730 # Get an array of Title objects linking to this non-existent title
731 # Also stores the IDs in the link cache
732 function getBrokenLinksTo() {
733 global $wgLinkCache;
734 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
735 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
736 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
737 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
738 $retVal = array();
739 if ( wfNumRows( $res ) ) {
740 while ( $row = wfFetchObject( $res ) ) {
741 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
742 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
743 $retVal[] = $titleObj;
746 wfFreeResult( $res );
747 return $retVal;
750 function getSquidURLs() {
751 return array(
752 $this->getInternalURL(),
753 $this->getInternalURL( "action=history" )
757 function moveNoAuth( &$nt ) {
758 return $this->moveTo( $nt, false );
761 # Move a title to a new location
762 # Returns true on success, message name on failure
763 # auth indicates whether wgUser's permissions should be checked
764 function moveTo( &$nt, $auth = true ) {
765 if( !$this or !$nt ) {
766 return "badtitletext";
769 $fname = "Title::move";
770 $oldid = $this->getArticleID();
771 $newid = $nt->getArticleID();
773 if ( strlen( $nt->getDBkey() ) < 1 ) {
774 return "articleexists";
776 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
777 ( "" == $this->getDBkey() ) ||
778 ( "" != $this->getInterwiki() ) ||
779 ( !$oldid ) ||
780 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
781 ( "" == $nt->getDBkey() ) ||
782 ( "" != $nt->getInterwiki() ) ) {
783 return "badarticleerror";
786 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
787 return "protectedpage";
790 # The move is allowed only if (1) the target doesn't exist, or
791 # (2) the target is a redirect to the source, and has no history
792 # (so we can undo bad moves right after they're done).
794 if ( 0 != $newid ) { # Target exists; check for validity
795 if ( ! $this->isValidMoveTarget( $nt ) ) {
796 return "articleexists";
798 $this->moveOverExistingRedirect( $nt );
799 } else { # Target didn't exist, do normal move.
800 $this->moveToNewTitle( $nt, $newid );
803 # Update watchlists
805 $oldnamespace = $this->getNamespace() & ~1;
806 $newnamespace = $nt->getNamespace() & ~1;
807 $oldtitle = $this->getDBkey();
808 $newtitle = $nt->getDBkey();
810 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
811 WatchedItem::duplicateEntries( $this, $nt );
814 # Update search engine
815 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
816 $u->doUpdate();
817 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
818 $u->doUpdate();
820 return true;
823 # Move page to title which is presently a redirect to the source page
825 /* private */ function moveOverExistingRedirect( &$nt )
827 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
828 $fname = "Title::moveOverExistingRedirect";
829 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
831 $now = wfTimestampNow();
832 $won = wfInvertTimestamp( $now );
833 $newid = $nt->getArticleID();
834 $oldid = $this->getArticleID();
836 # Change the name of the target page:
837 wfUpdateArray(
838 /* table */ 'cur',
839 /* SET */ array(
840 'cur_touched' => $now,
841 'cur_namespace' => $nt->getNamespace(),
842 'cur_title' => $nt->getDBkey()
844 /* WHERE */ array( 'cur_id' => $oldid ),
845 $fname
847 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
849 # Repurpose the old redirect. We don't save it to history since
850 # by definition if we've got here it's rather uninteresting.
852 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
853 wfUpdateArray(
854 /* table */ 'cur',
855 /* SET */ array(
856 'cur_touched' => $now,
857 'cur_timestamp' => $now,
858 'inverse_timestamp' => $won,
859 'cur_namespace' => $this->getNamespace(),
860 'cur_title' => $this->getDBkey(),
861 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
862 'cur_comment' => $comment,
863 'cur_user' => $wgUser->getID(),
864 'cur_minor_edit' => 0,
865 'cur_counter' => 0,
866 'cur_restrictions' => '',
867 'cur_user_text' => $wgUser->getName(),
868 'cur_is_redirect' => 1,
869 'cur_is_new' => 1
871 /* WHERE */ array( 'cur_id' => $newid ),
872 $fname
875 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
877 # Fix the redundant names for the past revisions of the target page.
878 # The redirect should have no old revisions.
879 wfUpdateArray(
880 /* table */ 'old',
881 /* SET */ array(
882 'old_namespace' => $nt->getNamespace(),
883 'old_title' => $nt->getDBkey(),
885 /* WHERE */ array(
886 'old_namespace' => $this->getNamespace(),
887 'old_title' => $this->getDBkey(),
889 $fname
892 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
894 # Swap links
896 # Load titles and IDs
897 $linksToOld = $this->getLinksTo();
898 $linksToNew = $nt->getLinksTo();
900 # Make function to convert Titles to IDs
901 $titleToID = create_function('$t', 'return $t->getArticleID();');
903 # Reassign links to old title
904 if ( count( $linksToOld ) ) {
905 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
906 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
907 $sql .= ")";
908 wfQuery( $sql, DB_WRITE, $fname );
911 # Reassign links to new title
912 if ( count( $linksToNew ) ) {
913 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
914 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
915 $sql .= ")";
916 wfQuery( $sql, DB_WRITE, $fname );
919 # Note: the insert below must be after the updates above!
921 # Now, we record the link from the redirect to the new title.
922 # It should have no other outgoing links...
923 $sql = "DELETE FROM links WHERE l_from={$newid}";
924 wfQuery( $sql, DB_WRITE, $fname );
925 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
926 wfQuery( $sql, DB_WRITE, $fname );
928 # Purge squid
929 if ( $wgUseSquid ) {
930 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
931 $u = new SquidUpdate( $urls );
932 $u->doUpdate();
936 # Move page to non-existing title.
937 # Sets $newid to be the new article ID
939 /* private */ function moveToNewTitle( &$nt, &$newid )
941 global $wgUser, $wgLinkCache, $wgUseSquid;
942 $fname = "MovePageForm::moveToNewTitle";
943 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
945 $now = wfTimestampNow();
946 $won = wfInvertTimestamp( $now );
947 $newid = $nt->getArticleID();
948 $oldid = $this->getArticleID();
950 # Rename cur entry
951 wfUpdateArray(
952 /* table */ 'cur',
953 /* SET */ array(
954 'cur_touched' => $now,
955 'cur_namespace' => $nt->getNamespace(),
956 'cur_title' => $nt->getDBkey()
958 /* WHERE */ array( 'cur_id' => $oldid ),
959 $fname
962 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
964 # Insert redirct
965 wfInsertArray( 'cur', array(
966 'cur_namespace' => $this->getNamespace(),
967 'cur_title' => $this->getDBkey(),
968 'cur_comment' => $comment,
969 'cur_user' => $wgUser->getID(),
970 'cur_user_text' => $wgUser->getName(),
971 'cur_timestamp' => $now,
972 'inverse_timestamp' => $won,
973 'cur_touched' => $now,
974 'cur_is_redirect' => 1,
975 'cur_is_new' => 1,
976 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
978 $newid = wfInsertId();
979 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
981 # Rename old entries
982 wfUpdateArray(
983 /* table */ 'old',
984 /* SET */ array(
985 'old_namespace' => $nt->getNamespace(),
986 'old_title' => $nt->getDBkey()
988 /* WHERE */ array(
989 'old_namespace' => $this->getNamespace(),
990 'old_title' => $this->getDBkey()
991 ), $fname
994 # Miscellaneous updates
996 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
997 Article::onArticleCreate( $nt );
999 # Any text links to the old title must be reassigned to the redirect
1000 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1001 wfQuery( $sql, DB_WRITE, $fname );
1003 # Record the just-created redirect's linking to the page
1004 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1005 wfQuery( $sql, DB_WRITE, $fname );
1007 # Non-existent target may have had broken links to it; these must
1008 # now be removed and made into good links.
1009 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1010 $update->fixBrokenLinks();
1012 # Purge old title from squid
1013 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1014 $titles = $nt->getLinksTo();
1015 if ( $wgUseSquid ) {
1016 $urls = $this->getSquidURLs();
1017 foreach ( $titles as $linkTitle ) {
1018 $urls[] = $linkTitle->getInternalURL();
1020 $u = new SquidUpdate( $urls );
1021 $u->doUpdate();
1025 # Checks if $this can be moved to $nt
1026 # Both titles must exist in the database, otherwise it will blow up
1027 function isValidMoveTarget( $nt )
1029 $fname = "Title::isValidMoveTarget";
1031 # Is it a redirect?
1032 $id = $nt->getArticleID();
1033 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1034 "WHERE cur_id={$id}";
1035 $res = wfQuery( $sql, DB_READ, $fname );
1036 $obj = wfFetchObject( $res );
1038 if ( 0 == $obj->cur_is_redirect ) {
1039 # Not a redirect
1040 return false;
1043 # Does the redirect point to the source?
1044 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1045 $redirTitle = Title::newFromText( $m[1] );
1046 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1047 return false;
1051 # Does the article have a history?
1052 $row = wfGetArray( 'old', array( 'old_id' ), array(
1053 'old_namespace' => $nt->getNamespace(),
1054 'old_title' => $nt->getDBkey() )
1057 # Return true if there was no history
1058 return $row === false;
1061 # Create a redirect, fails if the title already exists, does not notify RC
1062 # Returns success
1063 function createRedirect( $dest, $comment ) {
1064 global $wgUser;
1065 if ( $this->getArticleID() ) {
1066 return false;
1069 $now = wfTimestampNow();
1070 $won = wfInvertTimestamp( $now );
1072 wfInsertArray( 'cur', array(
1073 'cur_namespace' => $this->getNamespace(),
1074 'cur_title' => $this->getDBkey(),
1075 'cur_comment' => $comment,
1076 'cur_user' => $wgUser->getID(),
1077 'cur_user_text' => $wgUser->getName(),
1078 'cur_timestamp' => $now,
1079 'inverse_timestamp' => $won,
1080 'cur_touched' => $now,
1081 'cur_is_redirect' => 1,
1082 'cur_is_new' => 1,
1083 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1085 $newid = wfInsertId();
1086 $this->resetArticleID( $newid );
1088 # Link table
1089 if ( $dest->getArticleID() ) {
1090 wfInsertArray( 'links', array(
1091 'l_to' => $dest->getArticleID(),
1092 'l_from' => $newid
1094 } else {
1095 wfInsertArray( 'brokenlinks', array(
1096 'bl_to' => $dest->getPrefixedDBkey(),
1097 'bl_from' => $newid
1101 Article::onArticleCreate( $this );
1102 return true;