Moved image history retrieval function to Image.php.
[mediawiki.git] / includes / Title.php
blobb387d172b9702f8e6801eb7023adb363e6b4f556
1 <?php
2 # See title.doc
4 $wgTitleInterwikiCache = 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, $wgInterwikiExpiry;
242 static $wgTitleInterwikiCache = array();
244 $k = "$wgDBname:interwiki:$key";
246 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
247 return $wgTitleInterwikiCache[$k]->iw_url;
249 $s = $wgMemc->get( $k );
250 # Ignore old keys with no iw_local
251 if( $s && isset( $s->iw_local ) ) {
252 $wgTitleInterwikiCache[$k] = $s;
253 return $s->iw_url;
255 $dkey = wfStrencode( $key );
256 $query = "SELECT iw_url,iw_local FROM interwiki WHERE iw_prefix='$dkey'";
257 $res = wfQuery( $query, DB_READ, "Title::getInterwikiLink" );
258 if(!$res) return "";
260 $s = wfFetchObject( $res );
261 if(!$s) {
262 $s = (object)false;
263 $s->iw_url = "";
265 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
266 $wgTitleInterwikiCache[$k] = $s;
267 return $s->iw_url;
270 function isLocal() {
271 global $wgTitleInterwikiCache, $wgDBname;
273 if ( $this->mInterwiki != "" ) {
274 # Make sure key is loaded into cache
275 $this->getInterwikiLink( $this->mInterwiki );
276 $k = "$wgDBname:interwiki:" . $this->mInterwiki;
277 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
278 } else {
279 return true;
283 # Update the cur_touched field for an array of title objects
284 # Inefficient unless the IDs are already loaded into the link cache
285 /* static */ function touchArray( $titles, $timestamp = "" ) {
286 if ( count( $titles ) == 0 ) {
287 return;
289 if ( $timestamp == "" ) {
290 $timestamp = wfTimestampNow();
292 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
293 $first = true;
295 foreach ( $titles as $title ) {
296 if ( ! $first ) {
297 $sql .= ",";
300 $first = false;
301 $sql .= $title->getArticleID();
303 $sql .= ")";
304 if ( ! $first ) {
305 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
309 #----------------------------------------------------------------------------
310 # Other stuff
311 #----------------------------------------------------------------------------
313 # Simple accessors
314 # See the definitions at the top of this file
316 function getText() { return $this->mTextform; }
317 function getPartialURL() { return $this->mUrlform; }
318 function getDBkey() { return $this->mDbkeyform; }
319 function getNamespace() { return $this->mNamespace; }
320 function setNamespace( $n ) { $this->mNamespace = $n; }
321 function getInterwiki() { return $this->mInterwiki; }
322 function getFragment() { return $this->mFragment; }
323 function getDefaultNamespace() { return $this->mDefaultNamespace; }
325 # Get title for search index
326 function getIndexTitle()
328 return Title::indexTitle( $this->mNamespace, $this->mTextform );
331 # Get prefixed title with underscores
332 function getPrefixedDBkey()
334 $s = $this->prefix( $this->mDbkeyform );
335 $s = str_replace( " ", "_", $s );
336 return $s;
339 # Get prefixed title with spaces
340 # This is the form usually used for display
341 function getPrefixedText()
343 if ( empty( $this->mPrefixedText ) ) {
344 $s = $this->prefix( $this->mTextform );
345 $s = str_replace( "_", " ", $s );
346 $this->mPrefixedText = $s;
348 return $this->mPrefixedText;
351 # Get a URL-encoded title (not an actual URL) including interwiki
352 function getPrefixedURL()
354 $s = $this->prefix( $this->mDbkeyform );
355 $s = str_replace( " ", "_", $s );
357 $s = wfUrlencode ( $s ) ;
359 # Cleaning up URL to make it look nice -- is this safe?
360 $s = preg_replace( "/%3[Aa]/", ":", $s );
361 $s = preg_replace( "/%2[Ff]/", "/", $s );
362 $s = str_replace( "%28", "(", $s );
363 $s = str_replace( "%29", ")", $s );
365 return $s;
368 # Get a real URL referring to this title, with interwiki link and fragment
369 function getFullURL( $query = "" )
371 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
373 if ( "" == $this->mInterwiki ) {
374 $p = $wgArticlePath;
375 return $wgServer . $this->getLocalUrl( $query );
378 $p = $this->getInterwikiLink( $this->mInterwiki );
379 $n = $wgLang->getNsText( $this->mNamespace );
380 if ( "" != $n ) { $n .= ":"; }
381 $u = str_replace( "$1", $n . $this->mUrlform, $p );
382 if ( "" != $this->mFragment ) {
383 $u .= "#" . wfUrlencode( $this->mFragment );
385 return $u;
388 # Get a URL with an optional query string, no fragment
389 # * If $query=="", it will use $wgArticlePath
390 # * Returns a full for an interwiki link, loses any query string
391 # * Optionally adds the server and escapes for HTML
392 # * Setting $query to "-" makes an old-style URL with nothing in the
393 # query except a title
395 function getURL() {
396 die( "Call to obsolete obsolete function Title::getURL()" );
399 function getLocalURL( $query = "" )
401 global $wgLang, $wgArticlePath, $wgScript;
403 if ( $this->isExternal() ) {
404 return $this->getFullURL();
407 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
408 if ( $query == "" ) {
409 $url = str_replace( "$1", $dbkey, $wgArticlePath );
410 } else {
411 if ( $query == "-" ) {
412 $query = "";
414 if ( $wgScript != "" ) {
415 $url = "{$wgScript}?title={$dbkey}&{$query}";
416 } else {
417 # Top level wiki
418 $url = "/{$dbkey}?{$query}";
421 return $url;
424 function escapeLocalURL( $query = "" ) {
425 return wfEscapeHTML( $this->getLocalURL( $query ) );
428 function escapeFullURL( $query = "" ) {
429 return wfEscapeHTML( $this->getFullURL( $query ) );
432 function getInternalURL( $query = "" ) {
433 # Used in various Squid-related code, in case we have a different
434 # internal hostname for the server than the exposed one.
435 global $wgInternalServer;
436 return $wgInternalServer . $this->getLocalURL( $query );
439 # Get the edit URL, or a null string if it is an interwiki link
440 function getEditURL()
442 global $wgServer, $wgScript;
444 if ( "" != $this->mInterwiki ) { return ""; }
445 $s = $this->getLocalURL( "action=edit" );
447 return $s;
450 # Get HTML-escaped displayable text
451 # For the title field in <a> tags
452 function getEscapedText()
454 return wfEscapeHTML( $this->getPrefixedText() );
457 # Is the title interwiki?
458 function isExternal() { return ( "" != $this->mInterwiki ); }
460 # Does the title correspond to a protected article?
461 function isProtected()
463 if ( -1 == $this->mNamespace ) { return true; }
464 $a = $this->getRestrictions();
465 if ( in_array( "sysop", $a ) ) { return true; }
466 return false;
469 # Is the page a log page, i.e. one where the history is messed up by
470 # LogPage.php? This used to be used for suppressing diff links in recent
471 # changes, but now that's done by setting a flag in the recentchanges
472 # table. Hence, this probably is no longer used.
473 function isLog()
475 if ( $this->mNamespace != Namespace::getWikipedia() ) {
476 return false;
478 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
479 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
480 return true;
482 return false;
485 # Is $wgUser is watching this page?
486 function userIsWatching()
488 global $wgUser;
490 if ( -1 == $this->mNamespace ) { return false; }
491 if ( 0 == $wgUser->getID() ) { return false; }
493 return $wgUser->isWatched( $this );
496 # Can $wgUser edit this page?
497 function userCanEdit()
499 global $wgUser;
501 if ( -1 == $this->mNamespace ) { return false; }
502 # if ( 0 == $this->getArticleID() ) { return false; }
503 if ( $this->mDbkeyform == "_" ) { return false; }
504 # protect css/js subpages of user pages
505 # XXX: this might be better using restrictions
506 if( Namespace::getUser() == $this->mNamespace
507 and preg_match("/\\.(css|js)$/", $this->mTextform )
508 and !$wgUser->isSysop()
509 and !preg_match("/^".$wgUser->getName()."/", $this->mTextform) )
510 { return false; }
512 $ur = $wgUser->getRights();
513 foreach ( $this->getRestrictions() as $r ) {
514 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
515 return false;
518 return true;
521 # Accessor/initialisation for mRestrictions
522 function getRestrictions()
524 $id = $this->getArticleID();
525 if ( 0 == $id ) { return array(); }
527 if ( ! $this->mRestrictionsLoaded ) {
528 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
529 $this->mRestrictions = explode( ",", trim( $res ) );
530 $this->mRestrictionsLoaded = true;
532 return $this->mRestrictions;
535 # Is there a version of this page in the deletion archive?
536 function isDeleted() {
537 $ns = $this->getNamespace();
538 $t = wfStrencode( $this->getDBkey() );
539 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
540 if( $res = wfQuery( $sql, DB_READ ) ) {
541 $s = wfFetchObject( $res );
542 return $s->n;
544 return 0;
547 # Get the article ID from the link cache
548 # Used very heavily, e.g. in Parser::replaceInternalLinks()
549 function getArticleID()
551 global $wgLinkCache;
553 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
554 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
555 return $this->mArticleID;
558 # This clears some fields in this object, and clears any associated keys in the
559 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
560 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
561 function resetArticleID( $newid )
563 global $wgLinkCache;
564 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
566 if ( 0 == $newid ) { $this->mArticleID = -1; }
567 else { $this->mArticleID = $newid; }
568 $this->mRestrictionsLoaded = false;
569 $this->mRestrictions = array();
572 # Updates cur_touched
573 # Called from LinksUpdate.php
574 function invalidateCache() {
575 $now = wfTimestampNow();
576 $ns = $this->getNamespace();
577 $ti = wfStrencode( $this->getDBkey() );
578 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
579 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
582 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
583 /* private */ function prefix( $name )
585 global $wgLang;
587 $p = "";
588 if ( "" != $this->mInterwiki ) {
589 $p = $this->mInterwiki . ":";
591 if ( 0 != $this->mNamespace ) {
592 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
594 return $p . $name;
597 # Secure and split - main initialisation function for this object
599 # Assumes that mDbkeyform has been set, and is urldecoded
600 # and uses undersocres, but not otherwise munged. This function
601 # removes illegal characters, splits off the winterwiki and
602 # namespace prefixes, sets the other forms, and canonicalizes
603 # everything.
605 /* private */ function secureAndSplit()
607 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
608 $fname = "Title::secureAndSplit";
609 wfProfileIn( $fname );
611 static $imgpre = false;
612 static $rxTc = false;
614 # Initialisation
615 if ( $imgpre === false ) {
616 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
617 $rxTc = "/[^" . Title::legalChars() . "]/";
620 $this->mInterwiki = $this->mFragment = "";
621 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
623 # Clean up whitespace
625 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
626 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
628 if ( "" == $t ) {
629 wfProfileOut( $fname );
630 return false;
633 $this->mDbkeyform = $t;
634 $done = false;
636 # :Image: namespace
637 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
638 $t = substr( $t, 1 );
641 # Initial colon indicating main namespace
642 if ( ":" == $t{0} ) {
643 $r = substr( $t, 1 );
644 $this->mNamespace = NS_MAIN;
645 } else {
646 # Namespace or interwiki prefix
647 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
648 #$p = strtolower( $m[1] );
649 $p = $m[1];
650 $lowerNs = strtolower( $p );
651 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
652 # Canonical namespace
653 $t = $m[2];
654 $this->mNamespace = $ns;
655 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
656 # Ordinary namespace
657 $t = $m[2];
658 $this->mNamespace = $ns;
659 } elseif ( $this->getInterwikiLink( $p ) ) {
660 # Interwiki link
661 $t = $m[2];
662 $this->mInterwiki = $p;
664 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
665 $done = true;
666 } elseif($this->mInterwiki != $wgLocalInterwiki) {
667 $done = true;
671 $r = $t;
674 # Redundant interwiki prefix to the local wiki
675 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
676 $this->mInterwiki = "";
678 # We already know that some pages won't be in the database!
680 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
681 $this->mArticleID = 0;
683 $f = strstr( $r, "#" );
684 if ( false !== $f ) {
685 $this->mFragment = substr( $f, 1 );
686 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
689 # Reject illegal characters.
691 if( preg_match( $rxTc, $r ) ) {
692 return false;
695 # "." and ".." conflict with the directories of those names
696 if ( $r === "." || $r === ".." ) {
697 return false;
700 # Initial capital letter
701 if( $wgCapitalLinks && $this->mInterwiki == "") {
702 $t = $wgLang->ucfirst( $r );
705 # Fill fields
706 $this->mDbkeyform = $t;
707 $this->mUrlform = wfUrlencode( $t );
709 $this->mTextform = str_replace( "_", " ", $t );
711 wfProfileOut( $fname );
712 return true;
715 # Get a title object associated with the talk page of this article
716 function getTalkPage() {
717 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
720 # Get a title object associated with the subject page of this talk page
721 function getSubjectPage() {
722 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
725 # Get an array of Title objects linking to this title
726 # Also stores the IDs in the link cache
727 function getLinksTo() {
728 global $wgLinkCache;
729 $id = $this->getArticleID();
730 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
731 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
732 $retVal = array();
733 if ( wfNumRows( $res ) ) {
734 while ( $row = wfFetchObject( $res ) ) {
735 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
736 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
737 $retVal[] = $titleObj;
740 wfFreeResult( $res );
741 return $retVal;
744 # Get an array of Title objects linking to this non-existent title
745 # Also stores the IDs in the link cache
746 function getBrokenLinksTo() {
747 global $wgLinkCache;
748 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
749 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
750 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
751 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
752 $retVal = array();
753 if ( wfNumRows( $res ) ) {
754 while ( $row = wfFetchObject( $res ) ) {
755 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
756 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
757 $retVal[] = $titleObj;
760 wfFreeResult( $res );
761 return $retVal;
764 function getSquidURLs() {
765 return array(
766 $this->getInternalURL(),
767 $this->getInternalURL( "action=history" )
771 function moveNoAuth( &$nt ) {
772 return $this->moveTo( $nt, false );
775 # Move a title to a new location
776 # Returns true on success, message name on failure
777 # auth indicates whether wgUser's permissions should be checked
778 function moveTo( &$nt, $auth = true ) {
779 if( !$this or !$nt ) {
780 return "badtitletext";
783 $fname = "Title::move";
784 $oldid = $this->getArticleID();
785 $newid = $nt->getArticleID();
787 if ( strlen( $nt->getDBkey() ) < 1 ) {
788 return "articleexists";
790 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
791 ( "" == $this->getDBkey() ) ||
792 ( "" != $this->getInterwiki() ) ||
793 ( !$oldid ) ||
794 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
795 ( "" == $nt->getDBkey() ) ||
796 ( "" != $nt->getInterwiki() ) ) {
797 return "badarticleerror";
800 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
801 return "protectedpage";
804 # The move is allowed only if (1) the target doesn't exist, or
805 # (2) the target is a redirect to the source, and has no history
806 # (so we can undo bad moves right after they're done).
808 if ( 0 != $newid ) { # Target exists; check for validity
809 if ( ! $this->isValidMoveTarget( $nt ) ) {
810 return "articleexists";
812 $this->moveOverExistingRedirect( $nt );
813 } else { # Target didn't exist, do normal move.
814 $this->moveToNewTitle( $nt, $newid );
817 # Update watchlists
819 $oldnamespace = $this->getNamespace() & ~1;
820 $newnamespace = $nt->getNamespace() & ~1;
821 $oldtitle = $this->getDBkey();
822 $newtitle = $nt->getDBkey();
824 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
825 WatchedItem::duplicateEntries( $this, $nt );
828 # Update search engine
829 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
830 $u->doUpdate();
831 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
832 $u->doUpdate();
834 return true;
837 # Move page to title which is presently a redirect to the source page
839 /* private */ function moveOverExistingRedirect( &$nt )
841 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
842 $fname = "Title::moveOverExistingRedirect";
843 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
845 $now = wfTimestampNow();
846 $won = wfInvertTimestamp( $now );
847 $newid = $nt->getArticleID();
848 $oldid = $this->getArticleID();
850 # Change the name of the target page:
851 wfUpdateArray(
852 /* table */ 'cur',
853 /* SET */ array(
854 'cur_touched' => $now,
855 'cur_namespace' => $nt->getNamespace(),
856 'cur_title' => $nt->getDBkey()
858 /* WHERE */ array( 'cur_id' => $oldid ),
859 $fname
861 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
863 # Repurpose the old redirect. We don't save it to history since
864 # by definition if we've got here it's rather uninteresting.
866 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
867 wfUpdateArray(
868 /* table */ 'cur',
869 /* SET */ array(
870 'cur_touched' => $now,
871 'cur_timestamp' => $now,
872 'inverse_timestamp' => $won,
873 'cur_namespace' => $this->getNamespace(),
874 'cur_title' => $this->getDBkey(),
875 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
876 'cur_comment' => $comment,
877 'cur_user' => $wgUser->getID(),
878 'cur_minor_edit' => 0,
879 'cur_counter' => 0,
880 'cur_restrictions' => '',
881 'cur_user_text' => $wgUser->getName(),
882 'cur_is_redirect' => 1,
883 'cur_is_new' => 1
885 /* WHERE */ array( 'cur_id' => $newid ),
886 $fname
889 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
891 # Fix the redundant names for the past revisions of the target page.
892 # The redirect should have no old revisions.
893 wfUpdateArray(
894 /* table */ 'old',
895 /* SET */ array(
896 'old_namespace' => $nt->getNamespace(),
897 'old_title' => $nt->getDBkey(),
899 /* WHERE */ array(
900 'old_namespace' => $this->getNamespace(),
901 'old_title' => $this->getDBkey(),
903 $fname
906 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
908 # Swap links
910 # Load titles and IDs
911 $linksToOld = $this->getLinksTo();
912 $linksToNew = $nt->getLinksTo();
914 # Make function to convert Titles to IDs
915 $titleToID = create_function('$t', 'return $t->getArticleID();');
917 # Reassign links to old title
918 if ( count( $linksToOld ) ) {
919 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
920 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
921 $sql .= ")";
922 wfQuery( $sql, DB_WRITE, $fname );
925 # Reassign links to new title
926 if ( count( $linksToNew ) ) {
927 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
928 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
929 $sql .= ")";
930 wfQuery( $sql, DB_WRITE, $fname );
933 # Note: the insert below must be after the updates above!
935 # Now, we record the link from the redirect to the new title.
936 # It should have no other outgoing links...
937 $sql = "DELETE FROM links WHERE l_from={$newid}";
938 wfQuery( $sql, DB_WRITE, $fname );
939 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
940 wfQuery( $sql, DB_WRITE, $fname );
942 # Purge squid
943 if ( $wgUseSquid ) {
944 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
945 $u = new SquidUpdate( $urls );
946 $u->doUpdate();
950 # Move page to non-existing title.
951 # Sets $newid to be the new article ID
953 /* private */ function moveToNewTitle( &$nt, &$newid )
955 global $wgUser, $wgLinkCache, $wgUseSquid;
956 $fname = "MovePageForm::moveToNewTitle";
957 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
959 $now = wfTimestampNow();
960 $won = wfInvertTimestamp( $now );
961 $newid = $nt->getArticleID();
962 $oldid = $this->getArticleID();
964 # Rename cur entry
965 wfUpdateArray(
966 /* table */ 'cur',
967 /* SET */ array(
968 'cur_touched' => $now,
969 'cur_namespace' => $nt->getNamespace(),
970 'cur_title' => $nt->getDBkey()
972 /* WHERE */ array( 'cur_id' => $oldid ),
973 $fname
976 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
978 # Insert redirct
979 wfInsertArray( 'cur', array(
980 'cur_namespace' => $this->getNamespace(),
981 'cur_title' => $this->getDBkey(),
982 'cur_comment' => $comment,
983 'cur_user' => $wgUser->getID(),
984 'cur_user_text' => $wgUser->getName(),
985 'cur_timestamp' => $now,
986 'inverse_timestamp' => $won,
987 'cur_touched' => $now,
988 'cur_is_redirect' => 1,
989 'cur_is_new' => 1,
990 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
992 $newid = wfInsertId();
993 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
995 # Rename old entries
996 wfUpdateArray(
997 /* table */ 'old',
998 /* SET */ array(
999 'old_namespace' => $nt->getNamespace(),
1000 'old_title' => $nt->getDBkey()
1002 /* WHERE */ array(
1003 'old_namespace' => $this->getNamespace(),
1004 'old_title' => $this->getDBkey()
1005 ), $fname
1008 # Miscellaneous updates
1010 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
1011 Article::onArticleCreate( $nt );
1013 # Any text links to the old title must be reassigned to the redirect
1014 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1015 wfQuery( $sql, DB_WRITE, $fname );
1017 # Record the just-created redirect's linking to the page
1018 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1019 wfQuery( $sql, DB_WRITE, $fname );
1021 # Non-existent target may have had broken links to it; these must
1022 # now be removed and made into good links.
1023 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1024 $update->fixBrokenLinks();
1026 # Purge old title from squid
1027 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1028 $titles = $nt->getLinksTo();
1029 if ( $wgUseSquid ) {
1030 $urls = $this->getSquidURLs();
1031 foreach ( $titles as $linkTitle ) {
1032 $urls[] = $linkTitle->getInternalURL();
1034 $u = new SquidUpdate( $urls );
1035 $u->doUpdate();
1039 # Checks if $this can be moved to $nt
1040 # Both titles must exist in the database, otherwise it will blow up
1041 function isValidMoveTarget( $nt )
1043 $fname = "Title::isValidMoveTarget";
1045 # Is it a redirect?
1046 $id = $nt->getArticleID();
1047 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1048 "WHERE cur_id={$id}";
1049 $res = wfQuery( $sql, DB_READ, $fname );
1050 $obj = wfFetchObject( $res );
1052 if ( 0 == $obj->cur_is_redirect ) {
1053 # Not a redirect
1054 return false;
1057 # Does the redirect point to the source?
1058 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1059 $redirTitle = Title::newFromText( $m[1] );
1060 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1061 return false;
1065 # Does the article have a history?
1066 $row = wfGetArray( 'old', array( 'old_id' ), array(
1067 'old_namespace' => $nt->getNamespace(),
1068 'old_title' => $nt->getDBkey() )
1071 # Return true if there was no history
1072 return $row === false;
1075 # Create a redirect, fails if the title already exists, does not notify RC
1076 # Returns success
1077 function createRedirect( $dest, $comment ) {
1078 global $wgUser;
1079 if ( $this->getArticleID() ) {
1080 return false;
1083 $now = wfTimestampNow();
1084 $won = wfInvertTimestamp( $now );
1086 wfInsertArray( 'cur', array(
1087 'cur_namespace' => $this->getNamespace(),
1088 'cur_title' => $this->getDBkey(),
1089 'cur_comment' => $comment,
1090 'cur_user' => $wgUser->getID(),
1091 'cur_user_text' => $wgUser->getName(),
1092 'cur_timestamp' => $now,
1093 'inverse_timestamp' => $won,
1094 'cur_touched' => $now,
1095 'cur_is_redirect' => 1,
1096 'cur_is_new' => 1,
1097 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1099 $newid = wfInsertId();
1100 $this->resetArticleID( $newid );
1102 # Link table
1103 if ( $dest->getArticleID() ) {
1104 wfInsertArray( 'links', array(
1105 'l_to' => $dest->getArticleID(),
1106 'l_from' => $newid
1108 } else {
1109 wfInsertArray( 'brokenlinks', array(
1110 'bl_to' => $dest->getPrefixedDBkey(),
1111 'bl_from' => $newid
1115 Article::onArticleCreate( $this );
1116 return true;