page-move code moved to Title and disentangled from the user interface
[mediawiki.git] / includes / Title.php
blob3de57d4924ce545e008d466b8de84de76ffcc897
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( $t->secureAndSplit() ) {
89 return $t;
90 } else {
91 return NULL;
95 # From a URL-encoded title
96 /* static */ function newFromURL( $url )
98 global $wgLang, $wgServer;
99 $t = new Title();
100 $s = urldecode( $url ); # This is technically wrong, as anything
101 # we've gotten is already decoded by PHP.
102 # Kept for backwards compatibility with
103 # buggy URLs we had for a while...
104 $s = $url;
106 # For links that came from outside, check for alternate/legacy
107 # character encoding.
108 wfDebug( "Servr: $wgServer\n" );
109 if( empty( $_SERVER["HTTP_REFERER"] ) ||
110 strncmp($wgServer, $_SERVER["HTTP_REFERER"], strlen( $wgServer ) ) )
112 $s = $wgLang->checkTitleEncoding( $s );
113 } else {
114 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
117 $t->mDbkeyform = str_replace( " ", "_", $s );
118 if( $t->secureAndSplit() ) {
120 # check that lenght of title is < cur_title size
121 $sql = "SHOW COLUMNS FROM cur LIKE \"cur_title\";";
122 $cur_title_object = wfFetchObject(wfQuery( $sql, DB_READ ));
124 preg_match( "/\((.*)\)/", $cur_title_object->Type, $cur_title_size);
126 if (strlen($t->mDbkeyform) > $cur_title_size[1] ) {
127 return NULL;
130 return $t;
131 } else {
132 return NULL;
136 # From a cur_id
137 # This is inefficiently implemented, the cur row is requested but not
138 # used for anything else
139 /* static */ function newFromID( $id )
141 $fname = "Title::newFromID";
142 $row = wfGetArray( "cur", array( "cur_namespace", "cur_title" ),
143 array( "cur_id" => $id ), $fname );
144 if ( $row !== false ) {
145 $title = Title::makeTitle( $row->cur_namespace, $row->cur_title );
146 } else {
147 $title = NULL;
149 return $title;
152 # From a namespace index and a DB key
153 /* static */ function makeTitle( $ns, $title )
155 $t = new Title();
156 $t->mDbkeyform = Title::makeName( $ns, $title );
157 if( $t->secureAndSplit() ) {
158 return $t;
159 } else {
160 return NULL;
164 function newMainPage()
166 return Title::newFromText( wfMsg( "mainpage" ) );
169 #----------------------------------------------------------------------------
170 # Static functions
171 #----------------------------------------------------------------------------
173 # Get the prefixed DB key associated with an ID
174 /* static */ function nameOf( $id )
176 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
177 "cur_id={$id}";
178 $res = wfQuery( $sql, DB_READ, "Article::nameOf" );
179 if ( 0 == wfNumRows( $res ) ) { return NULL; }
181 $s = wfFetchObject( $res );
182 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
183 return $n;
186 # Get a regex character class describing the legal characters in a link
187 /* static */ function legalChars()
189 # Missing characters:
190 # * []|# Needed for link syntax
191 # * % and + are corrupted by Apache when they appear in the path
193 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
194 # this breaks interlanguage links
196 $set = " !\"$&'()*,\\-.\\/0-9:;<=>?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
197 return $set;
200 # Returns a stripped-down a title string ready for the search index
201 # Takes a namespace index and a text-form main part
202 /* static */ function indexTitle( $ns, $title )
204 global $wgDBminWordLen, $wgLang;
206 $lc = SearchEngine::legalSearchChars() . "&#;";
207 $t = $wgLang->stripForSearch( $title );
208 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
209 $t = strtolower( $t );
211 # Handle 's, s'
212 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
213 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
215 $t = preg_replace( "/\\s+/", " ", $t );
217 if ( $ns == Namespace::getImage() ) {
218 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
220 return trim( $t );
223 # Make a prefixed DB key from a DB key and a namespace index
224 /* static */ function makeName( $ns, $title )
226 global $wgLang;
228 $n = $wgLang->getNsText( $ns );
229 if ( "" == $n ) { return $title; }
230 else { return "{$n}:{$title}"; }
233 # Arguably static
234 # Returns the URL associated with an interwiki prefix
235 # The URL contains $1, which is replaced by the title
236 function getInterwikiLink( $key )
238 global $wgMemc, $wgDBname, $title_interwiki_cache;
239 $k = "$wgDBname:interwiki:$key";
241 if( array_key_exists( $k, $title_interwiki_cache ) )
242 return $title_interwiki_cache[$k]->iw_url;
244 $s = $wgMemc->get( $k );
245 if( $s ) {
246 $title_interwiki_cache[$k] = $s;
247 return $s->iw_url;
249 $dkey = wfStrencode( $key );
250 $query = "SELECT iw_url FROM interwiki WHERE iw_prefix='$dkey'";
251 $res = wfQuery( $query, DB_READ, "Title::getInterwikiLink" );
252 if(!$res) return "";
254 $s = wfFetchObject( $res );
255 if(!$s) {
256 $s = (object)false;
257 $s->iw_url = "";
259 $wgMemc->set( $k, $s );
260 $title_interwiki_cache[$k] = $s;
261 return $s->iw_url;
264 # Update the cur_touched field for an array of title objects
265 # Inefficient unless the IDs are already loaded into the link cache
266 /* static */ function touchArray( $titles, $timestamp = "" ) {
267 if ( count( $titles ) == 0 ) {
268 return;
270 if ( $timestamp == "" ) {
271 $timestamp = wfTimestampNow();
273 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
274 $first = true;
276 foreach ( $titles as $title ) {
277 if ( ! $first ) {
278 $sql .= ",";
281 $first = false;
282 $sql .= $title->getArticleID();
284 $sql .= ")";
285 if ( ! $first ) {
286 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
290 #----------------------------------------------------------------------------
291 # Other stuff
292 #----------------------------------------------------------------------------
294 # Simple accessors
295 # See the definitions at the top of this file
297 function getText() { return $this->mTextform; }
298 function getPartialURL() { return $this->mUrlform; }
299 function getDBkey() { return $this->mDbkeyform; }
300 function getNamespace() { return $this->mNamespace; }
301 function setNamespace( $n ) { $this->mNamespace = $n; }
302 function getInterwiki() { return $this->mInterwiki; }
303 function getFragment() { return $this->mFragment; }
304 function getDefaultNamespace() { return $this->mDefaultNamespace; }
306 # Get title for search index
307 function getIndexTitle()
309 return Title::indexTitle( $this->mNamespace, $this->mTextform );
312 # Get prefixed title with underscores
313 function getPrefixedDBkey()
315 $s = $this->prefix( $this->mDbkeyform );
316 $s = str_replace( " ", "_", $s );
317 return $s;
320 # Get prefixed title with spaces
321 # This is the form usually used for display
322 function getPrefixedText()
324 if ( empty( $this->mPrefixedText ) ) {
325 $s = $this->prefix( $this->mTextform );
326 $s = str_replace( "_", " ", $s );
327 $this->mPrefixedText = $s;
329 return $this->mPrefixedText;
332 # Get a URL-encoded title (not an actual URL) including interwiki
333 function getPrefixedURL()
335 $s = $this->prefix( $this->mDbkeyform );
336 $s = str_replace( " ", "_", $s );
338 $s = wfUrlencode ( $s ) ;
340 # Cleaning up URL to make it look nice -- is this safe?
341 $s = preg_replace( "/%3[Aa]/", ":", $s );
342 $s = preg_replace( "/%2[Ff]/", "/", $s );
343 $s = str_replace( "%28", "(", $s );
344 $s = str_replace( "%29", ")", $s );
346 return $s;
349 # Get a real URL referring to this title, with interwiki link and fragment
350 function getFullURL( $query = "" )
352 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
354 if ( "" == $this->mInterwiki ) {
355 $p = $wgArticlePath;
356 return $wgServer . $this->getLocalUrl( $query );
359 $p = $this->getInterwikiLink( $this->mInterwiki );
360 $n = $wgLang->getNsText( $this->mNamespace );
361 if ( "" != $n ) { $n .= ":"; }
362 $u = str_replace( "$1", $n . $this->mUrlform, $p );
363 if ( "" != $this->mFragment ) {
364 $u .= "#" . wfUrlencode( $this->mFragment );
366 return $u;
369 # Get a URL with an optional query string, no fragment
370 # * If $query=="", it will use $wgArticlePath
371 # * Returns a full for an interwiki link, loses any query string
372 # * Optionally adds the server and escapes for HTML
373 # * Setting $query to "-" makes an old-style URL with nothing in the
374 # query except a title
376 function getURL() {
377 die( "Call to obsolete obsolete function Title::getURL()" );
380 function getLocalURL( $query = "" )
382 global $wgLang, $wgArticlePath, $wgScript;
384 if ( $this->isExternal() ) {
385 return $this->getFullURL();
388 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
389 if ( $query == "" ) {
390 $url = str_replace( "$1", $dbkey, $wgArticlePath );
391 } else {
392 if ( $query == "-" ) {
393 $query = "";
395 if ( $wgScript != "" ) {
396 $url = "{$wgScript}?title={$dbkey}&{$query}";
397 } else {
398 # Top level wiki
399 $url = "/{$dbkey}?{$query}";
402 return $url;
405 function escapeLocalURL( $query = "" ) {
406 return wfEscapeHTML( $this->getLocalURL( $query ) );
409 function escapeFullURL( $query = "" ) {
410 return wfEscapeHTML( $this->getFullURL( $query ) );
413 function getInternalURL( $query = "" ) {
414 # Used in various Squid-related code, in case we have a different
415 # internal hostname for the server than the exposed one.
416 global $wgInternalServer;
417 return $wgInternalServer . $this->getLocalURL( $query );
420 # Get the edit URL, or a null string if it is an interwiki link
421 function getEditURL()
423 global $wgServer, $wgScript;
425 if ( "" != $this->mInterwiki ) { return ""; }
426 $s = $this->getLocalURL( "action=edit" );
428 return $s;
431 # Get HTML-escaped displayable text
432 # For the title field in <a> tags
433 function getEscapedText()
435 return wfEscapeHTML( $this->getPrefixedText() );
438 # Is the title interwiki?
439 function isExternal() { return ( "" != $this->mInterwiki ); }
441 # Does the title correspond to a protected article?
442 function isProtected()
444 if ( -1 == $this->mNamespace ) { return true; }
445 $a = $this->getRestrictions();
446 if ( in_array( "sysop", $a ) ) { return true; }
447 return false;
450 # Is the page a log page, i.e. one where the history is messed up by
451 # LogPage.php? This used to be used for suppressing diff links in recent
452 # changes, but now that's done by setting a flag in the recentchanges
453 # table. Hence, this probably is no longer used.
454 function isLog()
456 if ( $this->mNamespace != Namespace::getWikipedia() ) {
457 return false;
459 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
460 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
461 return true;
463 return false;
466 # Is $wgUser is watching this page?
467 function userIsWatching()
469 global $wgUser;
471 if ( -1 == $this->mNamespace ) { return false; }
472 if ( 0 == $wgUser->getID() ) { return false; }
474 return $wgUser->isWatched( $this );
477 # Can $wgUser edit this page?
478 function userCanEdit()
480 global $wgUser;
482 if ( -1 == $this->mNamespace ) { return false; }
483 # if ( 0 == $this->getArticleID() ) { return false; }
484 if ( $this->mDbkeyform == "_" ) { return false; }
486 $ur = $wgUser->getRights();
487 foreach ( $this->getRestrictions() as $r ) {
488 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
489 return false;
492 return true;
495 # Accessor/initialisation for mRestrictions
496 function getRestrictions()
498 $id = $this->getArticleID();
499 if ( 0 == $id ) { return array(); }
501 if ( ! $this->mRestrictionsLoaded ) {
502 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
503 $this->mRestrictions = explode( ",", trim( $res ) );
504 $this->mRestrictionsLoaded = true;
506 return $this->mRestrictions;
509 # Is there a version of this page in the deletion archive?
510 function isDeleted() {
511 $ns = $this->getNamespace();
512 $t = wfStrencode( $this->getDBkey() );
513 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
514 if( $res = wfQuery( $sql, DB_READ ) ) {
515 $s = wfFetchObject( $res );
516 return $s->n;
518 return 0;
521 # Get the article ID from the link cache
522 # Used very heavily, e.g. in Parser::replaceInternalLinks()
523 function getArticleID()
525 global $wgLinkCache;
527 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
528 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
529 return $this->mArticleID;
532 # This clears some fields in this object, and clears any associated keys in the
533 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
534 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
535 function resetArticleID( $newid )
537 global $wgLinkCache;
538 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
540 if ( 0 == $newid ) { $this->mArticleID = -1; }
541 else { $this->mArticleID = $newid; }
542 $this->mRestrictionsLoaded = false;
543 $this->mRestrictions = array();
546 # Updates cur_touched
547 # Called from LinksUpdate.php
548 function invalidateCache() {
549 $now = wfTimestampNow();
550 $ns = $this->getNamespace();
551 $ti = wfStrencode( $this->getDBkey() );
552 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
553 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
556 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
557 /* private */ function prefix( $name )
559 global $wgLang;
561 $p = "";
562 if ( "" != $this->mInterwiki ) {
563 $p = $this->mInterwiki . ":";
565 if ( 0 != $this->mNamespace ) {
566 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
568 return $p . $name;
571 # Secure and split - main initialisation function for this object
573 # Assumes that mDbkeyform has been set, and is urldecoded
574 # and uses undersocres, but not otherwise munged. This function
575 # removes illegal characters, splits off the winterwiki and
576 # namespace prefixes, sets the other forms, and canonicalizes
577 # everything.
579 /* private */ function secureAndSplit()
581 global $wgLang, $wgLocalInterwiki;
582 $fname = "Title::secureAndSplit";
583 wfProfileIn( $fname );
585 static $imgpre = false;
586 static $rxTc = false;
588 # Initialisation
589 if ( $imgpre === false ) {
590 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
591 $rxTc = "/[^" . Title::legalChars() . "]/";
594 $this->mInterwiki = $this->mFragment = "";
595 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
597 # Clean up whitespace
599 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
600 if ( "_" == @$t{0} ) {
601 $t = substr( $t, 1 );
603 $l = strlen( $t );
604 if ( $l && ( "_" == $t{$l-1} ) ) {
605 $t = substr( $t, 0, $l-1 );
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 if ( $ns = $wgLang->getNsIndex( strtolower( $p ) )) {
630 # Ordinary namespace
631 $t = $m[2];
632 $this->mNamespace = $ns;
633 } elseif ( $this->getInterwikiLink( $p ) ) {
634 # Interwiki link
635 $t = $m[2];
636 $this->mInterwiki = $p;
638 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
639 $done = true;
640 } elseif($this->mInterwiki != $wgLocalInterwiki) {
641 $done = true;
645 $r = $t;
648 # Redundant interwiki prefix to the local wiki
649 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
650 $this->mInterwiki = "";
652 # We already know that some pages won't be in the database!
654 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
655 $this->mArticleID = 0;
657 $f = strstr( $r, "#" );
658 if ( false !== $f ) {
659 $this->mFragment = substr( $f, 1 );
660 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
663 # Reject illegal characters.
665 if( preg_match( $rxTc, $r ) ) {
666 return false;
669 # "." and ".." conflict with the directories of those names
670 if ( $r === "." || $r === ".." ) {
671 return false;
674 # Initial capital letter
675 if( $this->mInterwiki == "") $t = $wgLang->ucfirst( $r );
677 # Fill fields
678 $this->mDbkeyform = $t;
679 $this->mUrlform = wfUrlencode( $t );
681 $this->mTextform = str_replace( "_", " ", $t );
683 wfProfileOut( $fname );
684 return true;
687 # Get a title object associated with the talk page of this article
688 function getTalkPage() {
689 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
692 # Get a title object associated with the subject page of this talk page
693 function getSubjectPage() {
694 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
697 # Get an array of Title objects linking to this title
698 # Also stores the IDs in the link cache
699 function getLinksTo() {
700 global $wgLinkCache;
701 $id = $this->getArticleID();
702 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
703 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
704 $retVal = array();
705 if ( wfNumRows( $res ) ) {
706 while ( $row = wfFetchObject( $res ) ) {
707 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
708 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
709 $retVal[] = $titleObj;
712 wfFreeResult( $res );
713 return $retVal;
716 # Get an array of Title objects linking to this non-existent title
717 # Also stores the IDs in the link cache
718 function getBrokenLinksTo() {
719 global $wgLinkCache;
720 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
721 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
722 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
723 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
724 $retVal = array();
725 if ( wfNumRows( $res ) ) {
726 while ( $row = wfFetchObject( $res ) ) {
727 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
728 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
729 $retVal[] = $titleObj;
732 wfFreeResult( $res );
733 return $retVal;
736 function getSquidURLs() {
737 return array(
738 $this->getInternalURL(),
739 $this->getInternalURL( "action=history" )
743 function moveNoAuth( &$nt ) {
744 return $this->moveTo( $nt, false );
747 # Move a title to a new location
748 # Returns true on success, message name on failure
749 # auth indicates whether wgUser's permissions should be checked
750 function moveTo( &$nt, $auth = true ) {
751 $fname = "Title::move";
752 $oldid = $this->getArticleID();
753 $newid = $nt->getArticleID();
755 if( !$this or !$nt ) {
756 return "badtitletext";
759 if ( strlen( $nt->getDBkey() ) < 1 ) {
760 return "articleexists";
762 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
763 ( "" == $this->getDBkey() ) ||
764 ( "" != $this->getInterwiki() ) ||
765 ( !$oldid ) ||
766 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
767 ( "" == $nt->getDBkey() ) ||
768 ( "" != $nt->getInterwiki() ) ) {
769 return "badarticleerror";
772 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
773 return "protectedpage";
776 # The move is allowed only if (1) the target doesn't exist, or
777 # (2) the target is a redirect to the source, and has no history
778 # (so we can undo bad moves right after they're done).
780 if ( 0 != $newid ) { # Target exists; check for validity
781 if ( ! $this->isValidMoveTarget( $nt ) ) {
782 return "articleexists";
784 $this->moveOverExistingRedirect( $nt );
785 } else { # Target didn't exist, do normal move.
786 $this->moveToNewTitle( $nt, $newid );
789 # Update watchlists
791 $oldnamespace = $this->getNamespace() & ~1;
792 $newnamespace = $nt->getNamespace() & ~1;
793 $oldtitle = $this->getDBkey();
794 $newtitle = $nt->getDBkey();
796 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
797 WatchedItem::duplicateEntries( $this, $nt );
800 # Update search engine
801 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
802 $u->doUpdate();
803 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
804 $u->doUpdate();
806 return true;
809 # Move page to title which is presently a redirect to the source page
811 /* private */ function moveOverExistingRedirect( &$nt )
813 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
814 $fname = "Title::moveOverExistingRedirect";
815 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
817 $now = wfTimestampNow();
818 $won = wfInvertTimestamp( $now );
819 $newid = $nt->getArticleID();
820 $oldid = $this->getArticleID();
822 # Change the name of the target page:
823 wfUpdateArray(
824 /* table */ 'cur',
825 /* SET */ array(
826 'cur_touched' => $now,
827 'cur_namespace' => $nt->getNamespace(),
828 'cur_title' => $nt->getDBkey()
830 /* WHERE */ array( 'cur_id' => $oldid ),
831 $fname
833 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
835 # Repurpose the old redirect. We don't save it to history since
836 # by definition if we've got here it's rather uninteresting.
838 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
839 wfUpdateArray(
840 /* table */ 'cur',
841 /* SET */ array(
842 'cur_touched' => $now,
843 'cur_timestamp' => $now,
844 'inverse_timestamp' => $won,
845 'cur_namespace' => $this->getNamespace(),
846 'cur_title' => $this->getDBkey(),
847 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
848 'cur_comment' => $comment,
849 'cur_user' => $wgUser->getID(),
850 'cur_minor_edit' => 0,
851 'cur_counter' => 0,
852 'cur_restrictions' => '',
853 'cur_user_text' => $wgUser->getName(),
854 'cur_is_redirect' => 1,
855 'cur_is_new' => 1
857 /* WHERE */ array( 'cur_id' => $newid ),
858 $fname
861 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
863 # Fix the redundant names for the past revisions of the target page.
864 # The redirect should have no old revisions.
865 wfUpdateArray(
866 /* table */ 'old',
867 /* SET */ array(
868 'old_namespace' => $nt->getNamespace(),
869 'old_title' => $nt->getDBkey(),
871 /* WHERE */ array(
872 'old_namespace' => $this->getNamespace(),
873 'old_title' => $this->getDBkey(),
875 $fname
878 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
880 # Swap links
882 # Load titles and IDs
883 $linksToOld = $this->getLinksTo();
884 $linksToNew = $nt->getLinksTo();
886 # Make function to convert Titles to IDs
887 $titleToID = create_function('$t', 'return $t->getArticleID();');
889 # Reassign links to old title
890 if ( count( $linksToOld ) ) {
891 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
892 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
893 $sql .= ")";
894 wfQuery( $sql, DB_WRITE, $fname );
897 # Reassign links to new title
898 if ( count( $linksToNew ) ) {
899 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
900 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
901 $sql .= ")";
902 wfQuery( $sql, DB_WRITE, $fname );
905 # Note: the insert below must be after the updates above!
907 # Now, we record the link from the redirect to the new title.
908 # It should have no other outgoing links...
909 $sql = "DELETE FROM links WHERE l_from={$newid}";
910 wfQuery( $sql, DB_WRITE, $fname );
911 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
912 wfQuery( $sql, DB_WRITE, $fname );
914 # Purge squid
915 if ( $wgUseSquid ) {
916 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
917 $u = new SquidUpdate( $urls );
918 $u->doUpdate();
922 # Move page to non-existing title.
923 # Sets $newid to be the new article ID
925 /* private */ function moveToNewTitle( &$nt, &$newid )
927 global $wgUser, $wgLinkCache, $wgUseSquid;
928 $fname = "MovePageForm::moveToNewTitle";
929 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
931 $now = wfTimestampNow();
932 $won = wfInvertTimestamp( $now );
933 $newid = $nt->getArticleID();
934 $oldid = $this->getArticleID();
936 # Rename cur entry
937 wfUpdateArray(
938 /* table */ 'cur',
939 /* SET */ array(
940 'cur_touched' => $now,
941 'cur_namespace' => $nt->getNamespace(),
942 'cur_title' => $nt->getDBkey()
944 /* WHERE */ array( 'cur_id' => $oldid ),
945 $fname
948 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
950 # Insert redirct
951 wfInsertArray( 'cur', array(
952 'cur_namespace' => $this->getNamespace(),
953 'cur_title' => $this->getDBkey(),
954 'cur_comment' => $comment,
955 'cur_user' => $wgUser->getID(),
956 'cur_user_text' => $wgUser->getName(),
957 'cur_timestamp' => $now,
958 'inverse_timestamp' => $won,
959 'cur_touched' => $now,
960 'cur_is_redirect' => 1,
961 'cur_is_new' => 1,
962 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
964 $newid = wfInsertId();
965 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
967 # Rename old entries
968 wfUpdateArray(
969 /* table */ 'old',
970 /* SET */ array(
971 'old_namespace' => $nt->getNamespace(),
972 'old_title' => $nt->getDBkey()
974 /* WHERE */ array(
975 'old_namespace' => $this->getNamespace(),
976 'old_title' => $this->getDBkey()
977 ), $fname
980 # Miscellaneous updates
982 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
983 Article::onArticleCreate( $nt );
985 # Any text links to the old title must be reassigned to the redirect
986 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
987 wfQuery( $sql, DB_WRITE, $fname );
989 # Record the just-created redirect's linking to the page
990 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
991 wfQuery( $sql, DB_WRITE, $fname );
993 # Non-existent target may have had broken links to it; these must
994 # now be removed and made into good links.
995 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
996 $update->fixBrokenLinks();
998 # Purge old title from squid
999 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1000 $titles = $nt->getLinksTo();
1001 if ( $wgUseSquid ) {
1002 $urls = $this->getSquidURLs();
1003 foreach ( $titles as $linkTitle ) {
1004 $urls[] = $linkTitle->getInternalURL();
1006 $u = new SquidUpdate( $urls );
1007 $u->doUpdate();
1011 # Checks if $this can be moved to $nt
1012 # Both titles must exist in the database, otherwise it will blow up
1013 function isValidMoveTarget( $nt )
1015 $fname = "Title::isValidMoveTarget";
1017 # Is it a redirect?
1018 $id = $nt->getArticleID();
1019 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1020 "WHERE cur_id={$id}";
1021 $res = wfQuery( $sql, DB_READ, $fname );
1022 $obj = wfFetchObject( $res );
1024 if ( 0 == $obj->cur_is_redirect ) {
1025 # Not a redirect
1026 return false;
1029 # Does the redirect point to the source?
1030 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1031 $redirTitle = Title::newFromText( $m[1] );
1032 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1033 return false;
1037 # Does the article have a history?
1038 $row = wfGetArray( 'old', array( 'old_id' ), array(
1039 'old_namespace' => $nt->getNamespace(),
1040 'old_title' => $nt->getDBkey() )
1043 # Return true if there was no history
1044 return $row === false;