Interwiki redirects using prefixes in the URL
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 # See title.doc
3
4 $wgTitleInterwikiCache = 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, $wgInterwikiExpiry;
242 static $wgTitleInterwikiCache = array();
243
244 $k = "$wgDBname:interwiki:$key";
245
246 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
247 return $wgTitleInterwikiCache[$k]->iw_url;
248
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;
254 }
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 "";
259
260 $s = wfFetchObject( $res );
261 if(!$s) {
262 $s = (object)false;
263 $s->iw_url = "";
264 }
265 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
266 $wgTitleInterwikiCache[$k] = $s;
267 return $s->iw_url;
268 }
269
270 function isLocal() {
271 global $wgTitleInterwikiCache, $wgDBname;
272
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;
280 }
281 }
282
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;
288 }
289 if ( $timestamp == "" ) {
290 $timestamp = wfTimestampNow();
291 }
292 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
293 $first = true;
294
295 foreach ( $titles as $title ) {
296 if ( ! $first ) {
297 $sql .= ",";
298 }
299
300 $first = false;
301 $sql .= $title->getArticleID();
302 }
303 $sql .= ")";
304 if ( ! $first ) {
305 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
306 }
307 }
308
309 #----------------------------------------------------------------------------
310 # Other stuff
311 #----------------------------------------------------------------------------
312
313 # Simple accessors
314 # See the definitions at the top of this file
315
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; }
324
325 # Get title for search index
326 function getIndexTitle()
327 {
328 return Title::indexTitle( $this->mNamespace, $this->mTextform );
329 }
330
331 # Get prefixed title with underscores
332 function getPrefixedDBkey()
333 {
334 $s = $this->prefix( $this->mDbkeyform );
335 $s = str_replace( " ", "_", $s );
336 return $s;
337 }
338
339 # Get prefixed title with spaces
340 # This is the form usually used for display
341 function getPrefixedText()
342 {
343 if ( empty( $this->mPrefixedText ) ) {
344 $s = $this->prefix( $this->mTextform );
345 $s = str_replace( "_", " ", $s );
346 $this->mPrefixedText = $s;
347 }
348 return $this->mPrefixedText;
349 }
350
351 # Get a URL-encoded title (not an actual URL) including interwiki
352 function getPrefixedURL()
353 {
354 $s = $this->prefix( $this->mDbkeyform );
355 $s = str_replace( " ", "_", $s );
356
357 $s = wfUrlencode ( $s ) ;
358
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 );
364
365 return $s;
366 }
367
368 # Get a real URL referring to this title, with interwiki link and fragment
369 function getFullURL( $query = "" )
370 {
371 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
372
373 if ( "" == $this->mInterwiki ) {
374 $p = $wgArticlePath;
375 return $wgServer . $this->getLocalUrl( $query );
376 }
377
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 );
384 }
385 return $u;
386 }
387
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
394
395 function getURL() {
396 die( "Call to obsolete obsolete function Title::getURL()" );
397 }
398
399 function getLocalURL( $query = "" )
400 {
401 global $wgLang, $wgArticlePath, $wgScript;
402
403 if ( $this->isExternal() ) {
404 return $this->getFullURL();
405 }
406
407 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
408 if ( $query == "" ) {
409 $url = str_replace( "$1", $dbkey, $wgArticlePath );
410 } else {
411 if ( $query == "-" ) {
412 $query = "";
413 }
414 if ( $wgScript != "" ) {
415 $url = "{$wgScript}?title={$dbkey}&{$query}";
416 } else {
417 # Top level wiki
418 $url = "/{$dbkey}?{$query}";
419 }
420 }
421 return $url;
422 }
423
424 function escapeLocalURL( $query = "" ) {
425 return wfEscapeHTML( $this->getLocalURL( $query ) );
426 }
427
428 function escapeFullURL( $query = "" ) {
429 return wfEscapeHTML( $this->getFullURL( $query ) );
430 }
431
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 );
437 }
438
439 # Get the edit URL, or a null string if it is an interwiki link
440 function getEditURL()
441 {
442 global $wgServer, $wgScript;
443
444 if ( "" != $this->mInterwiki ) { return ""; }
445 $s = $this->getLocalURL( "action=edit" );
446
447 return $s;
448 }
449
450 # Get HTML-escaped displayable text
451 # For the title field in <a> tags
452 function getEscapedText()
453 {
454 return wfEscapeHTML( $this->getPrefixedText() );
455 }
456
457 # Is the title interwiki?
458 function isExternal() { return ( "" != $this->mInterwiki ); }
459
460 # Does the title correspond to a protected article?
461 function isProtected()
462 {
463 if ( -1 == $this->mNamespace ) { return true; }
464 $a = $this->getRestrictions();
465 if ( in_array( "sysop", $a ) ) { return true; }
466 return false;
467 }
468
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()
474 {
475 if ( $this->mNamespace != Namespace::getWikipedia() ) {
476 return false;
477 }
478 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
479 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
480 return true;
481 }
482 return false;
483 }
484
485 # Is $wgUser is watching this page?
486 function userIsWatching()
487 {
488 global $wgUser;
489
490 if ( -1 == $this->mNamespace ) { return false; }
491 if ( 0 == $wgUser->getID() ) { return false; }
492
493 return $wgUser->isWatched( $this );
494 }
495
496 # Can $wgUser edit this page?
497 function userCanEdit()
498 {
499 global $wgUser;
500
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; }
511
512 $ur = $wgUser->getRights();
513 foreach ( $this->getRestrictions() as $r ) {
514 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
515 return false;
516 }
517 }
518 return true;
519 }
520
521 # Accessor/initialisation for mRestrictions
522 function getRestrictions()
523 {
524 $id = $this->getArticleID();
525 if ( 0 == $id ) { return array(); }
526
527 if ( ! $this->mRestrictionsLoaded ) {
528 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
529 $this->mRestrictions = explode( ",", trim( $res ) );
530 $this->mRestrictionsLoaded = true;
531 }
532 return $this->mRestrictions;
533 }
534
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;
543 }
544 return 0;
545 }
546
547 # Get the article ID from the link cache
548 # Used very heavily, e.g. in Parser::replaceInternalLinks()
549 function getArticleID()
550 {
551 global $wgLinkCache;
552
553 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
554 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
555 return $this->mArticleID;
556 }
557
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 )
562 {
563 global $wgLinkCache;
564 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
565
566 if ( 0 == $newid ) { $this->mArticleID = -1; }
567 else { $this->mArticleID = $newid; }
568 $this->mRestrictionsLoaded = false;
569 $this->mRestrictions = array();
570 }
571
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" );
580 }
581
582 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
583 /* private */ function prefix( $name )
584 {
585 global $wgLang;
586
587 $p = "";
588 if ( "" != $this->mInterwiki ) {
589 $p = $this->mInterwiki . ":";
590 }
591 if ( 0 != $this->mNamespace ) {
592 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
593 }
594 return $p . $name;
595 }
596
597 # Secure and split - main initialisation function for this object
598 #
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.
604 #
605 /* private */ function secureAndSplit()
606 {
607 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
608 $fname = "Title::secureAndSplit";
609 wfProfileIn( $fname );
610
611 static $imgpre = false;
612 static $rxTc = false;
613
614 # Initialisation
615 if ( $imgpre === false ) {
616 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
617 $rxTc = "/[^" . Title::legalChars() . "]/";
618 }
619
620 $this->mInterwiki = $this->mFragment = "";
621 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
622
623 # Clean up whitespace
624 #
625 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
626 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
627
628 if ( "" == $t ) {
629 wfProfileOut( $fname );
630 return false;
631 }
632
633 $this->mDbkeyform = $t;
634 $done = false;
635
636 # :Image: namespace
637 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
638 $t = substr( $t, 1 );
639 }
640
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;
663
664 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
665 $done = true;
666 } elseif($this->mInterwiki != $wgLocalInterwiki) {
667 $done = true;
668 }
669 }
670 }
671 $r = $t;
672 }
673
674 # Redundant interwiki prefix to the local wiki
675 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
676 $this->mInterwiki = "";
677 }
678 # We already know that some pages won't be in the database!
679 #
680 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
681 $this->mArticleID = 0;
682 }
683 $f = strstr( $r, "#" );
684 if ( false !== $f ) {
685 $this->mFragment = substr( $f, 1 );
686 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
687 }
688
689 # Reject illegal characters.
690 #
691 if( preg_match( $rxTc, $r ) ) {
692 return false;
693 }
694
695 # "." and ".." conflict with the directories of those names
696 if ( $r === "." || $r === ".." ) {
697 return false;
698 }
699
700 # Initial capital letter
701 if( $wgCapitalLinks && $this->mInterwiki == "") {
702 $t = $wgLang->ucfirst( $r );
703 }
704
705 # Fill fields
706 $this->mDbkeyform = $t;
707 $this->mUrlform = wfUrlencode( $t );
708
709 $this->mTextform = str_replace( "_", " ", $t );
710
711 wfProfileOut( $fname );
712 return true;
713 }
714
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() );
718 }
719
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() );
723 }
724
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;
738 }
739 }
740 wfFreeResult( $res );
741 return $retVal;
742 }
743
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;
758 }
759 }
760 wfFreeResult( $res );
761 return $retVal;
762 }
763
764 function getSquidURLs() {
765 return array(
766 $this->getInternalURL(),
767 $this->getInternalURL( "action=history" )
768 );
769 }
770
771 function moveNoAuth( &$nt ) {
772 return $this->moveTo( $nt, false );
773 }
774
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";
781 }
782
783 $fname = "Title::move";
784 $oldid = $this->getArticleID();
785 $newid = $nt->getArticleID();
786
787 if ( strlen( $nt->getDBkey() ) < 1 ) {
788 return "articleexists";
789 }
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";
798 }
799
800 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
801 return "protectedpage";
802 }
803
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).
807
808 if ( 0 != $newid ) { # Target exists; check for validity
809 if ( ! $this->isValidMoveTarget( $nt ) ) {
810 return "articleexists";
811 }
812 $this->moveOverExistingRedirect( $nt );
813 } else { # Target didn't exist, do normal move.
814 $this->moveToNewTitle( $nt, $newid );
815 }
816
817 # Update watchlists
818
819 $oldnamespace = $this->getNamespace() & ~1;
820 $newnamespace = $nt->getNamespace() & ~1;
821 $oldtitle = $this->getDBkey();
822 $newtitle = $nt->getDBkey();
823
824 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
825 WatchedItem::duplicateEntries( $this, $nt );
826 }
827
828 # Update search engine
829 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
830 $u->doUpdate();
831 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
832 $u->doUpdate();
833
834 return true;
835 }
836
837 # Move page to title which is presently a redirect to the source page
838
839 /* private */ function moveOverExistingRedirect( &$nt )
840 {
841 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
842 $fname = "Title::moveOverExistingRedirect";
843 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
844
845 $now = wfTimestampNow();
846 $won = wfInvertTimestamp( $now );
847 $newid = $nt->getArticleID();
848 $oldid = $this->getArticleID();
849
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()
857 ),
858 /* WHERE */ array( 'cur_id' => $oldid ),
859 $fname
860 );
861 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
862
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.
865
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
884 ),
885 /* WHERE */ array( 'cur_id' => $newid ),
886 $fname
887 );
888
889 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
890
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(),
898 ),
899 /* WHERE */ array(
900 'old_namespace' => $this->getNamespace(),
901 'old_title' => $this->getDBkey(),
902 ),
903 $fname
904 );
905
906 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
907
908 # Swap links
909
910 # Load titles and IDs
911 $linksToOld = $this->getLinksTo();
912 $linksToNew = $nt->getLinksTo();
913
914 # Make function to convert Titles to IDs
915 $titleToID = create_function('$t', 'return $t->getArticleID();');
916
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 );
923 }
924
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 );
931 }
932
933 # Note: the insert below must be after the updates above!
934
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 );
941
942 # Purge squid
943 if ( $wgUseSquid ) {
944 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
945 $u = new SquidUpdate( $urls );
946 $u->doUpdate();
947 }
948 }
949
950 # Move page to non-existing title.
951 # Sets $newid to be the new article ID
952
953 /* private */ function moveToNewTitle( &$nt, &$newid )
954 {
955 global $wgUser, $wgLinkCache, $wgUseSquid;
956 $fname = "MovePageForm::moveToNewTitle";
957 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
958
959 $now = wfTimestampNow();
960 $won = wfInvertTimestamp( $now );
961 $newid = $nt->getArticleID();
962 $oldid = $this->getArticleID();
963
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()
971 ),
972 /* WHERE */ array( 'cur_id' => $oldid ),
973 $fname
974 );
975
976 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
977
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" )
991 );
992 $newid = wfInsertId();
993 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
994
995 # Rename old entries
996 wfUpdateArray(
997 /* table */ 'old',
998 /* SET */ array(
999 'old_namespace' => $nt->getNamespace(),
1000 'old_title' => $nt->getDBkey()
1001 ),
1002 /* WHERE */ array(
1003 'old_namespace' => $this->getNamespace(),
1004 'old_title' => $this->getDBkey()
1005 ), $fname
1006 );
1007
1008 # Miscellaneous updates
1009
1010 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
1011 Article::onArticleCreate( $nt );
1012
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 );
1016
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 );
1020
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();
1025
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();
1033 }
1034 $u = new SquidUpdate( $urls );
1035 $u->doUpdate();
1036 }
1037 }
1038
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 )
1042 {
1043 $fname = "Title::isValidMoveTarget";
1044
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 );
1051
1052 if ( 0 == $obj->cur_is_redirect ) {
1053 # Not a redirect
1054 return false;
1055 }
1056
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;
1062 }
1063 }
1064
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() )
1069 );
1070
1071 # Return true if there was no history
1072 return $row === false;
1073 }
1074
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;
1081 }
1082
1083 $now = wfTimestampNow();
1084 $won = wfInvertTimestamp( $now );
1085
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"
1098 ));
1099 $newid = wfInsertId();
1100 $this->resetArticleID( $newid );
1101
1102 # Link table
1103 if ( $dest->getArticleID() ) {
1104 wfInsertArray( 'links', array(
1105 'l_to' => $dest->getArticleID(),
1106 'l_from' => $newid
1107 ));
1108 } else {
1109 wfInsertArray( 'brokenlinks', array(
1110 'bl_to' => $dest->getPrefixedDBkey(),
1111 'bl_from' => $newid
1112 ));
1113 }
1114
1115 Article::onArticleCreate( $this );
1116 return true;
1117 }
1118 }
1119 ?>