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