Slight adjustment to self-interwiki fix: disallow empty title links
[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 if( $t == '' ) {
1115 # Can't have an empty self-link
1116 wfProfileOut( $fname );
1117 return false;
1118 }
1119 $this->mInterwiki = '';
1120 $firstPass = false;
1121 # Do another namespace split...
1122 continue;
1123 }
1124 }
1125 # If there's no recognized interwiki or namespace,
1126 # then let the colon expression be part of the title.
1127 }
1128 break;
1129 } while( true );
1130 $r = $t;
1131 }
1132
1133 # We already know that some pages won't be in the database!
1134 #
1135 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1136 $this->mArticleID = 0;
1137 }
1138 $f = strstr( $r, '#' );
1139 if ( false !== $f ) {
1140 $this->mFragment = substr( $f, 1 );
1141 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1142 # remove whitespace again: prevents "Foo_bar_#"
1143 # becoming "Foo_bar_"
1144 $r = preg_replace( '/_*$/', '', $r );
1145 }
1146
1147 # Reject illegal characters.
1148 #
1149 if( preg_match( $rxTc, $r ) ) {
1150 wfProfileOut( $fname );
1151 return false;
1152 }
1153
1154 /**
1155 * Pages with "/./" or "/../" appearing in the URLs will
1156 * often be unreachable due to the way web browsers deal
1157 * with 'relative' URLs. Forbid them explicitly.
1158 */
1159 if ( strpos( $r, '.' ) !== false &&
1160 ( $r === '.' || $r === '..' ||
1161 strpos( $r, './' ) === 0 ||
1162 strpos( $r, '../' ) === 0 ||
1163 strpos( $r, '/./' ) !== false ||
1164 strpos( $r, '/../' ) !== false ) )
1165 {
1166 wfProfileOut( $fname );
1167 return false;
1168 }
1169
1170 # We shouldn't need to query the DB for the size.
1171 #$maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
1172 if ( strlen( $r ) > 255 ) {
1173 return false;
1174 }
1175
1176 /**
1177 * Normally, all wiki links are forced to have
1178 * an initial capital letter so [[foo]] and [[Foo]]
1179 * point to the same place.
1180 *
1181 * Don't force it for interwikis, since the other
1182 * site might be case-sensitive.
1183 */
1184 if( $wgCapitalLinks && $this->mInterwiki == '') {
1185 $t = $wgContLang->ucfirst( $r );
1186 } else {
1187 $t = $r;
1188 }
1189
1190 # Fill fields
1191 $this->mDbkeyform = $t;
1192 $this->mUrlform = wfUrlencode( $t );
1193
1194 $this->mTextform = str_replace( '_', ' ', $t );
1195
1196 wfProfileOut( $fname );
1197 return true;
1198 }
1199
1200 /**
1201 * Get a Title object associated with the talk page of this article
1202 * @return Title the object for the talk page
1203 * @access public
1204 */
1205 function getTalkPage() {
1206 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1207 }
1208
1209 /**
1210 * Get a title object associated with the subject page of this
1211 * talk page
1212 *
1213 * @return Title the object for the subject page
1214 * @access public
1215 */
1216 function getSubjectPage() {
1217 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1218 }
1219
1220 /**
1221 * Get an array of Title objects linking to this Title
1222 * - Also stores the IDs in the link cache.
1223 *
1224 * @param string $options may be FOR UPDATE
1225 * @return array the Title objects linking here
1226 * @access public
1227 */
1228 function getLinksTo( $options = '' ) {
1229 global $wgLinkCache;
1230 $id = $this->getArticleID();
1231
1232 if ( $options ) {
1233 $db =& wfGetDB( DB_MASTER );
1234 } else {
1235 $db =& wfGetDB( DB_SLAVE );
1236 }
1237 $cur = $db->tableName( 'cur' );
1238 $links = $db->tableName( 'links' );
1239
1240 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
1241 $res = $db->query( $sql, 'Title::getLinksTo' );
1242 $retVal = array();
1243 if ( $db->numRows( $res ) ) {
1244 while ( $row = $db->fetchObject( $res ) ) {
1245 if ( $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title ) ) {
1246 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
1247 $retVal[] = $titleObj;
1248 }
1249 }
1250 }
1251 $db->freeResult( $res );
1252 return $retVal;
1253 }
1254
1255 /**
1256 * Get an array of Title objects linking to this non-existent title.
1257 * - Also stores the IDs in the link cache.
1258 *
1259 * @param string $options may be FOR UPDATE
1260 * @return array the Title objects linking here
1261 * @access public
1262 */
1263 function getBrokenLinksTo( $options = '' ) {
1264 global $wgLinkCache;
1265
1266 if ( $options ) {
1267 $db =& wfGetDB( DB_MASTER );
1268 } else {
1269 $db =& wfGetDB( DB_SLAVE );
1270 }
1271 $cur = $db->tableName( 'cur' );
1272 $brokenlinks = $db->tableName( 'brokenlinks' );
1273 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1274
1275 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
1276 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
1277 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1278 $retVal = array();
1279 if ( $db->numRows( $res ) ) {
1280 while ( $row = $db->fetchObject( $res ) ) {
1281 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
1282 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
1283 $retVal[] = $titleObj;
1284 }
1285 }
1286 $db->freeResult( $res );
1287 return $retVal;
1288 }
1289
1290 /**
1291 * Get a list of URLs to purge from the Squid cache when this
1292 * page changes
1293 *
1294 * @return array the URLs
1295 * @access public
1296 */
1297 function getSquidURLs() {
1298 return array(
1299 $this->getInternalURL(),
1300 $this->getInternalURL( 'action=history' )
1301 );
1302 }
1303
1304 /**
1305 * Move this page without authentication
1306 * @param Title &$nt the new page Title
1307 * @access public
1308 */
1309 function moveNoAuth( &$nt ) {
1310 return $this->moveTo( $nt, false );
1311 }
1312
1313 /**
1314 * Move a title to a new location
1315 * @param Title &$nt the new title
1316 * @param bool $auth indicates whether $wgUser's permissions
1317 * should be checked
1318 * @return mixed true on success, message name on failure
1319 * @access public
1320 */
1321 function moveTo( &$nt, $auth = true ) {
1322 if( !$this or !$nt ) {
1323 return 'badtitletext';
1324 }
1325
1326 $fname = 'Title::move';
1327 $oldid = $this->getArticleID();
1328 $newid = $nt->getArticleID();
1329
1330 if ( strlen( $nt->getDBkey() ) < 1 ) {
1331 return 'articleexists';
1332 }
1333 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1334 ( '' == $this->getDBkey() ) ||
1335 ( '' != $this->getInterwiki() ) ||
1336 ( !$oldid ) ||
1337 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1338 ( '' == $nt->getDBkey() ) ||
1339 ( '' != $nt->getInterwiki() ) ) {
1340 return 'badarticleerror';
1341 }
1342
1343 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
1344 return 'protectedpage';
1345 }
1346
1347 # The move is allowed only if (1) the target doesn't exist, or
1348 # (2) the target is a redirect to the source, and has no history
1349 # (so we can undo bad moves right after they're done).
1350
1351 if ( 0 != $newid ) { # Target exists; check for validity
1352 if ( ! $this->isValidMoveTarget( $nt ) ) {
1353 return 'articleexists';
1354 }
1355 $this->moveOverExistingRedirect( $nt );
1356 } else { # Target didn't exist, do normal move.
1357 $this->moveToNewTitle( $nt, $newid );
1358 }
1359
1360 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1361
1362 $dbw =& wfGetDB( DB_MASTER );
1363 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1364 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1365 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1366 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1367
1368 # Update watchlists
1369
1370 $oldnamespace = $this->getNamespace() & ~1;
1371 $newnamespace = $nt->getNamespace() & ~1;
1372 $oldtitle = $this->getDBkey();
1373 $newtitle = $nt->getDBkey();
1374
1375 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1376 WatchedItem::duplicateEntries( $this, $nt );
1377 }
1378
1379 # Update search engine
1380 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1381 $u->doUpdate();
1382 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1383 $u->doUpdate();
1384
1385 return true;
1386 }
1387
1388 /**
1389 * Move page to a title which is at present a redirect to the
1390 * source page
1391 *
1392 * @param Title &$nt the page to move to, which should currently
1393 * be a redirect
1394 * @access private
1395 */
1396 /* private */ function moveOverExistingRedirect( &$nt ) {
1397 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1398 $fname = 'Title::moveOverExistingRedirect';
1399 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1400
1401 $now = wfTimestampNow();
1402 $won = wfInvertTimestamp( $now );
1403 $newid = $nt->getArticleID();
1404 $oldid = $this->getArticleID();
1405 $dbw =& wfGetDB( DB_MASTER );
1406 $links = $dbw->tableName( 'links' );
1407
1408 # Change the name of the target page:
1409 $dbw->update( 'cur',
1410 /* SET */ array(
1411 'cur_touched' => $dbw->timestamp($now),
1412 'cur_namespace' => $nt->getNamespace(),
1413 'cur_title' => $nt->getDBkey()
1414 ),
1415 /* WHERE */ array( 'cur_id' => $oldid ),
1416 $fname
1417 );
1418 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1419
1420 # Repurpose the old redirect. We don't save it to history since
1421 # by definition if we've got here it's rather uninteresting.
1422
1423 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1424 $dbw->update( 'cur',
1425 /* SET */ array(
1426 'cur_touched' => $dbw->timestamp($now),
1427 'cur_timestamp' => $dbw->timestamp($now),
1428 'inverse_timestamp' => $won,
1429 'cur_namespace' => $this->getNamespace(),
1430 'cur_title' => $this->getDBkey(),
1431 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1432 'cur_comment' => $comment,
1433 'cur_user' => $wgUser->getID(),
1434 'cur_minor_edit' => 0,
1435 'cur_counter' => 0,
1436 'cur_restrictions' => '',
1437 'cur_user_text' => $wgUser->getName(),
1438 'cur_is_redirect' => 1,
1439 'cur_is_new' => 1
1440 ),
1441 /* WHERE */ array( 'cur_id' => $newid ),
1442 $fname
1443 );
1444
1445 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1446
1447 # Fix the redundant names for the past revisions of the target page.
1448 # The redirect should have no old revisions.
1449 $dbw->update(
1450 /* table */ 'old',
1451 /* SET */ array(
1452 'old_namespace' => $nt->getNamespace(),
1453 'old_title' => $nt->getDBkey(),
1454 ),
1455 /* WHERE */ array(
1456 'old_namespace' => $this->getNamespace(),
1457 'old_title' => $this->getDBkey(),
1458 ),
1459 $fname
1460 );
1461
1462 RecentChange::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1463
1464 # Swap links
1465
1466 # Load titles and IDs
1467 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1468 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1469
1470 # Delete them all
1471 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1472 $dbw->query( $sql, $fname );
1473
1474 # Reinsert
1475 if ( count( $linksToOld ) || count( $linksToNew )) {
1476 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1477 $first = true;
1478
1479 # Insert links to old title
1480 foreach ( $linksToOld as $linkTitle ) {
1481 if ( $first ) {
1482 $first = false;
1483 } else {
1484 $sql .= ',';
1485 }
1486 $id = $linkTitle->getArticleID();
1487 $sql .= "($id,$newid)";
1488 }
1489
1490 # Insert links to new title
1491 foreach ( $linksToNew as $linkTitle ) {
1492 if ( $first ) {
1493 $first = false;
1494 } else {
1495 $sql .= ',';
1496 }
1497 $id = $linkTitle->getArticleID();
1498 $sql .= "($id, $oldid)";
1499 }
1500
1501 $dbw->query( $sql, DB_MASTER, $fname );
1502 }
1503
1504 # Now, we record the link from the redirect to the new title.
1505 # It should have no other outgoing links...
1506 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1507 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1508
1509 # Clear linkscc
1510 LinkCache::linksccClearLinksTo( $oldid );
1511 LinkCache::linksccClearLinksTo( $newid );
1512
1513 # Purge squid
1514 if ( $wgUseSquid ) {
1515 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1516 $u = new SquidUpdate( $urls );
1517 $u->doUpdate();
1518 }
1519 }
1520
1521 /**
1522 * Move page to non-existing title.
1523 * @param Title &$nt the new Title
1524 * @param int &$newid set to be the new article ID
1525 * @access private
1526 */
1527 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1528 global $wgUser, $wgLinkCache, $wgUseSquid;
1529 $fname = 'MovePageForm::moveToNewTitle';
1530 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1531
1532 $newid = $nt->getArticleID();
1533 $oldid = $this->getArticleID();
1534 $dbw =& wfGetDB( DB_MASTER );
1535 $now = $dbw->timestamp();
1536 $won = wfInvertTimestamp( wfTimestamp(TS_MW,$now) );
1537 wfSeedRandom();
1538 $rand = wfRandom();
1539
1540 # Rename cur entry
1541 $dbw->update( 'cur',
1542 /* SET */ array(
1543 'cur_touched' => $now,
1544 'cur_namespace' => $nt->getNamespace(),
1545 'cur_title' => $nt->getDBkey()
1546 ),
1547 /* WHERE */ array( 'cur_id' => $oldid ),
1548 $fname
1549 );
1550
1551 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1552
1553 # Insert redirect
1554 $dbw->insert( 'cur', array(
1555 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1556 'cur_namespace' => $this->getNamespace(),
1557 'cur_title' => $this->getDBkey(),
1558 'cur_comment' => $comment,
1559 'cur_user' => $wgUser->getID(),
1560 'cur_user_text' => $wgUser->getName(),
1561 'cur_timestamp' => $now,
1562 'inverse_timestamp' => $won,
1563 'cur_touched' => $now,
1564 'cur_is_redirect' => 1,
1565 'cur_random' => $rand,
1566 'cur_is_new' => 1,
1567 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1568 );
1569 $newid = $dbw->insertId();
1570 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1571
1572 # Rename old entries
1573 $dbw->update(
1574 /* table */ 'old',
1575 /* SET */ array(
1576 'old_namespace' => $nt->getNamespace(),
1577 'old_title' => $nt->getDBkey()
1578 ),
1579 /* WHERE */ array(
1580 'old_namespace' => $this->getNamespace(),
1581 'old_title' => $this->getDBkey()
1582 ), $fname
1583 );
1584
1585 # Record in RC
1586 RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1587
1588 # Purge squid and linkscc as per article creation
1589 Article::onArticleCreate( $nt );
1590
1591 # Any text links to the old title must be reassigned to the redirect
1592 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1593 LinkCache::linksccClearLinksTo( $oldid );
1594
1595 # Record the just-created redirect's linking to the page
1596 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1597
1598 # Non-existent target may have had broken links to it; these must
1599 # now be removed and made into good links.
1600 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1601 $update->fixBrokenLinks();
1602
1603 # Purge old title from squid
1604 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1605 $titles = $nt->getLinksTo();
1606 if ( $wgUseSquid ) {
1607 $urls = $this->getSquidURLs();
1608 foreach ( $titles as $linkTitle ) {
1609 $urls[] = $linkTitle->getInternalURL();
1610 }
1611 $u = new SquidUpdate( $urls );
1612 $u->doUpdate();
1613 }
1614 }
1615
1616 /**
1617 * Checks if $this can be moved to a given Title
1618 * - Selects for update, so don't call it unless you mean business
1619 *
1620 * @param Title &$nt the new title to check
1621 * @access public
1622 */
1623 function isValidMoveTarget( $nt ) {
1624 $fname = 'Title::isValidMoveTarget';
1625 $dbw =& wfGetDB( DB_MASTER );
1626
1627 # Is it a redirect?
1628 $id = $nt->getArticleID();
1629 $obj = $dbw->selectRow( 'cur', array( 'cur_is_redirect','cur_text' ),
1630 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1631
1632 if ( !$obj || 0 == $obj->cur_is_redirect ) {
1633 # Not a redirect
1634 return false;
1635 }
1636
1637 # Does the redirect point to the source?
1638 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text, $m ) ) {
1639 $redirTitle = Title::newFromText( $m[1] );
1640 if( !is_object( $redirTitle ) ||
1641 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1642 return false;
1643 }
1644 }
1645
1646 # Does the article have a history?
1647 $row = $dbw->selectRow( 'old', array( 'old_id' ),
1648 array(
1649 'old_namespace' => $nt->getNamespace(),
1650 'old_title' => $nt->getDBkey()
1651 ), $fname, 'FOR UPDATE'
1652 );
1653
1654 # Return true if there was no history
1655 return $row === false;
1656 }
1657
1658 /**
1659 * Create a redirect; fails if the title already exists; does
1660 * not notify RC
1661 *
1662 * @param Title $dest the destination of the redirect
1663 * @param string $comment the comment string describing the move
1664 * @return bool true on success
1665 * @access public
1666 */
1667 function createRedirect( $dest, $comment ) {
1668 global $wgUser;
1669 if ( $this->getArticleID() ) {
1670 return false;
1671 }
1672
1673 $fname = 'Title::createRedirect';
1674 $dbw =& wfGetDB( DB_MASTER );
1675 $now = wfTimestampNow();
1676 $won = wfInvertTimestamp( $now );
1677 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1678
1679 $dbw->insert( 'cur', array(
1680 'cur_id' => $seqVal,
1681 'cur_namespace' => $this->getNamespace(),
1682 'cur_title' => $this->getDBkey(),
1683 'cur_comment' => $comment,
1684 'cur_user' => $wgUser->getID(),
1685 'cur_user_text' => $wgUser->getName(),
1686 'cur_timestamp' => $now,
1687 'inverse_timestamp' => $won,
1688 'cur_touched' => $now,
1689 'cur_is_redirect' => 1,
1690 'cur_is_new' => 1,
1691 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1692 ), $fname );
1693 $newid = $dbw->insertId();
1694 $this->resetArticleID( $newid );
1695
1696 # Link table
1697 if ( $dest->getArticleID() ) {
1698 $dbw->insert( 'links',
1699 array(
1700 'l_to' => $dest->getArticleID(),
1701 'l_from' => $newid
1702 ), $fname
1703 );
1704 } else {
1705 $dbw->insert( 'brokenlinks',
1706 array(
1707 'bl_to' => $dest->getPrefixedDBkey(),
1708 'bl_from' => $newid
1709 ), $fname
1710 );
1711 }
1712
1713 Article::onArticleCreate( $this );
1714 return true;
1715 }
1716
1717 /**
1718 * Get categories to which this Title belongs and return an array of
1719 * categories' names.
1720 *
1721 * @return array an array of parents in the form:
1722 * $parent => $currentarticle
1723 * @access public
1724 */
1725 function getParentCategories() {
1726 global $wgContLang,$wgUser;
1727
1728 $titlekey = $this->getArticleId();
1729 $sk =& $wgUser->getSkin();
1730 $parents = array();
1731 $dbr =& wfGetDB( DB_SLAVE );
1732 $categorylinks = $dbr->tableName( 'categorylinks' );
1733
1734 # NEW SQL
1735 $sql = "SELECT * FROM $categorylinks"
1736 ." WHERE cl_from='$titlekey'"
1737 ." AND cl_from <> '0'"
1738 ." ORDER BY cl_sortkey";
1739
1740 $res = $dbr->query ( $sql ) ;
1741
1742 if($dbr->numRows($res) > 0) {
1743 while ( $x = $dbr->fetchObject ( $res ) )
1744 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1745 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1746 $dbr->freeResult ( $res ) ;
1747 } else {
1748 $data = '';
1749 }
1750 return $data;
1751 }
1752
1753 /**
1754 * Get a tree of parent categories
1755 * @param array $children an array with the children in the keys, to check for circular refs
1756 * @return array
1757 * @access public
1758 */
1759 function getParentCategoryTree( $children = array() ) {
1760 $parents = $this->getParentCategories();
1761
1762 if($parents != '') {
1763 foreach($parents as $parent => $current)
1764 {
1765 if ( array_key_exists( $parent, $children ) ) {
1766 # Circular reference
1767 $stack[$parent] = array();
1768 } else {
1769 $nt = Title::newFromText($parent);
1770 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1771 }
1772 }
1773 return $stack;
1774 } else {
1775 return array();
1776 }
1777 }
1778
1779
1780 /**
1781 * Get an associative array for selecting this title from
1782 * the "cur" table
1783 *
1784 * @return array
1785 * @access public
1786 */
1787 function curCond() {
1788 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1789 }
1790
1791 /**
1792 * Get an associative array for selecting this title from the
1793 * "old" table
1794 *
1795 * @return array
1796 * @access public
1797 */
1798 function oldCond() {
1799 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1800 }
1801
1802 /**
1803 * Get the revision ID of the previous revision
1804 *
1805 * @param integer $revision Revision ID. Get the revision that was before this one.
1806 * @return interger $oldrevision|false
1807 */
1808 function getPreviousRevisionID( $revision ) {
1809 $dbr =& wfGetDB( DB_SLAVE );
1810 return $dbr->selectField( 'old', 'old_id',
1811 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1812 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1813 ' AND old_id<' . IntVal( $revision ) . ' ORDER BY old_id DESC' );
1814 }
1815
1816 /**
1817 * Get the revision ID of the next revision
1818 *
1819 * @param integer $revision Revision ID. Get the revision that was after this one.
1820 * @return interger $oldrevision|false
1821 */
1822 function getNextRevisionID( $revision ) {
1823 $dbr =& wfGetDB( DB_SLAVE );
1824 return $dbr->selectField( 'old', 'old_id',
1825 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1826 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1827 ' AND old_id>' . IntVal( $revision ) . ' ORDER BY old_id' );
1828 }
1829
1830 }
1831 ?>