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