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