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