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