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