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