Fixed problem of User DaB. not being able to log in.
[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 ( strpos( $r, "." ) !== false &&
730 ( $r === "." || $r === ".." ||
731 strpos( $r, "./" ) === 0 ||
732 strpos( $r, "/./" !== false ) ||
733 strpos( $r, "/../" !== false ) ) )
734 {
735 return false;
736 }
737
738 # Initial capital letter
739 if( $wgCapitalLinks && $this->mInterwiki == "") {
740 $t = $wgLang->ucfirst( $r );
741 }
742
743 # Fill fields
744 $this->mDbkeyform = $t;
745 $this->mUrlform = wfUrlencode( $t );
746
747 $this->mTextform = str_replace( "_", " ", $t );
748
749 wfProfileOut( $fname );
750 return true;
751 }
752
753 # Get a title object associated with the talk page of this article
754 function getTalkPage() {
755 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
756 }
757
758 # Get a title object associated with the subject page of this talk page
759 function getSubjectPage() {
760 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
761 }
762
763 # Get an array of Title objects linking to this title
764 # Also stores the IDs in the link cache
765 function getLinksTo() {
766 global $wgLinkCache;
767 $id = $this->getArticleID();
768 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
769 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
770 $retVal = array();
771 if ( wfNumRows( $res ) ) {
772 while ( $row = wfFetchObject( $res ) ) {
773 if ( $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title ) ) {
774 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
775 $retVal[] = $titleObj;
776 }
777 }
778 }
779 wfFreeResult( $res );
780 return $retVal;
781 }
782
783 # Get an array of Title objects linking to this non-existent title
784 # Also stores the IDs in the link cache
785 function getBrokenLinksTo() {
786 global $wgLinkCache;
787 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
788 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
789 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
790 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
791 $retVal = array();
792 if ( wfNumRows( $res ) ) {
793 while ( $row = wfFetchObject( $res ) ) {
794 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
795 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
796 $retVal[] = $titleObj;
797 }
798 }
799 wfFreeResult( $res );
800 return $retVal;
801 }
802
803 function getSquidURLs() {
804 return array(
805 $this->getInternalURL(),
806 $this->getInternalURL( "action=history" )
807 );
808 }
809
810 function moveNoAuth( &$nt ) {
811 return $this->moveTo( $nt, false );
812 }
813
814 # Move a title to a new location
815 # Returns true on success, message name on failure
816 # auth indicates whether wgUser's permissions should be checked
817 function moveTo( &$nt, $auth = true ) {
818 if( !$this or !$nt ) {
819 return "badtitletext";
820 }
821
822 $fname = "Title::move";
823 $oldid = $this->getArticleID();
824 $newid = $nt->getArticleID();
825
826 if ( strlen( $nt->getDBkey() ) < 1 ) {
827 return "articleexists";
828 }
829 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
830 ( "" == $this->getDBkey() ) ||
831 ( "" != $this->getInterwiki() ) ||
832 ( !$oldid ) ||
833 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
834 ( "" == $nt->getDBkey() ) ||
835 ( "" != $nt->getInterwiki() ) ) {
836 return "badarticleerror";
837 }
838
839 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
840 return "protectedpage";
841 }
842
843 # The move is allowed only if (1) the target doesn't exist, or
844 # (2) the target is a redirect to the source, and has no history
845 # (so we can undo bad moves right after they're done).
846
847 if ( 0 != $newid ) { # Target exists; check for validity
848 if ( ! $this->isValidMoveTarget( $nt ) ) {
849 return "articleexists";
850 }
851 $this->moveOverExistingRedirect( $nt );
852 } else { # Target didn't exist, do normal move.
853 $this->moveToNewTitle( $nt, $newid );
854 }
855
856 # Update watchlists
857
858 $oldnamespace = $this->getNamespace() & ~1;
859 $newnamespace = $nt->getNamespace() & ~1;
860 $oldtitle = $this->getDBkey();
861 $newtitle = $nt->getDBkey();
862
863 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
864 WatchedItem::duplicateEntries( $this, $nt );
865 }
866
867 # Update search engine
868 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
869 $u->doUpdate();
870 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
871 $u->doUpdate();
872
873 return true;
874 }
875
876 # Move page to title which is presently a redirect to the source page
877
878 /* private */ function moveOverExistingRedirect( &$nt )
879 {
880 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
881 $fname = "Title::moveOverExistingRedirect";
882 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
883
884 $now = wfTimestampNow();
885 $won = wfInvertTimestamp( $now );
886 $newid = $nt->getArticleID();
887 $oldid = $this->getArticleID();
888
889 # Change the name of the target page:
890 wfUpdateArray(
891 /* table */ 'cur',
892 /* SET */ array(
893 'cur_touched' => $now,
894 'cur_namespace' => $nt->getNamespace(),
895 'cur_title' => $nt->getDBkey()
896 ),
897 /* WHERE */ array( 'cur_id' => $oldid ),
898 $fname
899 );
900 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
901
902 # Repurpose the old redirect. We don't save it to history since
903 # by definition if we've got here it's rather uninteresting.
904
905 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
906 wfUpdateArray(
907 /* table */ 'cur',
908 /* SET */ array(
909 'cur_touched' => $now,
910 'cur_timestamp' => $now,
911 'inverse_timestamp' => $won,
912 'cur_namespace' => $this->getNamespace(),
913 'cur_title' => $this->getDBkey(),
914 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
915 'cur_comment' => $comment,
916 'cur_user' => $wgUser->getID(),
917 'cur_minor_edit' => 0,
918 'cur_counter' => 0,
919 'cur_restrictions' => '',
920 'cur_user_text' => $wgUser->getName(),
921 'cur_is_redirect' => 1,
922 'cur_is_new' => 1
923 ),
924 /* WHERE */ array( 'cur_id' => $newid ),
925 $fname
926 );
927
928 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
929
930 # Fix the redundant names for the past revisions of the target page.
931 # The redirect should have no old revisions.
932 wfUpdateArray(
933 /* table */ 'old',
934 /* SET */ array(
935 'old_namespace' => $nt->getNamespace(),
936 'old_title' => $nt->getDBkey(),
937 ),
938 /* WHERE */ array(
939 'old_namespace' => $this->getNamespace(),
940 'old_title' => $this->getDBkey(),
941 ),
942 $fname
943 );
944
945 RecentChange::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
946
947 # Swap links
948
949 # Load titles and IDs
950 $linksToOld = $this->getLinksTo();
951 $linksToNew = $nt->getLinksTo();
952
953 # Delete them all
954 $sql = "DELETE FROM links WHERE l_to=$oldid OR l_to=$newid";
955 wfQuery( $sql, DB_WRITE, $fname );
956
957 # Reinsert
958 if ( count( $linksToOld ) || count( $linksToNew )) {
959 $sql = "INSERT INTO links (l_from,l_to) VALUES ";
960 $first = true;
961
962 # Insert links to old title
963 foreach ( $linksToOld as $linkTitle ) {
964 if ( $first ) {
965 $first = false;
966 } else {
967 $sql .= ",";
968 }
969 $id = $linkTitle->getArticleID();
970 $sql .= "($id,$newid)";
971 }
972
973 # Insert links to new title
974 foreach ( $linksToNew as $linkTitle ) {
975 if ( $first ) {
976 $first = false;
977 } else {
978 $sql .= ",";
979 }
980 $id = $linkTitle->getArticleID();
981 $sql .= "($id, $oldid)";
982 }
983
984 wfQuery( $sql, DB_WRITE, $fname );
985 }
986
987 # Now, we record the link from the redirect to the new title.
988 # It should have no other outgoing links...
989 $sql = "DELETE FROM links WHERE l_from={$newid}";
990 wfQuery( $sql, DB_WRITE, $fname );
991 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
992 wfQuery( $sql, DB_WRITE, $fname );
993
994 # Clear linkscc
995 LinkCache::linksccClearLinksTo( $oldid );
996 LinkCache::linksccClearLinksTo( $newid );
997
998 # Purge squid
999 if ( $wgUseSquid ) {
1000 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1001 $u = new SquidUpdate( $urls );
1002 $u->doUpdate();
1003 }
1004 }
1005
1006 # Move page to non-existing title.
1007 # Sets $newid to be the new article ID
1008
1009 /* private */ function moveToNewTitle( &$nt, &$newid )
1010 {
1011 global $wgUser, $wgLinkCache, $wgUseSquid;
1012 $fname = "MovePageForm::moveToNewTitle";
1013 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
1014
1015 $now = wfTimestampNow();
1016 $won = wfInvertTimestamp( $now );
1017 $newid = $nt->getArticleID();
1018 $oldid = $this->getArticleID();
1019
1020 # Rename cur entry
1021 wfUpdateArray(
1022 /* table */ 'cur',
1023 /* SET */ array(
1024 'cur_touched' => $now,
1025 'cur_namespace' => $nt->getNamespace(),
1026 'cur_title' => $nt->getDBkey()
1027 ),
1028 /* WHERE */ array( 'cur_id' => $oldid ),
1029 $fname
1030 );
1031
1032 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1033
1034 # Insert redirct
1035 wfInsertArray( 'cur', array(
1036 'cur_namespace' => $this->getNamespace(),
1037 'cur_title' => $this->getDBkey(),
1038 'cur_comment' => $comment,
1039 'cur_user' => $wgUser->getID(),
1040 'cur_user_text' => $wgUser->getName(),
1041 'cur_timestamp' => $now,
1042 'inverse_timestamp' => $won,
1043 'cur_touched' => $now,
1044 'cur_is_redirect' => 1,
1045 'cur_is_new' => 1,
1046 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
1047 );
1048 $newid = wfInsertId();
1049 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1050
1051 # Rename old entries
1052 wfUpdateArray(
1053 /* table */ 'old',
1054 /* SET */ array(
1055 'old_namespace' => $nt->getNamespace(),
1056 'old_title' => $nt->getDBkey()
1057 ),
1058 /* WHERE */ array(
1059 'old_namespace' => $this->getNamespace(),
1060 'old_title' => $this->getDBkey()
1061 ), $fname
1062 );
1063
1064 # Record in RC
1065 RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1066
1067 # Purge squid and linkscc as per article creation
1068 Article::onArticleCreate( $nt );
1069
1070 # Any text links to the old title must be reassigned to the redirect
1071 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1072 wfQuery( $sql, DB_WRITE, $fname );
1073 LinkCache::linksccClearLinksTo( $oldid );
1074
1075 # Record the just-created redirect's linking to the page
1076 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1077 wfQuery( $sql, DB_WRITE, $fname );
1078
1079 # Non-existent target may have had broken links to it; these must
1080 # now be removed and made into good links.
1081 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1082 $update->fixBrokenLinks();
1083
1084 # Purge old title from squid
1085 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1086 $titles = $nt->getLinksTo();
1087 if ( $wgUseSquid ) {
1088 $urls = $this->getSquidURLs();
1089 foreach ( $titles as $linkTitle ) {
1090 $urls[] = $linkTitle->getInternalURL();
1091 }
1092 $u = new SquidUpdate( $urls );
1093 $u->doUpdate();
1094 }
1095 }
1096
1097 # Checks if $this can be moved to $nt
1098 # Both titles must exist in the database, otherwise it will blow up
1099 function isValidMoveTarget( $nt )
1100 {
1101 $fname = "Title::isValidMoveTarget";
1102
1103 # Is it a redirect?
1104 $id = $nt->getArticleID();
1105 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1106 "WHERE cur_id={$id}";
1107 $res = wfQuery( $sql, DB_READ, $fname );
1108 $obj = wfFetchObject( $res );
1109
1110 if ( 0 == $obj->cur_is_redirect ) {
1111 # Not a redirect
1112 return false;
1113 }
1114
1115 # Does the redirect point to the source?
1116 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1117 $redirTitle = Title::newFromText( $m[1] );
1118 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1119 return false;
1120 }
1121 }
1122
1123 # Does the article have a history?
1124 $row = wfGetArray( 'old', array( 'old_id' ), array(
1125 'old_namespace' => $nt->getNamespace(),
1126 'old_title' => $nt->getDBkey() )
1127 );
1128
1129 # Return true if there was no history
1130 return $row === false;
1131 }
1132
1133 # Create a redirect, fails if the title already exists, does not notify RC
1134 # Returns success
1135 function createRedirect( $dest, $comment ) {
1136 global $wgUser;
1137 if ( $this->getArticleID() ) {
1138 return false;
1139 }
1140
1141 $now = wfTimestampNow();
1142 $won = wfInvertTimestamp( $now );
1143
1144 wfInsertArray( 'cur', array(
1145 'cur_namespace' => $this->getNamespace(),
1146 'cur_title' => $this->getDBkey(),
1147 'cur_comment' => $comment,
1148 'cur_user' => $wgUser->getID(),
1149 'cur_user_text' => $wgUser->getName(),
1150 'cur_timestamp' => $now,
1151 'inverse_timestamp' => $won,
1152 'cur_touched' => $now,
1153 'cur_is_redirect' => 1,
1154 'cur_is_new' => 1,
1155 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1156 ));
1157 $newid = wfInsertId();
1158 $this->resetArticleID( $newid );
1159
1160 # Link table
1161 if ( $dest->getArticleID() ) {
1162 wfInsertArray( 'links', array(
1163 'l_to' => $dest->getArticleID(),
1164 'l_from' => $newid
1165 ));
1166 } else {
1167 wfInsertArray( 'brokenlinks', array(
1168 'bl_to' => $dest->getPrefixedDBkey(),
1169 'bl_from' => $newid
1170 ));
1171 }
1172
1173 Article::onArticleCreate( $this );
1174 return true;
1175 }
1176
1177 # Get categories to wich belong this title and return an array of
1178 # categories names.
1179 function getParentCategories( )
1180 {
1181 global $wgLang,$wgUser;
1182
1183 #$titlekey = wfStrencode( $this->getArticleID() );
1184 $titlekey = $this->getArticleId();
1185 $cns = Namespace::getCategory();
1186 $sk =& $wgUser->getSkin();
1187 $parents = array();
1188
1189 # get the parents categories of this title from the database
1190 $sql = "SELECT DISTINCT cur_id FROM cur,categorylinks
1191 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1192 ORDER BY cl_sortkey" ;
1193 $res = wfQuery ( $sql, DB_READ ) ;
1194
1195 if(wfNumRows($res) > 0) {
1196 while ( $x = wfFetchObject ( $res ) ) $data[] = $x ;
1197 wfFreeResult ( $res ) ;
1198 } else {
1199 $data = '';
1200 }
1201 return $data;
1202 }
1203
1204 # will get the parents and grand-parents
1205 # TODO : not sure what's happening when a loop happen like:
1206 # Encyclopedia > Astronomy > Encyclopedia
1207 function getAllParentCategories(&$stack)
1208 {
1209 global $wgUser,$wgLang;
1210 $result = '';
1211
1212 # getting parents
1213 $parents = $this->getParentCategories( );
1214
1215 if($parents == '')
1216 {
1217 # The current element has no more parent so we dump the stack
1218 # and make a clean line of categories
1219 $sk =& $wgUser->getSkin() ;
1220
1221 foreach ( array_reverse($stack) as $child => $parent )
1222 {
1223 # make a link of that parent
1224 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).":".$parent,$parent);
1225 $result .= ' &gt; ';
1226 $lastchild = $child;
1227 }
1228 # append the last child.
1229 # TODO : We should have a last child unless there is an error in the
1230 # "categorylinks" table.
1231 if(isset($lastchild)) { $result .= $lastchild; }
1232
1233 $result .= "<br/>\n";
1234
1235 # now we can empty the stack
1236 $stack = array();
1237
1238 } else {
1239 # look at parents of current category
1240 foreach($parents as $parent)
1241 {
1242 # create a title object for the parent
1243 $tpar = Title::newFromID($parent->cur_id);
1244 # add it to the stack
1245 $stack[$this->getText()] = $tpar->getText();
1246 # grab its parents
1247 $result .= $tpar->getAllParentCategories($stack);
1248 }
1249 }
1250
1251 if(isset($result)) { return $result; }
1252 else { return ''; };
1253 }
1254
1255
1256 }
1257 ?>