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