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