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