1) when autosummaries are mixed with human-written ones, insert separators
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 # See title.doc
3
4 /* private static */ $title_interwiki_cache = array();
5
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.
10 #
11 class Title {
12 # All member variables should be considered private
13 # Please use the accessor functions
14
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
28
29 #----------------------------------------------------------------------------
30 # Construction
31 #----------------------------------------------------------------------------
32
33 /* private */ function Title()
34 {
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;
42 }
43
44 # From a prefixed DB key
45 /* static */ function newFromDBkey( $key )
46 {
47 $t = new Title();
48 $t->mDbkeyform = $key;
49 if( $t->secureAndSplit() )
50 return $t;
51 else
52 return NULL;
53 }
54
55 # From text, such as what you would find in a link
56 /* static */ function newFromText( $text, $defaultNamespace = 0 )
57 {
58 static $trans;
59 $fname = "Title::newFromText";
60 wfProfileIn( $fname );
61
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 );
69 }
70 }
71
72 if( is_object( $text ) ) {
73 wfDebugDieBacktrace( "Called with object instead of string." );
74 }
75 $text = strtr( $text, $trans );
76
77 $text = wfMungeToUtf8( $text );
78
79
80 # What was this for? TS 2004-03-03
81 # $text = urldecode( $text );
82
83 $t = new Title();
84 $t->mDbkeyform = str_replace( " ", "_", $text );
85 $t->mDefaultNamespace = $defaultNamespace;
86
87 wfProfileOut( $fname );
88 if ( !is_object( $t ) ) {
89 var_dump( debug_backtrace() );
90 }
91 if( $t->secureAndSplit() ) {
92 return $t;
93 } else {
94 return NULL;
95 }
96 }
97
98 # From a URL-encoded title
99 /* static */ function newFromURL( $url )
100 {
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;
108
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 ) ) )
114 {
115 $s = $wgLang->checkTitleEncoding( $s );
116 } else {
117 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
118 }
119
120 $t->mDbkeyform = str_replace( " ", "_", $s );
121 if( $t->secureAndSplit() ) {
122
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 ));
126
127 preg_match( "/\((.*)\)/", $cur_title_object->Type, $cur_title_size);
128
129 if (strlen($t->mDbkeyform) > $cur_title_size[1] ) {
130 return NULL;
131 }
132
133 return $t;
134 } else {
135 return NULL;
136 }
137 }
138
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 )
143 {
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;
151 }
152 return $title;
153 }
154
155 # From a namespace index and a DB key
156 /* static */ function makeTitle( $ns, $title )
157 {
158 $t = new Title();
159 $t->mDbkeyform = Title::makeName( $ns, $title );
160 if( $t->secureAndSplit() ) {
161 return $t;
162 } else {
163 return NULL;
164 }
165 }
166
167 function newMainPage()
168 {
169 return Title::newFromText( wfMsg( "mainpage" ) );
170 }
171
172 #----------------------------------------------------------------------------
173 # Static functions
174 #----------------------------------------------------------------------------
175
176 # Get the prefixed DB key associated with an ID
177 /* static */ function nameOf( $id )
178 {
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; }
183
184 $s = wfFetchObject( $res );
185 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
186 return $n;
187 }
188
189 # Get a regex character class describing the legal characters in a link
190 /* static */ function legalChars()
191 {
192 # Missing characters:
193 # * []|# Needed for link syntax
194 # * % and + are corrupted by Apache when they appear in the path
195 #
196 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
197 # this breaks interlanguage links
198
199 $set = " !\"$&'()*,\\-.\\/0-9:;<=>?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
200 return $set;
201 }
202
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 )
206 {
207 global $wgDBminWordLen, $wgLang;
208
209 $lc = SearchEngine::legalSearchChars() . "&#;";
210 $t = $wgLang->stripForSearch( $title );
211 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
212 $t = strtolower( $t );
213
214 # Handle 's, s'
215 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
216 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
217
218 $t = preg_replace( "/\\s+/", " ", $t );
219
220 if ( $ns == Namespace::getImage() ) {
221 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
222 }
223 return trim( $t );
224 }
225
226 # Make a prefixed DB key from a DB key and a namespace index
227 /* static */ function makeName( $ns, $title )
228 {
229 global $wgLang;
230
231 $n = $wgLang->getNsText( $ns );
232 if ( "" == $n ) { return $title; }
233 else { return "{$n}:{$title}"; }
234 }
235
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 )
240 {
241 global $wgMemc, $wgDBname;
242 static $title_interwiki_cache = array();
243
244 $k = "$wgDBname:interwiki:$key";
245
246 if( array_key_exists( $k, $title_interwiki_cache ) )
247 return $title_interwiki_cache[$k]->iw_url;
248
249 $s = $wgMemc->get( $k );
250 if( $s ) {
251 $title_interwiki_cache[$k] = $s;
252 return $s->iw_url;
253 }
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 "";
258
259 $s = wfFetchObject( $res );
260 if(!$s) {
261 $s = (object)false;
262 $s->iw_url = "";
263 }
264 $wgMemc->set( $k, $s );
265 $title_interwiki_cache[$k] = $s;
266 return $s->iw_url;
267 }
268
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;
274 }
275 if ( $timestamp == "" ) {
276 $timestamp = wfTimestampNow();
277 }
278 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
279 $first = true;
280
281 foreach ( $titles as $title ) {
282 if ( ! $first ) {
283 $sql .= ",";
284 }
285
286 $first = false;
287 $sql .= $title->getArticleID();
288 }
289 $sql .= ")";
290 if ( ! $first ) {
291 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
292 }
293 }
294
295 #----------------------------------------------------------------------------
296 # Other stuff
297 #----------------------------------------------------------------------------
298
299 # Simple accessors
300 # See the definitions at the top of this file
301
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; }
310
311 # Get title for search index
312 function getIndexTitle()
313 {
314 return Title::indexTitle( $this->mNamespace, $this->mTextform );
315 }
316
317 # Get prefixed title with underscores
318 function getPrefixedDBkey()
319 {
320 $s = $this->prefix( $this->mDbkeyform );
321 $s = str_replace( " ", "_", $s );
322 return $s;
323 }
324
325 # Get prefixed title with spaces
326 # This is the form usually used for display
327 function getPrefixedText()
328 {
329 if ( empty( $this->mPrefixedText ) ) {
330 $s = $this->prefix( $this->mTextform );
331 $s = str_replace( "_", " ", $s );
332 $this->mPrefixedText = $s;
333 }
334 return $this->mPrefixedText;
335 }
336
337 # Get a URL-encoded title (not an actual URL) including interwiki
338 function getPrefixedURL()
339 {
340 $s = $this->prefix( $this->mDbkeyform );
341 $s = str_replace( " ", "_", $s );
342
343 $s = wfUrlencode ( $s ) ;
344
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 );
350
351 return $s;
352 }
353
354 # Get a real URL referring to this title, with interwiki link and fragment
355 function getFullURL( $query = "" )
356 {
357 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
358
359 if ( "" == $this->mInterwiki ) {
360 $p = $wgArticlePath;
361 return $wgServer . $this->getLocalUrl( $query );
362 }
363
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 );
370 }
371 return $u;
372 }
373
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
380
381 function getURL() {
382 die( "Call to obsolete obsolete function Title::getURL()" );
383 }
384
385 function getLocalURL( $query = "" )
386 {
387 global $wgLang, $wgArticlePath, $wgScript;
388
389 if ( $this->isExternal() ) {
390 return $this->getFullURL();
391 }
392
393 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
394 if ( $query == "" ) {
395 $url = str_replace( "$1", $dbkey, $wgArticlePath );
396 } else {
397 if ( $query == "-" ) {
398 $query = "";
399 }
400 if ( $wgScript != "" ) {
401 $url = "{$wgScript}?title={$dbkey}&{$query}";
402 } else {
403 # Top level wiki
404 $url = "/{$dbkey}?{$query}";
405 }
406 }
407 return $url;
408 }
409
410 function escapeLocalURL( $query = "" ) {
411 return wfEscapeHTML( $this->getLocalURL( $query ) );
412 }
413
414 function escapeFullURL( $query = "" ) {
415 return wfEscapeHTML( $this->getFullURL( $query ) );
416 }
417
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 );
423 }
424
425 # Get the edit URL, or a null string if it is an interwiki link
426 function getEditURL()
427 {
428 global $wgServer, $wgScript;
429
430 if ( "" != $this->mInterwiki ) { return ""; }
431 $s = $this->getLocalURL( "action=edit" );
432
433 return $s;
434 }
435
436 # Get HTML-escaped displayable text
437 # For the title field in <a> tags
438 function getEscapedText()
439 {
440 return wfEscapeHTML( $this->getPrefixedText() );
441 }
442
443 # Is the title interwiki?
444 function isExternal() { return ( "" != $this->mInterwiki ); }
445
446 # Does the title correspond to a protected article?
447 function isProtected()
448 {
449 if ( -1 == $this->mNamespace ) { return true; }
450 $a = $this->getRestrictions();
451 if ( in_array( "sysop", $a ) ) { return true; }
452 return false;
453 }
454
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()
460 {
461 if ( $this->mNamespace != Namespace::getWikipedia() ) {
462 return false;
463 }
464 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
465 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
466 return true;
467 }
468 return false;
469 }
470
471 # Is $wgUser is watching this page?
472 function userIsWatching()
473 {
474 global $wgUser;
475
476 if ( -1 == $this->mNamespace ) { return false; }
477 if ( 0 == $wgUser->getID() ) { return false; }
478
479 return $wgUser->isWatched( $this );
480 }
481
482 # Can $wgUser edit this page?
483 function userCanEdit()
484 {
485 global $wgUser;
486
487 if ( -1 == $this->mNamespace ) { return false; }
488 # if ( 0 == $this->getArticleID() ) { return false; }
489 if ( $this->mDbkeyform == "_" ) { return false; }
490
491 $ur = $wgUser->getRights();
492 foreach ( $this->getRestrictions() as $r ) {
493 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
494 return false;
495 }
496 }
497 return true;
498 }
499
500 # Accessor/initialisation for mRestrictions
501 function getRestrictions()
502 {
503 $id = $this->getArticleID();
504 if ( 0 == $id ) { return array(); }
505
506 if ( ! $this->mRestrictionsLoaded ) {
507 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
508 $this->mRestrictions = explode( ",", trim( $res ) );
509 $this->mRestrictionsLoaded = true;
510 }
511 return $this->mRestrictions;
512 }
513
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;
522 }
523 return 0;
524 }
525
526 # Get the article ID from the link cache
527 # Used very heavily, e.g. in Parser::replaceInternalLinks()
528 function getArticleID()
529 {
530 global $wgLinkCache;
531
532 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
533 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
534 return $this->mArticleID;
535 }
536
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 )
541 {
542 global $wgLinkCache;
543 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
544
545 if ( 0 == $newid ) { $this->mArticleID = -1; }
546 else { $this->mArticleID = $newid; }
547 $this->mRestrictionsLoaded = false;
548 $this->mRestrictions = array();
549 }
550
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" );
559 }
560
561 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
562 /* private */ function prefix( $name )
563 {
564 global $wgLang;
565
566 $p = "";
567 if ( "" != $this->mInterwiki ) {
568 $p = $this->mInterwiki . ":";
569 }
570 if ( 0 != $this->mNamespace ) {
571 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
572 }
573 return $p . $name;
574 }
575
576 # Secure and split - main initialisation function for this object
577 #
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.
583 #
584 /* private */ function secureAndSplit()
585 {
586 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
587 $fname = "Title::secureAndSplit";
588 wfProfileIn( $fname );
589
590 static $imgpre = false;
591 static $rxTc = false;
592
593 # Initialisation
594 if ( $imgpre === false ) {
595 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
596 $rxTc = "/[^" . Title::legalChars() . "]/";
597 }
598
599 $this->mInterwiki = $this->mFragment = "";
600 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
601
602 # Clean up whitespace
603 #
604 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
605 if ( "_" == @$t{0} ) {
606 $t = substr( $t, 1 );
607 }
608 $l = strlen( $t );
609 if ( $l && ( "_" == $t{$l-1} ) ) {
610 $t = substr( $t, 0, $l-1 );
611 }
612 if ( "" == $t ) {
613 wfProfileOut( $fname );
614 return false;
615 }
616
617 $this->mDbkeyform = $t;
618 $done = false;
619
620 # :Image: namespace
621 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
622 $t = substr( $t, 1 );
623 }
624
625 # Initial colon indicating main namespace
626 if ( ":" == $t{0} ) {
627 $r = substr( $t, 1 );
628 $this->mNamespace = NS_MAIN;
629 } else {
630 # Namespace or interwiki prefix
631 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
632 #$p = strtolower( $m[1] );
633 $p = $m[1];
634 $lowerNs = strtolower( $p );
635 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
636 # Canonical namespace
637 $t = $m[2];
638 $this->mNamespace = $ns;
639 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
640 # Ordinary namespace
641 $t = $m[2];
642 $this->mNamespace = $ns;
643 } elseif ( $this->getInterwikiLink( $p ) ) {
644 # Interwiki link
645 $t = $m[2];
646 $this->mInterwiki = $p;
647
648 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
649 $done = true;
650 } elseif($this->mInterwiki != $wgLocalInterwiki) {
651 $done = true;
652 }
653 }
654 }
655 $r = $t;
656 }
657
658 # Redundant interwiki prefix to the local wiki
659 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
660 $this->mInterwiki = "";
661 }
662 # We already know that some pages won't be in the database!
663 #
664 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
665 $this->mArticleID = 0;
666 }
667 $f = strstr( $r, "#" );
668 if ( false !== $f ) {
669 $this->mFragment = substr( $f, 1 );
670 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
671 }
672
673 # Reject illegal characters.
674 #
675 if( preg_match( $rxTc, $r ) ) {
676 return false;
677 }
678
679 # "." and ".." conflict with the directories of those names
680 if ( $r === "." || $r === ".." ) {
681 return false;
682 }
683
684 # Initial capital letter
685 if( $wgCapitalLinks && $this->mInterwiki == "") {
686 $t = $wgLang->ucfirst( $r );
687 }
688
689 # Fill fields
690 $this->mDbkeyform = $t;
691 $this->mUrlform = wfUrlencode( $t );
692
693 $this->mTextform = str_replace( "_", " ", $t );
694
695 wfProfileOut( $fname );
696 return true;
697 }
698
699 # Get a title object associated with the talk page of this article
700 function getTalkPage() {
701 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
702 }
703
704 # Get a title object associated with the subject page of this talk page
705 function getSubjectPage() {
706 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
707 }
708
709 # Get an array of Title objects linking to this title
710 # Also stores the IDs in the link cache
711 function getLinksTo() {
712 global $wgLinkCache;
713 $id = $this->getArticleID();
714 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
715 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
716 $retVal = array();
717 if ( wfNumRows( $res ) ) {
718 while ( $row = wfFetchObject( $res ) ) {
719 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
720 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
721 $retVal[] = $titleObj;
722 }
723 }
724 wfFreeResult( $res );
725 return $retVal;
726 }
727
728 # Get an array of Title objects linking to this non-existent title
729 # Also stores the IDs in the link cache
730 function getBrokenLinksTo() {
731 global $wgLinkCache;
732 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
733 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
734 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
735 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
736 $retVal = array();
737 if ( wfNumRows( $res ) ) {
738 while ( $row = wfFetchObject( $res ) ) {
739 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
740 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
741 $retVal[] = $titleObj;
742 }
743 }
744 wfFreeResult( $res );
745 return $retVal;
746 }
747
748 function getSquidURLs() {
749 return array(
750 $this->getInternalURL(),
751 $this->getInternalURL( "action=history" )
752 );
753 }
754
755 function moveNoAuth( &$nt ) {
756 return $this->moveTo( $nt, false );
757 }
758
759 # Move a title to a new location
760 # Returns true on success, message name on failure
761 # auth indicates whether wgUser's permissions should be checked
762 function moveTo( &$nt, $auth = true ) {
763 $fname = "Title::move";
764 $oldid = $this->getArticleID();
765 $newid = $nt->getArticleID();
766
767 if( !$this or !$nt ) {
768 return "badtitletext";
769 }
770
771 if ( strlen( $nt->getDBkey() ) < 1 ) {
772 return "articleexists";
773 }
774 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
775 ( "" == $this->getDBkey() ) ||
776 ( "" != $this->getInterwiki() ) ||
777 ( !$oldid ) ||
778 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
779 ( "" == $nt->getDBkey() ) ||
780 ( "" != $nt->getInterwiki() ) ) {
781 return "badarticleerror";
782 }
783
784 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
785 return "protectedpage";
786 }
787
788 # The move is allowed only if (1) the target doesn't exist, or
789 # (2) the target is a redirect to the source, and has no history
790 # (so we can undo bad moves right after they're done).
791
792 if ( 0 != $newid ) { # Target exists; check for validity
793 if ( ! $this->isValidMoveTarget( $nt ) ) {
794 return "articleexists";
795 }
796 $this->moveOverExistingRedirect( $nt );
797 } else { # Target didn't exist, do normal move.
798 $this->moveToNewTitle( $nt, $newid );
799 }
800
801 # Update watchlists
802
803 $oldnamespace = $this->getNamespace() & ~1;
804 $newnamespace = $nt->getNamespace() & ~1;
805 $oldtitle = $this->getDBkey();
806 $newtitle = $nt->getDBkey();
807
808 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
809 WatchedItem::duplicateEntries( $this, $nt );
810 }
811
812 # Update search engine
813 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
814 $u->doUpdate();
815 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
816 $u->doUpdate();
817
818 return true;
819 }
820
821 # Move page to title which is presently a redirect to the source page
822
823 /* private */ function moveOverExistingRedirect( &$nt )
824 {
825 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
826 $fname = "Title::moveOverExistingRedirect";
827 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
828
829 $now = wfTimestampNow();
830 $won = wfInvertTimestamp( $now );
831 $newid = $nt->getArticleID();
832 $oldid = $this->getArticleID();
833
834 # Change the name of the target page:
835 wfUpdateArray(
836 /* table */ 'cur',
837 /* SET */ array(
838 'cur_touched' => $now,
839 'cur_namespace' => $nt->getNamespace(),
840 'cur_title' => $nt->getDBkey()
841 ),
842 /* WHERE */ array( 'cur_id' => $oldid ),
843 $fname
844 );
845 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
846
847 # Repurpose the old redirect. We don't save it to history since
848 # by definition if we've got here it's rather uninteresting.
849
850 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
851 wfUpdateArray(
852 /* table */ 'cur',
853 /* SET */ array(
854 'cur_touched' => $now,
855 'cur_timestamp' => $now,
856 'inverse_timestamp' => $won,
857 'cur_namespace' => $this->getNamespace(),
858 'cur_title' => $this->getDBkey(),
859 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
860 'cur_comment' => $comment,
861 'cur_user' => $wgUser->getID(),
862 'cur_minor_edit' => 0,
863 'cur_counter' => 0,
864 'cur_restrictions' => '',
865 'cur_user_text' => $wgUser->getName(),
866 'cur_is_redirect' => 1,
867 'cur_is_new' => 1
868 ),
869 /* WHERE */ array( 'cur_id' => $newid ),
870 $fname
871 );
872
873 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
874
875 # Fix the redundant names for the past revisions of the target page.
876 # The redirect should have no old revisions.
877 wfUpdateArray(
878 /* table */ 'old',
879 /* SET */ array(
880 'old_namespace' => $nt->getNamespace(),
881 'old_title' => $nt->getDBkey(),
882 ),
883 /* WHERE */ array(
884 'old_namespace' => $this->getNamespace(),
885 'old_title' => $this->getDBkey(),
886 ),
887 $fname
888 );
889
890 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
891
892 # Swap links
893
894 # Load titles and IDs
895 $linksToOld = $this->getLinksTo();
896 $linksToNew = $nt->getLinksTo();
897
898 # Make function to convert Titles to IDs
899 $titleToID = create_function('$t', 'return $t->getArticleID();');
900
901 # Reassign links to old title
902 if ( count( $linksToOld ) ) {
903 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
904 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
905 $sql .= ")";
906 wfQuery( $sql, DB_WRITE, $fname );
907 }
908
909 # Reassign links to new title
910 if ( count( $linksToNew ) ) {
911 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
912 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
913 $sql .= ")";
914 wfQuery( $sql, DB_WRITE, $fname );
915 }
916
917 # Note: the insert below must be after the updates above!
918
919 # Now, we record the link from the redirect to the new title.
920 # It should have no other outgoing links...
921 $sql = "DELETE FROM links WHERE l_from={$newid}";
922 wfQuery( $sql, DB_WRITE, $fname );
923 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
924 wfQuery( $sql, DB_WRITE, $fname );
925
926 # Purge squid
927 if ( $wgUseSquid ) {
928 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
929 $u = new SquidUpdate( $urls );
930 $u->doUpdate();
931 }
932 }
933
934 # Move page to non-existing title.
935 # Sets $newid to be the new article ID
936
937 /* private */ function moveToNewTitle( &$nt, &$newid )
938 {
939 global $wgUser, $wgLinkCache, $wgUseSquid;
940 $fname = "MovePageForm::moveToNewTitle";
941 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
942
943 $now = wfTimestampNow();
944 $won = wfInvertTimestamp( $now );
945 $newid = $nt->getArticleID();
946 $oldid = $this->getArticleID();
947
948 # Rename cur entry
949 wfUpdateArray(
950 /* table */ 'cur',
951 /* SET */ array(
952 'cur_touched' => $now,
953 'cur_namespace' => $nt->getNamespace(),
954 'cur_title' => $nt->getDBkey()
955 ),
956 /* WHERE */ array( 'cur_id' => $oldid ),
957 $fname
958 );
959
960 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
961
962 # Insert redirct
963 wfInsertArray( 'cur', array(
964 'cur_namespace' => $this->getNamespace(),
965 'cur_title' => $this->getDBkey(),
966 'cur_comment' => $comment,
967 'cur_user' => $wgUser->getID(),
968 'cur_user_text' => $wgUser->getName(),
969 'cur_timestamp' => $now,
970 'inverse_timestamp' => $won,
971 'cur_touched' => $now,
972 'cur_is_redirect' => 1,
973 'cur_is_new' => 1,
974 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
975 );
976 $newid = wfInsertId();
977 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
978
979 # Rename old entries
980 wfUpdateArray(
981 /* table */ 'old',
982 /* SET */ array(
983 'old_namespace' => $nt->getNamespace(),
984 'old_title' => $nt->getDBkey()
985 ),
986 /* WHERE */ array(
987 'old_namespace' => $this->getNamespace(),
988 'old_title' => $this->getDBkey()
989 ), $fname
990 );
991
992 # Miscellaneous updates
993
994 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
995 Article::onArticleCreate( $nt );
996
997 # Any text links to the old title must be reassigned to the redirect
998 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
999 wfQuery( $sql, DB_WRITE, $fname );
1000
1001 # Record the just-created redirect's linking to the page
1002 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1003 wfQuery( $sql, DB_WRITE, $fname );
1004
1005 # Non-existent target may have had broken links to it; these must
1006 # now be removed and made into good links.
1007 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1008 $update->fixBrokenLinks();
1009
1010 # Purge old title from squid
1011 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1012 $titles = $nt->getLinksTo();
1013 if ( $wgUseSquid ) {
1014 $urls = $this->getSquidURLs();
1015 foreach ( $titles as $linkTitle ) {
1016 $urls[] = $linkTitle->getInternalURL();
1017 }
1018 $u = new SquidUpdate( $urls );
1019 $u->doUpdate();
1020 }
1021 }
1022
1023 # Checks if $this can be moved to $nt
1024 # Both titles must exist in the database, otherwise it will blow up
1025 function isValidMoveTarget( $nt )
1026 {
1027 $fname = "Title::isValidMoveTarget";
1028
1029 # Is it a redirect?
1030 $id = $nt->getArticleID();
1031 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1032 "WHERE cur_id={$id}";
1033 $res = wfQuery( $sql, DB_READ, $fname );
1034 $obj = wfFetchObject( $res );
1035
1036 if ( 0 == $obj->cur_is_redirect ) {
1037 # Not a redirect
1038 return false;
1039 }
1040
1041 # Does the redirect point to the source?
1042 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1043 $redirTitle = Title::newFromText( $m[1] );
1044 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1045 return false;
1046 }
1047 }
1048
1049 # Does the article have a history?
1050 $row = wfGetArray( 'old', array( 'old_id' ), array(
1051 'old_namespace' => $nt->getNamespace(),
1052 'old_title' => $nt->getDBkey() )
1053 );
1054
1055 # Return true if there was no history
1056 return $row === false;
1057 }
1058
1059 # Create a redirect, fails if the title already exists, does not notify RC
1060 # Returns success
1061 function createRedirect( $dest, $comment ) {
1062 global $wgUser;
1063 if ( $this->getArticleID() ) {
1064 return false;
1065 }
1066
1067 $now = wfTimestampNow();
1068 $won = wfInvertTimestamp( $now );
1069
1070 wfInsertArray( 'cur', array(
1071 'cur_namespace' => $this->getNamespace(),
1072 'cur_title' => $this->getDBkey(),
1073 'cur_comment' => $comment,
1074 'cur_user' => $wgUser->getID(),
1075 'cur_user_text' => $wgUser->getName(),
1076 'cur_timestamp' => $now,
1077 'inverse_timestamp' => $won,
1078 'cur_touched' => $now,
1079 'cur_is_redirect' => 1,
1080 'cur_is_new' => 1,
1081 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1082 ));
1083 $newid = wfInsertId();
1084 $this->resetArticleID( $newid );
1085
1086 # Link table
1087 if ( $dest->getArticleID() ) {
1088 wfInsertArray( 'links', array(
1089 'l_to' => $dest->getArticleID(),
1090 'l_from' => $newid
1091 ));
1092 } else {
1093 wfInsertArray( 'brokenlinks', array(
1094 'bl_to' => $dest->getPrefixedDBkey(),
1095 'bl_from' => $newid
1096 ));
1097 }
1098
1099 Article::onArticleCreate( $this );
1100 return true;
1101 }
1102 }
1103 ?>