removed old DaVinci files
[mediawiki.git] / includes / Title.php
blob77b1a956710563e9cde9f959f6ada9d8a759419e
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; }
491 $ur = $wgUser->getRights();
492 foreach ( $this->getRestrictions() as $r ) {
493 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
494 return false;
497 return true;
500 # Accessor/initialisation for mRestrictions
501 function getRestrictions()
503 $id = $this->getArticleID();
504 if ( 0 == $id ) { return array(); }
506 if ( ! $this->mRestrictionsLoaded ) {
507 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
508 $this->mRestrictions = explode( ",", trim( $res ) );
509 $this->mRestrictionsLoaded = true;
511 return $this->mRestrictions;
514 # Is there a version of this page in the deletion archive?
515 function isDeleted() {
516 $ns = $this->getNamespace();
517 $t = wfStrencode( $this->getDBkey() );
518 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
519 if( $res = wfQuery( $sql, DB_READ ) ) {
520 $s = wfFetchObject( $res );
521 return $s->n;
523 return 0;
526 # Get the article ID from the link cache
527 # Used very heavily, e.g. in Parser::replaceInternalLinks()
528 function getArticleID()
530 global $wgLinkCache;
532 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
533 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
534 return $this->mArticleID;
537 # This clears some fields in this object, and clears any associated keys in the
538 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
539 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
540 function resetArticleID( $newid )
542 global $wgLinkCache;
543 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
545 if ( 0 == $newid ) { $this->mArticleID = -1; }
546 else { $this->mArticleID = $newid; }
547 $this->mRestrictionsLoaded = false;
548 $this->mRestrictions = array();
551 # Updates cur_touched
552 # Called from LinksUpdate.php
553 function invalidateCache() {
554 $now = wfTimestampNow();
555 $ns = $this->getNamespace();
556 $ti = wfStrencode( $this->getDBkey() );
557 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
558 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
561 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
562 /* private */ function prefix( $name )
564 global $wgLang;
566 $p = "";
567 if ( "" != $this->mInterwiki ) {
568 $p = $this->mInterwiki . ":";
570 if ( 0 != $this->mNamespace ) {
571 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
573 return $p . $name;
576 # Secure and split - main initialisation function for this object
578 # Assumes that mDbkeyform has been set, and is urldecoded
579 # and uses undersocres, but not otherwise munged. This function
580 # removes illegal characters, splits off the winterwiki and
581 # namespace prefixes, sets the other forms, and canonicalizes
582 # everything.
584 /* private */ function secureAndSplit()
586 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
587 $fname = "Title::secureAndSplit";
588 wfProfileIn( $fname );
590 static $imgpre = false;
591 static $rxTc = false;
593 # Initialisation
594 if ( $imgpre === false ) {
595 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
596 $rxTc = "/[^" . Title::legalChars() . "]/";
599 $this->mInterwiki = $this->mFragment = "";
600 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
602 # Clean up whitespace
604 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
605 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
607 if ( "" == $t ) {
608 wfProfileOut( $fname );
609 return false;
612 $this->mDbkeyform = $t;
613 $done = false;
615 # :Image: namespace
616 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
617 $t = substr( $t, 1 );
620 # Initial colon indicating main namespace
621 if ( ":" == $t{0} ) {
622 $r = substr( $t, 1 );
623 $this->mNamespace = NS_MAIN;
624 } else {
625 # Namespace or interwiki prefix
626 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
627 #$p = strtolower( $m[1] );
628 $p = $m[1];
629 $lowerNs = strtolower( $p );
630 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
631 # Canonical namespace
632 $t = $m[2];
633 $this->mNamespace = $ns;
634 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
635 # Ordinary namespace
636 $t = $m[2];
637 $this->mNamespace = $ns;
638 } elseif ( $this->getInterwikiLink( $p ) ) {
639 # Interwiki link
640 $t = $m[2];
641 $this->mInterwiki = $p;
643 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
644 $done = true;
645 } elseif($this->mInterwiki != $wgLocalInterwiki) {
646 $done = true;
650 $r = $t;
653 # Redundant interwiki prefix to the local wiki
654 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
655 $this->mInterwiki = "";
657 # We already know that some pages won't be in the database!
659 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
660 $this->mArticleID = 0;
662 $f = strstr( $r, "#" );
663 if ( false !== $f ) {
664 $this->mFragment = substr( $f, 1 );
665 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
668 # Reject illegal characters.
670 if( preg_match( $rxTc, $r ) ) {
671 return false;
674 # "." and ".." conflict with the directories of those names
675 if ( $r === "." || $r === ".." ) {
676 return false;
679 # Initial capital letter
680 if( $wgCapitalLinks && $this->mInterwiki == "") {
681 $t = $wgLang->ucfirst( $r );
684 # Fill fields
685 $this->mDbkeyform = $t;
686 $this->mUrlform = wfUrlencode( $t );
688 $this->mTextform = str_replace( "_", " ", $t );
690 wfProfileOut( $fname );
691 return true;
694 # Get a title object associated with the talk page of this article
695 function getTalkPage() {
696 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
699 # Get a title object associated with the subject page of this talk page
700 function getSubjectPage() {
701 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
704 # Get an array of Title objects linking to this title
705 # Also stores the IDs in the link cache
706 function getLinksTo() {
707 global $wgLinkCache;
708 $id = $this->getArticleID();
709 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
710 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
711 $retVal = array();
712 if ( wfNumRows( $res ) ) {
713 while ( $row = wfFetchObject( $res ) ) {
714 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
715 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
716 $retVal[] = $titleObj;
719 wfFreeResult( $res );
720 return $retVal;
723 # Get an array of Title objects linking to this non-existent title
724 # Also stores the IDs in the link cache
725 function getBrokenLinksTo() {
726 global $wgLinkCache;
727 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
728 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
729 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
730 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
731 $retVal = array();
732 if ( wfNumRows( $res ) ) {
733 while ( $row = wfFetchObject( $res ) ) {
734 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
735 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
736 $retVal[] = $titleObj;
739 wfFreeResult( $res );
740 return $retVal;
743 function getSquidURLs() {
744 return array(
745 $this->getInternalURL(),
746 $this->getInternalURL( "action=history" )
750 function moveNoAuth( &$nt ) {
751 return $this->moveTo( $nt, false );
754 # Move a title to a new location
755 # Returns true on success, message name on failure
756 # auth indicates whether wgUser's permissions should be checked
757 function moveTo( &$nt, $auth = true ) {
758 $fname = "Title::move";
759 $oldid = $this->getArticleID();
760 $newid = $nt->getArticleID();
762 if( !$this or !$nt ) {
763 return "badtitletext";
766 if ( strlen( $nt->getDBkey() ) < 1 ) {
767 return "articleexists";
769 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
770 ( "" == $this->getDBkey() ) ||
771 ( "" != $this->getInterwiki() ) ||
772 ( !$oldid ) ||
773 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
774 ( "" == $nt->getDBkey() ) ||
775 ( "" != $nt->getInterwiki() ) ) {
776 return "badarticleerror";
779 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
780 return "protectedpage";
783 # The move is allowed only if (1) the target doesn't exist, or
784 # (2) the target is a redirect to the source, and has no history
785 # (so we can undo bad moves right after they're done).
787 if ( 0 != $newid ) { # Target exists; check for validity
788 if ( ! $this->isValidMoveTarget( $nt ) ) {
789 return "articleexists";
791 $this->moveOverExistingRedirect( $nt );
792 } else { # Target didn't exist, do normal move.
793 $this->moveToNewTitle( $nt, $newid );
796 # Update watchlists
798 $oldnamespace = $this->getNamespace() & ~1;
799 $newnamespace = $nt->getNamespace() & ~1;
800 $oldtitle = $this->getDBkey();
801 $newtitle = $nt->getDBkey();
803 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
804 WatchedItem::duplicateEntries( $this, $nt );
807 # Update search engine
808 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
809 $u->doUpdate();
810 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
811 $u->doUpdate();
813 return true;
816 # Move page to title which is presently a redirect to the source page
818 /* private */ function moveOverExistingRedirect( &$nt )
820 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
821 $fname = "Title::moveOverExistingRedirect";
822 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
824 $now = wfTimestampNow();
825 $won = wfInvertTimestamp( $now );
826 $newid = $nt->getArticleID();
827 $oldid = $this->getArticleID();
829 # Change the name of the target page:
830 wfUpdateArray(
831 /* table */ 'cur',
832 /* SET */ array(
833 'cur_touched' => $now,
834 'cur_namespace' => $nt->getNamespace(),
835 'cur_title' => $nt->getDBkey()
837 /* WHERE */ array( 'cur_id' => $oldid ),
838 $fname
840 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
842 # Repurpose the old redirect. We don't save it to history since
843 # by definition if we've got here it's rather uninteresting.
845 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
846 wfUpdateArray(
847 /* table */ 'cur',
848 /* SET */ array(
849 'cur_touched' => $now,
850 'cur_timestamp' => $now,
851 'inverse_timestamp' => $won,
852 'cur_namespace' => $this->getNamespace(),
853 'cur_title' => $this->getDBkey(),
854 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
855 'cur_comment' => $comment,
856 'cur_user' => $wgUser->getID(),
857 'cur_minor_edit' => 0,
858 'cur_counter' => 0,
859 'cur_restrictions' => '',
860 'cur_user_text' => $wgUser->getName(),
861 'cur_is_redirect' => 1,
862 'cur_is_new' => 1
864 /* WHERE */ array( 'cur_id' => $newid ),
865 $fname
868 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
870 # Fix the redundant names for the past revisions of the target page.
871 # The redirect should have no old revisions.
872 wfUpdateArray(
873 /* table */ 'old',
874 /* SET */ array(
875 'old_namespace' => $nt->getNamespace(),
876 'old_title' => $nt->getDBkey(),
878 /* WHERE */ array(
879 'old_namespace' => $this->getNamespace(),
880 'old_title' => $this->getDBkey(),
882 $fname
885 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
887 # Swap links
889 # Load titles and IDs
890 $linksToOld = $this->getLinksTo();
891 $linksToNew = $nt->getLinksTo();
893 # Make function to convert Titles to IDs
894 $titleToID = create_function('$t', 'return $t->getArticleID();');
896 # Reassign links to old title
897 if ( count( $linksToOld ) ) {
898 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
899 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
900 $sql .= ")";
901 wfQuery( $sql, DB_WRITE, $fname );
904 # Reassign links to new title
905 if ( count( $linksToNew ) ) {
906 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
907 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
908 $sql .= ")";
909 wfQuery( $sql, DB_WRITE, $fname );
912 # Note: the insert below must be after the updates above!
914 # Now, we record the link from the redirect to the new title.
915 # It should have no other outgoing links...
916 $sql = "DELETE FROM links WHERE l_from={$newid}";
917 wfQuery( $sql, DB_WRITE, $fname );
918 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
919 wfQuery( $sql, DB_WRITE, $fname );
921 # Purge squid
922 if ( $wgUseSquid ) {
923 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
924 $u = new SquidUpdate( $urls );
925 $u->doUpdate();
929 # Move page to non-existing title.
930 # Sets $newid to be the new article ID
932 /* private */ function moveToNewTitle( &$nt, &$newid )
934 global $wgUser, $wgLinkCache, $wgUseSquid;
935 $fname = "MovePageForm::moveToNewTitle";
936 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
938 $now = wfTimestampNow();
939 $won = wfInvertTimestamp( $now );
940 $newid = $nt->getArticleID();
941 $oldid = $this->getArticleID();
943 # Rename cur entry
944 wfUpdateArray(
945 /* table */ 'cur',
946 /* SET */ array(
947 'cur_touched' => $now,
948 'cur_namespace' => $nt->getNamespace(),
949 'cur_title' => $nt->getDBkey()
951 /* WHERE */ array( 'cur_id' => $oldid ),
952 $fname
955 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
957 # Insert redirct
958 wfInsertArray( 'cur', array(
959 'cur_namespace' => $this->getNamespace(),
960 'cur_title' => $this->getDBkey(),
961 'cur_comment' => $comment,
962 'cur_user' => $wgUser->getID(),
963 'cur_user_text' => $wgUser->getName(),
964 'cur_timestamp' => $now,
965 'inverse_timestamp' => $won,
966 'cur_touched' => $now,
967 'cur_is_redirect' => 1,
968 'cur_is_new' => 1,
969 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
971 $newid = wfInsertId();
972 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
974 # Rename old entries
975 wfUpdateArray(
976 /* table */ 'old',
977 /* SET */ array(
978 'old_namespace' => $nt->getNamespace(),
979 'old_title' => $nt->getDBkey()
981 /* WHERE */ array(
982 'old_namespace' => $this->getNamespace(),
983 'old_title' => $this->getDBkey()
984 ), $fname
987 # Miscellaneous updates
989 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
990 Article::onArticleCreate( $nt );
992 # Any text links to the old title must be reassigned to the redirect
993 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
994 wfQuery( $sql, DB_WRITE, $fname );
996 # Record the just-created redirect's linking to the page
997 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
998 wfQuery( $sql, DB_WRITE, $fname );
1000 # Non-existent target may have had broken links to it; these must
1001 # now be removed and made into good links.
1002 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1003 $update->fixBrokenLinks();
1005 # Purge old title from squid
1006 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1007 $titles = $nt->getLinksTo();
1008 if ( $wgUseSquid ) {
1009 $urls = $this->getSquidURLs();
1010 foreach ( $titles as $linkTitle ) {
1011 $urls[] = $linkTitle->getInternalURL();
1013 $u = new SquidUpdate( $urls );
1014 $u->doUpdate();
1018 # Checks if $this can be moved to $nt
1019 # Both titles must exist in the database, otherwise it will blow up
1020 function isValidMoveTarget( $nt )
1022 $fname = "Title::isValidMoveTarget";
1024 # Is it a redirect?
1025 $id = $nt->getArticleID();
1026 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1027 "WHERE cur_id={$id}";
1028 $res = wfQuery( $sql, DB_READ, $fname );
1029 $obj = wfFetchObject( $res );
1031 if ( 0 == $obj->cur_is_redirect ) {
1032 # Not a redirect
1033 return false;
1036 # Does the redirect point to the source?
1037 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1038 $redirTitle = Title::newFromText( $m[1] );
1039 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1040 return false;
1044 # Does the article have a history?
1045 $row = wfGetArray( 'old', array( 'old_id' ), array(
1046 'old_namespace' => $nt->getNamespace(),
1047 'old_title' => $nt->getDBkey() )
1050 # Return true if there was no history
1051 return $row === false;
1054 # Create a redirect, fails if the title already exists, does not notify RC
1055 # Returns success
1056 function createRedirect( $dest, $comment ) {
1057 global $wgUser;
1058 if ( $this->getArticleID() ) {
1059 return false;
1062 $now = wfTimestampNow();
1063 $won = wfInvertTimestamp( $now );
1065 wfInsertArray( 'cur', array(
1066 'cur_namespace' => $this->getNamespace(),
1067 'cur_title' => $this->getDBkey(),
1068 'cur_comment' => $comment,
1069 'cur_user' => $wgUser->getID(),
1070 'cur_user_text' => $wgUser->getName(),
1071 'cur_timestamp' => $now,
1072 'inverse_timestamp' => $won,
1073 'cur_touched' => $now,
1074 'cur_is_redirect' => 1,
1075 'cur_is_new' => 1,
1076 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1078 $newid = wfInsertId();
1079 $this->resetArticleID( $newid );
1081 # Link table
1082 if ( $dest->getArticleID() ) {
1083 wfInsertArray( 'links', array(
1084 'l_to' => $dest->getArticleID(),
1085 'l_from' => $newid
1087 } else {
1088 wfInsertArray( 'brokenlinks', array(
1089 'bl_to' => $dest->getPrefixedDBkey(),
1090 'bl_from' => $newid
1094 Article::onArticleCreate( $this );
1095 return true;