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