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