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