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