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