18bec83643dd78ed9d59df6a842ffa7090363f18
[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
613 if ( "" == $t ) {
614 wfProfileOut( $fname );
615 return false;
616 }
617
618 $this->mDbkeyform = $t;
619 $done = false;
620
621 # :Image: namespace
622 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
623 $t = substr( $t, 1 );
624 }
625
626 # Initial colon indicating main namespace
627 if ( ":" == $t{0} ) {
628 $r = substr( $t, 1 );
629 $this->mNamespace = NS_MAIN;
630 } else {
631 # Namespace or interwiki prefix
632 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
633 #$p = strtolower( $m[1] );
634 $p = $m[1];
635 $lowerNs = strtolower( $p );
636 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
637 # Canonical namespace
638 $t = $m[2];
639 $this->mNamespace = $ns;
640 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
641 # Ordinary namespace
642 $t = $m[2];
643 $this->mNamespace = $ns;
644 } elseif ( $this->getInterwikiLink( $p ) ) {
645 # Interwiki link
646 $t = $m[2];
647 $this->mInterwiki = $p;
648
649 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
650 $done = true;
651 } elseif($this->mInterwiki != $wgLocalInterwiki) {
652 $done = true;
653 }
654 }
655 }
656 $r = $t;
657 }
658
659 # Redundant interwiki prefix to the local wiki
660 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
661 $this->mInterwiki = "";
662 }
663 # We already know that some pages won't be in the database!
664 #
665 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
666 $this->mArticleID = 0;
667 }
668 $f = strstr( $r, "#" );
669 if ( false !== $f ) {
670 $this->mFragment = substr( $f, 1 );
671 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
672 }
673
674 # Reject illegal characters.
675 #
676 if( preg_match( $rxTc, $r ) ) {
677 return false;
678 }
679
680 # "." and ".." conflict with the directories of those names
681 if ( $r === "." || $r === ".." ) {
682 return false;
683 }
684
685 # Initial capital letter
686 if( $wgCapitalLinks && $this->mInterwiki == "") {
687 $t = $wgLang->ucfirst( $r );
688 }
689
690 # Fill fields
691 $this->mDbkeyform = $t;
692 $this->mUrlform = wfUrlencode( $t );
693
694 $this->mTextform = str_replace( "_", " ", $t );
695
696 wfProfileOut( $fname );
697 return true;
698 }
699
700 # Get a title object associated with the talk page of this article
701 function getTalkPage() {
702 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
703 }
704
705 # Get a title object associated with the subject page of this talk page
706 function getSubjectPage() {
707 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
708 }
709
710 # Get an array of Title objects linking to this title
711 # Also stores the IDs in the link cache
712 function getLinksTo() {
713 global $wgLinkCache;
714 $id = $this->getArticleID();
715 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
716 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
717 $retVal = array();
718 if ( wfNumRows( $res ) ) {
719 while ( $row = wfFetchObject( $res ) ) {
720 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
721 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
722 $retVal[] = $titleObj;
723 }
724 }
725 wfFreeResult( $res );
726 return $retVal;
727 }
728
729 # Get an array of Title objects linking to this non-existent title
730 # Also stores the IDs in the link cache
731 function getBrokenLinksTo() {
732 global $wgLinkCache;
733 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
734 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
735 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
736 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
737 $retVal = array();
738 if ( wfNumRows( $res ) ) {
739 while ( $row = wfFetchObject( $res ) ) {
740 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
741 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
742 $retVal[] = $titleObj;
743 }
744 }
745 wfFreeResult( $res );
746 return $retVal;
747 }
748
749 function getSquidURLs() {
750 return array(
751 $this->getInternalURL(),
752 $this->getInternalURL( "action=history" )
753 );
754 }
755
756 function moveNoAuth( &$nt ) {
757 return $this->moveTo( $nt, false );
758 }
759
760 # Move a title to a new location
761 # Returns true on success, message name on failure
762 # auth indicates whether wgUser's permissions should be checked
763 function moveTo( &$nt, $auth = true ) {
764 $fname = "Title::move";
765 $oldid = $this->getArticleID();
766 $newid = $nt->getArticleID();
767
768 if( !$this or !$nt ) {
769 return "badtitletext";
770 }
771
772 if ( strlen( $nt->getDBkey() ) < 1 ) {
773 return "articleexists";
774 }
775 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
776 ( "" == $this->getDBkey() ) ||
777 ( "" != $this->getInterwiki() ) ||
778 ( !$oldid ) ||
779 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
780 ( "" == $nt->getDBkey() ) ||
781 ( "" != $nt->getInterwiki() ) ) {
782 return "badarticleerror";
783 }
784
785 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
786 return "protectedpage";
787 }
788
789 # The move is allowed only if (1) the target doesn't exist, or
790 # (2) the target is a redirect to the source, and has no history
791 # (so we can undo bad moves right after they're done).
792
793 if ( 0 != $newid ) { # Target exists; check for validity
794 if ( ! $this->isValidMoveTarget( $nt ) ) {
795 return "articleexists";
796 }
797 $this->moveOverExistingRedirect( $nt );
798 } else { # Target didn't exist, do normal move.
799 $this->moveToNewTitle( $nt, $newid );
800 }
801
802 # Update watchlists
803
804 $oldnamespace = $this->getNamespace() & ~1;
805 $newnamespace = $nt->getNamespace() & ~1;
806 $oldtitle = $this->getDBkey();
807 $newtitle = $nt->getDBkey();
808
809 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
810 WatchedItem::duplicateEntries( $this, $nt );
811 }
812
813 # Update search engine
814 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
815 $u->doUpdate();
816 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
817 $u->doUpdate();
818
819 return true;
820 }
821
822 # Move page to title which is presently a redirect to the source page
823
824 /* private */ function moveOverExistingRedirect( &$nt )
825 {
826 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
827 $fname = "Title::moveOverExistingRedirect";
828 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
829
830 $now = wfTimestampNow();
831 $won = wfInvertTimestamp( $now );
832 $newid = $nt->getArticleID();
833 $oldid = $this->getArticleID();
834
835 # Change the name of the target page:
836 wfUpdateArray(
837 /* table */ 'cur',
838 /* SET */ array(
839 'cur_touched' => $now,
840 'cur_namespace' => $nt->getNamespace(),
841 'cur_title' => $nt->getDBkey()
842 ),
843 /* WHERE */ array( 'cur_id' => $oldid ),
844 $fname
845 );
846 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
847
848 # Repurpose the old redirect. We don't save it to history since
849 # by definition if we've got here it's rather uninteresting.
850
851 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
852 wfUpdateArray(
853 /* table */ 'cur',
854 /* SET */ array(
855 'cur_touched' => $now,
856 'cur_timestamp' => $now,
857 'inverse_timestamp' => $won,
858 'cur_namespace' => $this->getNamespace(),
859 'cur_title' => $this->getDBkey(),
860 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
861 'cur_comment' => $comment,
862 'cur_user' => $wgUser->getID(),
863 'cur_minor_edit' => 0,
864 'cur_counter' => 0,
865 'cur_restrictions' => '',
866 'cur_user_text' => $wgUser->getName(),
867 'cur_is_redirect' => 1,
868 'cur_is_new' => 1
869 ),
870 /* WHERE */ array( 'cur_id' => $newid ),
871 $fname
872 );
873
874 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
875
876 # Fix the redundant names for the past revisions of the target page.
877 # The redirect should have no old revisions.
878 wfUpdateArray(
879 /* table */ 'old',
880 /* SET */ array(
881 'old_namespace' => $nt->getNamespace(),
882 'old_title' => $nt->getDBkey(),
883 ),
884 /* WHERE */ array(
885 'old_namespace' => $this->getNamespace(),
886 'old_title' => $this->getDBkey(),
887 ),
888 $fname
889 );
890
891 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
892
893 # Swap links
894
895 # Load titles and IDs
896 $linksToOld = $this->getLinksTo();
897 $linksToNew = $nt->getLinksTo();
898
899 # Make function to convert Titles to IDs
900 $titleToID = create_function('$t', 'return $t->getArticleID();');
901
902 # Reassign links to old title
903 if ( count( $linksToOld ) ) {
904 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
905 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
906 $sql .= ")";
907 wfQuery( $sql, DB_WRITE, $fname );
908 }
909
910 # Reassign links to new title
911 if ( count( $linksToNew ) ) {
912 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
913 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
914 $sql .= ")";
915 wfQuery( $sql, DB_WRITE, $fname );
916 }
917
918 # Note: the insert below must be after the updates above!
919
920 # Now, we record the link from the redirect to the new title.
921 # It should have no other outgoing links...
922 $sql = "DELETE FROM links WHERE l_from={$newid}";
923 wfQuery( $sql, DB_WRITE, $fname );
924 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
925 wfQuery( $sql, DB_WRITE, $fname );
926
927 # Purge squid
928 if ( $wgUseSquid ) {
929 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
930 $u = new SquidUpdate( $urls );
931 $u->doUpdate();
932 }
933 }
934
935 # Move page to non-existing title.
936 # Sets $newid to be the new article ID
937
938 /* private */ function moveToNewTitle( &$nt, &$newid )
939 {
940 global $wgUser, $wgLinkCache, $wgUseSquid;
941 $fname = "MovePageForm::moveToNewTitle";
942 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
943
944 $now = wfTimestampNow();
945 $won = wfInvertTimestamp( $now );
946 $newid = $nt->getArticleID();
947 $oldid = $this->getArticleID();
948
949 # Rename cur entry
950 wfUpdateArray(
951 /* table */ 'cur',
952 /* SET */ array(
953 'cur_touched' => $now,
954 'cur_namespace' => $nt->getNamespace(),
955 'cur_title' => $nt->getDBkey()
956 ),
957 /* WHERE */ array( 'cur_id' => $oldid ),
958 $fname
959 );
960
961 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
962
963 # Insert redirct
964 wfInsertArray( 'cur', array(
965 'cur_namespace' => $this->getNamespace(),
966 'cur_title' => $this->getDBkey(),
967 'cur_comment' => $comment,
968 'cur_user' => $wgUser->getID(),
969 'cur_user_text' => $wgUser->getName(),
970 'cur_timestamp' => $now,
971 'inverse_timestamp' => $won,
972 'cur_touched' => $now,
973 'cur_is_redirect' => 1,
974 'cur_is_new' => 1,
975 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
976 );
977 $newid = wfInsertId();
978 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
979
980 # Rename old entries
981 wfUpdateArray(
982 /* table */ 'old',
983 /* SET */ array(
984 'old_namespace' => $nt->getNamespace(),
985 'old_title' => $nt->getDBkey()
986 ),
987 /* WHERE */ array(
988 'old_namespace' => $this->getNamespace(),
989 'old_title' => $this->getDBkey()
990 ), $fname
991 );
992
993 # Miscellaneous updates
994
995 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
996 Article::onArticleCreate( $nt );
997
998 # Any text links to the old title must be reassigned to the redirect
999 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1000 wfQuery( $sql, DB_WRITE, $fname );
1001
1002 # Record the just-created redirect's linking to the page
1003 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1004 wfQuery( $sql, DB_WRITE, $fname );
1005
1006 # Non-existent target may have had broken links to it; these must
1007 # now be removed and made into good links.
1008 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1009 $update->fixBrokenLinks();
1010
1011 # Purge old title from squid
1012 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1013 $titles = $nt->getLinksTo();
1014 if ( $wgUseSquid ) {
1015 $urls = $this->getSquidURLs();
1016 foreach ( $titles as $linkTitle ) {
1017 $urls[] = $linkTitle->getInternalURL();
1018 }
1019 $u = new SquidUpdate( $urls );
1020 $u->doUpdate();
1021 }
1022 }
1023
1024 # Checks if $this can be moved to $nt
1025 # Both titles must exist in the database, otherwise it will blow up
1026 function isValidMoveTarget( $nt )
1027 {
1028 $fname = "Title::isValidMoveTarget";
1029
1030 # Is it a redirect?
1031 $id = $nt->getArticleID();
1032 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1033 "WHERE cur_id={$id}";
1034 $res = wfQuery( $sql, DB_READ, $fname );
1035 $obj = wfFetchObject( $res );
1036
1037 if ( 0 == $obj->cur_is_redirect ) {
1038 # Not a redirect
1039 return false;
1040 }
1041
1042 # Does the redirect point to the source?
1043 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1044 $redirTitle = Title::newFromText( $m[1] );
1045 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1046 return false;
1047 }
1048 }
1049
1050 # Does the article have a history?
1051 $row = wfGetArray( 'old', array( 'old_id' ), array(
1052 'old_namespace' => $nt->getNamespace(),
1053 'old_title' => $nt->getDBkey() )
1054 );
1055
1056 # Return true if there was no history
1057 return $row === false;
1058 }
1059
1060 # Create a redirect, fails if the title already exists, does not notify RC
1061 # Returns success
1062 function createRedirect( $dest, $comment ) {
1063 global $wgUser;
1064 if ( $this->getArticleID() ) {
1065 return false;
1066 }
1067
1068 $now = wfTimestampNow();
1069 $won = wfInvertTimestamp( $now );
1070
1071 wfInsertArray( 'cur', array(
1072 'cur_namespace' => $this->getNamespace(),
1073 'cur_title' => $this->getDBkey(),
1074 'cur_comment' => $comment,
1075 'cur_user' => $wgUser->getID(),
1076 'cur_user_text' => $wgUser->getName(),
1077 'cur_timestamp' => $now,
1078 'inverse_timestamp' => $won,
1079 'cur_touched' => $now,
1080 'cur_is_redirect' => 1,
1081 'cur_is_new' => 1,
1082 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1083 ));
1084 $newid = wfInsertId();
1085 $this->resetArticleID( $newid );
1086
1087 # Link table
1088 if ( $dest->getArticleID() ) {
1089 wfInsertArray( 'links', array(
1090 'l_to' => $dest->getArticleID(),
1091 'l_from' => $newid
1092 ));
1093 } else {
1094 wfInsertArray( 'brokenlinks', array(
1095 'bl_to' => $dest->getPrefixedDBkey(),
1096 'bl_from' => $newid
1097 ));
1098 }
1099
1100 Article::onArticleCreate( $this );
1101 return true;
1102 }
1103 }
1104 ?>