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