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