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