Whitelist and diff fixes:
[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
490 if ( -1 == $this->mNamespace ) { return false; }
491 # if ( 0 == $this->getArticleID() ) { return false; }
492 if ( $this->mDbkeyform == "_" ) { return false; }
493 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
494 # protect css/js subpages of user pages
495 # XXX: this might be better using restrictions
496 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
497 global $wgUser;
498 if( Namespace::getUser() == $this->mNamespace
499 and preg_match("/\\.(css|js)$/", $this->mTextform )
500 and !$wgUser->isSysop()
501 and !preg_match("/^".preg_quote($wgUser->getName(), '/')."/", $this->mTextform) )
502 { return false; }
503 $ur = $wgUser->getRights();
504 foreach ( $this->getRestrictions() as $r ) {
505 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
506 return false;
507 }
508 }
509 return true;
510 }
511
512 function userCanRead() {
513 global $wgUser;
514 global $wgWhitelistRead;
515
516 if( 0 != $wgUser->getID() ) return true;
517 if( !is_array( $wgWhitelistRead ) ) return true;
518
519 $name = $this->getPrefixedText();
520 if( in_array( $name, $wgWhitelistRead ) ) return true;
521
522 # Compatibility with old settings
523 if( $this->getNamespace() == NS_ARTICLE ) {
524 if( in_array( ":" . $name, $wgWhitelistRead ) ) return true;
525 }
526 return false;
527 }
528
529 function isCssJsSubpage() {
530 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
531 }
532 function isCssSubpage() {
533 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
534 }
535 function isJsSubpage() {
536 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
537 }
538 function userCanEditCssJsSubpage() {
539 # protect css/js subpages of user pages
540 # XXX: this might be better using restrictions
541 global $wgUser;
542 return ( $wgUser->isSysop() or preg_match("/^".preg_quote($wgUser->getName())."/", $this->mTextform) );
543 }
544
545 # Accessor/initialisation for mRestrictions
546 function getRestrictions()
547 {
548 $id = $this->getArticleID();
549 if ( 0 == $id ) { return array(); }
550
551 if ( ! $this->mRestrictionsLoaded ) {
552 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
553 $this->mRestrictions = explode( ",", trim( $res ) );
554 $this->mRestrictionsLoaded = true;
555 }
556 return $this->mRestrictions;
557 }
558
559 # Is there a version of this page in the deletion archive?
560 function isDeleted() {
561 $ns = $this->getNamespace();
562 $t = wfStrencode( $this->getDBkey() );
563 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
564 if( $res = wfQuery( $sql, DB_READ ) ) {
565 $s = wfFetchObject( $res );
566 return $s->n;
567 }
568 return 0;
569 }
570
571 # Get the article ID from the link cache
572 # Used very heavily, e.g. in Parser::replaceInternalLinks()
573 function getArticleID()
574 {
575 global $wgLinkCache;
576
577 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
578 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
579 return $this->mArticleID;
580 }
581
582 # This clears some fields in this object, and clears any associated keys in the
583 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
584 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
585 function resetArticleID( $newid )
586 {
587 global $wgLinkCache;
588 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
589
590 if ( 0 == $newid ) { $this->mArticleID = -1; }
591 else { $this->mArticleID = $newid; }
592 $this->mRestrictionsLoaded = false;
593 $this->mRestrictions = array();
594 }
595
596 # Updates cur_touched
597 # Called from LinksUpdate.php
598 function invalidateCache() {
599 $now = wfTimestampNow();
600 $ns = $this->getNamespace();
601 $ti = wfStrencode( $this->getDBkey() );
602 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
603 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
604 }
605
606 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
607 /* private */ function prefix( $name )
608 {
609 global $wgLang;
610
611 $p = "";
612 if ( "" != $this->mInterwiki ) {
613 $p = $this->mInterwiki . ":";
614 }
615 if ( 0 != $this->mNamespace ) {
616 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
617 }
618 return $p . $name;
619 }
620
621 # Secure and split - main initialisation function for this object
622 #
623 # Assumes that mDbkeyform has been set, and is urldecoded
624 # and uses undersocres, but not otherwise munged. This function
625 # removes illegal characters, splits off the winterwiki and
626 # namespace prefixes, sets the other forms, and canonicalizes
627 # everything.
628 #
629 /* private */ function secureAndSplit()
630 {
631 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
632 $fname = "Title::secureAndSplit";
633 wfProfileIn( $fname );
634
635 static $imgpre = false;
636 static $rxTc = false;
637
638 # Initialisation
639 if ( $imgpre === false ) {
640 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
641 $rxTc = "/[^" . Title::legalChars() . "]/";
642 }
643
644 $this->mInterwiki = $this->mFragment = "";
645 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
646
647 # Clean up whitespace
648 #
649 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
650 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
651
652 if ( "" == $t ) {
653 wfProfileOut( $fname );
654 return false;
655 }
656
657 $this->mDbkeyform = $t;
658 $done = false;
659
660 # :Image: namespace
661 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
662 $t = substr( $t, 1 );
663 }
664
665 # Initial colon indicating main namespace
666 if ( ":" == $t{0} ) {
667 $r = substr( $t, 1 );
668 $this->mNamespace = NS_MAIN;
669 } else {
670 # Namespace or interwiki prefix
671 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
672 #$p = strtolower( $m[1] );
673 $p = $m[1];
674 $lowerNs = strtolower( $p );
675 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
676 # Canonical namespace
677 $t = $m[2];
678 $this->mNamespace = $ns;
679 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
680 # Ordinary namespace
681 $t = $m[2];
682 $this->mNamespace = $ns;
683 } elseif ( $this->getInterwikiLink( $p ) ) {
684 # Interwiki link
685 $t = $m[2];
686 $this->mInterwiki = $p;
687
688 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
689 $done = true;
690 } elseif($this->mInterwiki != $wgLocalInterwiki) {
691 $done = true;
692 }
693 }
694 }
695 $r = $t;
696 }
697
698 # Redundant interwiki prefix to the local wiki
699 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
700 $this->mInterwiki = "";
701 }
702 # We already know that some pages won't be in the database!
703 #
704 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
705 $this->mArticleID = 0;
706 }
707 $f = strstr( $r, "#" );
708 if ( false !== $f ) {
709 $this->mFragment = substr( $f, 1 );
710 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
711 }
712
713 # Reject illegal characters.
714 #
715 if( preg_match( $rxTc, $r ) ) {
716 return false;
717 }
718
719 # "." and ".." conflict with the directories of those names
720 if ( $r === "." || $r === ".." ) {
721 return false;
722 }
723
724 # Initial capital letter
725 if( $wgCapitalLinks && $this->mInterwiki == "") {
726 $t = $wgLang->ucfirst( $r );
727 }
728
729 # Fill fields
730 $this->mDbkeyform = $t;
731 $this->mUrlform = wfUrlencode( $t );
732
733 $this->mTextform = str_replace( "_", " ", $t );
734
735 wfProfileOut( $fname );
736 return true;
737 }
738
739 # Get a title object associated with the talk page of this article
740 function getTalkPage() {
741 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
742 }
743
744 # Get a title object associated with the subject page of this talk page
745 function getSubjectPage() {
746 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
747 }
748
749 # Get an array of Title objects linking to this title
750 # Also stores the IDs in the link cache
751 function getLinksTo() {
752 global $wgLinkCache;
753 $id = $this->getArticleID();
754 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
755 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
756 $retVal = array();
757 if ( wfNumRows( $res ) ) {
758 while ( $row = wfFetchObject( $res ) ) {
759 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
760 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
761 $retVal[] = $titleObj;
762 }
763 }
764 wfFreeResult( $res );
765 return $retVal;
766 }
767
768 # Get an array of Title objects linking to this non-existent title
769 # Also stores the IDs in the link cache
770 function getBrokenLinksTo() {
771 global $wgLinkCache;
772 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
773 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
774 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
775 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
776 $retVal = array();
777 if ( wfNumRows( $res ) ) {
778 while ( $row = wfFetchObject( $res ) ) {
779 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
780 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
781 $retVal[] = $titleObj;
782 }
783 }
784 wfFreeResult( $res );
785 return $retVal;
786 }
787
788 function getSquidURLs() {
789 return array(
790 $this->getInternalURL(),
791 $this->getInternalURL( "action=history" )
792 );
793 }
794
795 function moveNoAuth( &$nt ) {
796 return $this->moveTo( $nt, false );
797 }
798
799 # Move a title to a new location
800 # Returns true on success, message name on failure
801 # auth indicates whether wgUser's permissions should be checked
802 function moveTo( &$nt, $auth = true ) {
803 if( !$this or !$nt ) {
804 return "badtitletext";
805 }
806
807 $fname = "Title::move";
808 $oldid = $this->getArticleID();
809 $newid = $nt->getArticleID();
810
811 if ( strlen( $nt->getDBkey() ) < 1 ) {
812 return "articleexists";
813 }
814 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
815 ( "" == $this->getDBkey() ) ||
816 ( "" != $this->getInterwiki() ) ||
817 ( !$oldid ) ||
818 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
819 ( "" == $nt->getDBkey() ) ||
820 ( "" != $nt->getInterwiki() ) ) {
821 return "badarticleerror";
822 }
823
824 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
825 return "protectedpage";
826 }
827
828 # The move is allowed only if (1) the target doesn't exist, or
829 # (2) the target is a redirect to the source, and has no history
830 # (so we can undo bad moves right after they're done).
831
832 if ( 0 != $newid ) { # Target exists; check for validity
833 if ( ! $this->isValidMoveTarget( $nt ) ) {
834 return "articleexists";
835 }
836 $this->moveOverExistingRedirect( $nt );
837 } else { # Target didn't exist, do normal move.
838 $this->moveToNewTitle( $nt, $newid );
839 }
840
841 # Update watchlists
842
843 $oldnamespace = $this->getNamespace() & ~1;
844 $newnamespace = $nt->getNamespace() & ~1;
845 $oldtitle = $this->getDBkey();
846 $newtitle = $nt->getDBkey();
847
848 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
849 WatchedItem::duplicateEntries( $this, $nt );
850 }
851
852 # Update search engine
853 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
854 $u->doUpdate();
855 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
856 $u->doUpdate();
857
858 return true;
859 }
860
861 # Move page to title which is presently a redirect to the source page
862
863 /* private */ function moveOverExistingRedirect( &$nt )
864 {
865 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
866 $fname = "Title::moveOverExistingRedirect";
867 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
868
869 $now = wfTimestampNow();
870 $won = wfInvertTimestamp( $now );
871 $newid = $nt->getArticleID();
872 $oldid = $this->getArticleID();
873
874 # Change the name of the target page:
875 wfUpdateArray(
876 /* table */ 'cur',
877 /* SET */ array(
878 'cur_touched' => $now,
879 'cur_namespace' => $nt->getNamespace(),
880 'cur_title' => $nt->getDBkey()
881 ),
882 /* WHERE */ array( 'cur_id' => $oldid ),
883 $fname
884 );
885 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
886
887 # Repurpose the old redirect. We don't save it to history since
888 # by definition if we've got here it's rather uninteresting.
889
890 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
891 wfUpdateArray(
892 /* table */ 'cur',
893 /* SET */ array(
894 'cur_touched' => $now,
895 'cur_timestamp' => $now,
896 'inverse_timestamp' => $won,
897 'cur_namespace' => $this->getNamespace(),
898 'cur_title' => $this->getDBkey(),
899 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
900 'cur_comment' => $comment,
901 'cur_user' => $wgUser->getID(),
902 'cur_minor_edit' => 0,
903 'cur_counter' => 0,
904 'cur_restrictions' => '',
905 'cur_user_text' => $wgUser->getName(),
906 'cur_is_redirect' => 1,
907 'cur_is_new' => 1
908 ),
909 /* WHERE */ array( 'cur_id' => $newid ),
910 $fname
911 );
912
913 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
914
915 # Fix the redundant names for the past revisions of the target page.
916 # The redirect should have no old revisions.
917 wfUpdateArray(
918 /* table */ 'old',
919 /* SET */ array(
920 'old_namespace' => $nt->getNamespace(),
921 'old_title' => $nt->getDBkey(),
922 ),
923 /* WHERE */ array(
924 'old_namespace' => $this->getNamespace(),
925 'old_title' => $this->getDBkey(),
926 ),
927 $fname
928 );
929
930 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
931
932 # Swap links
933
934 # Load titles and IDs
935 $linksToOld = $this->getLinksTo();
936 $linksToNew = $nt->getLinksTo();
937
938 # Make function to convert Titles to IDs
939 $titleToID = create_function('$t', 'return $t->getArticleID();');
940
941 # Reassign links to old title
942 if ( count( $linksToOld ) ) {
943 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
944 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
945 $sql .= ")";
946 wfQuery( $sql, DB_WRITE, $fname );
947 }
948
949 # Reassign links to new title
950 if ( count( $linksToNew ) ) {
951 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
952 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
953 $sql .= ")";
954 wfQuery( $sql, DB_WRITE, $fname );
955 }
956
957 # Note: the insert below must be after the updates above!
958
959 # Now, we record the link from the redirect to the new title.
960 # It should have no other outgoing links...
961 $sql = "DELETE FROM links WHERE l_from={$newid}";
962 wfQuery( $sql, DB_WRITE, $fname );
963 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
964 wfQuery( $sql, DB_WRITE, $fname );
965
966 # Purge squid
967 if ( $wgUseSquid ) {
968 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
969 $u = new SquidUpdate( $urls );
970 $u->doUpdate();
971 }
972 }
973
974 # Move page to non-existing title.
975 # Sets $newid to be the new article ID
976
977 /* private */ function moveToNewTitle( &$nt, &$newid )
978 {
979 global $wgUser, $wgLinkCache, $wgUseSquid;
980 $fname = "MovePageForm::moveToNewTitle";
981 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
982
983 $now = wfTimestampNow();
984 $won = wfInvertTimestamp( $now );
985 $newid = $nt->getArticleID();
986 $oldid = $this->getArticleID();
987
988 # Rename cur entry
989 wfUpdateArray(
990 /* table */ 'cur',
991 /* SET */ array(
992 'cur_touched' => $now,
993 'cur_namespace' => $nt->getNamespace(),
994 'cur_title' => $nt->getDBkey()
995 ),
996 /* WHERE */ array( 'cur_id' => $oldid ),
997 $fname
998 );
999
1000 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1001
1002 # Insert redirct
1003 wfInsertArray( 'cur', array(
1004 'cur_namespace' => $this->getNamespace(),
1005 'cur_title' => $this->getDBkey(),
1006 'cur_comment' => $comment,
1007 'cur_user' => $wgUser->getID(),
1008 'cur_user_text' => $wgUser->getName(),
1009 'cur_timestamp' => $now,
1010 'inverse_timestamp' => $won,
1011 'cur_touched' => $now,
1012 'cur_is_redirect' => 1,
1013 'cur_is_new' => 1,
1014 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
1015 );
1016 $newid = wfInsertId();
1017 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1018
1019 # Rename old entries
1020 wfUpdateArray(
1021 /* table */ 'old',
1022 /* SET */ array(
1023 'old_namespace' => $nt->getNamespace(),
1024 'old_title' => $nt->getDBkey()
1025 ),
1026 /* WHERE */ array(
1027 'old_namespace' => $this->getNamespace(),
1028 'old_title' => $this->getDBkey()
1029 ), $fname
1030 );
1031
1032 # Miscellaneous updates
1033
1034 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
1035 Article::onArticleCreate( $nt );
1036
1037 # Any text links to the old title must be reassigned to the redirect
1038 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1039 wfQuery( $sql, DB_WRITE, $fname );
1040
1041 # Record the just-created redirect's linking to the page
1042 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1043 wfQuery( $sql, DB_WRITE, $fname );
1044
1045 # Non-existent target may have had broken links to it; these must
1046 # now be removed and made into good links.
1047 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1048 $update->fixBrokenLinks();
1049
1050 # Purge old title from squid
1051 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1052 $titles = $nt->getLinksTo();
1053 if ( $wgUseSquid ) {
1054 $urls = $this->getSquidURLs();
1055 foreach ( $titles as $linkTitle ) {
1056 $urls[] = $linkTitle->getInternalURL();
1057 }
1058 $u = new SquidUpdate( $urls );
1059 $u->doUpdate();
1060 }
1061 }
1062
1063 # Checks if $this can be moved to $nt
1064 # Both titles must exist in the database, otherwise it will blow up
1065 function isValidMoveTarget( $nt )
1066 {
1067 $fname = "Title::isValidMoveTarget";
1068
1069 # Is it a redirect?
1070 $id = $nt->getArticleID();
1071 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1072 "WHERE cur_id={$id}";
1073 $res = wfQuery( $sql, DB_READ, $fname );
1074 $obj = wfFetchObject( $res );
1075
1076 if ( 0 == $obj->cur_is_redirect ) {
1077 # Not a redirect
1078 return false;
1079 }
1080
1081 # Does the redirect point to the source?
1082 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1083 $redirTitle = Title::newFromText( $m[1] );
1084 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1085 return false;
1086 }
1087 }
1088
1089 # Does the article have a history?
1090 $row = wfGetArray( 'old', array( 'old_id' ), array(
1091 'old_namespace' => $nt->getNamespace(),
1092 'old_title' => $nt->getDBkey() )
1093 );
1094
1095 # Return true if there was no history
1096 return $row === false;
1097 }
1098
1099 # Create a redirect, fails if the title already exists, does not notify RC
1100 # Returns success
1101 function createRedirect( $dest, $comment ) {
1102 global $wgUser;
1103 if ( $this->getArticleID() ) {
1104 return false;
1105 }
1106
1107 $now = wfTimestampNow();
1108 $won = wfInvertTimestamp( $now );
1109
1110 wfInsertArray( 'cur', array(
1111 'cur_namespace' => $this->getNamespace(),
1112 'cur_title' => $this->getDBkey(),
1113 'cur_comment' => $comment,
1114 'cur_user' => $wgUser->getID(),
1115 'cur_user_text' => $wgUser->getName(),
1116 'cur_timestamp' => $now,
1117 'inverse_timestamp' => $won,
1118 'cur_touched' => $now,
1119 'cur_is_redirect' => 1,
1120 'cur_is_new' => 1,
1121 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1122 ));
1123 $newid = wfInsertId();
1124 $this->resetArticleID( $newid );
1125
1126 # Link table
1127 if ( $dest->getArticleID() ) {
1128 wfInsertArray( 'links', array(
1129 'l_to' => $dest->getArticleID(),
1130 'l_from' => $newid
1131 ));
1132 } else {
1133 wfInsertArray( 'brokenlinks', array(
1134 'bl_to' => $dest->getPrefixedDBkey(),
1135 'bl_from' => $newid
1136 ));
1137 }
1138
1139 Article::onArticleCreate( $this );
1140 return true;
1141 }
1142
1143 }
1144 ?>