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