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