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