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