95ee0176c461c033955b717409db61755e959256
[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 ( '' != $this->mFragment ) {
633 $url .= '#' . $this->mFragment;
634 }
635 return $url;
636 }
637 }
638
639 /**
640 * Get a URL with no fragment or server name
641 * @param string $query an optional query string; if not specified,
642 * $wgArticlePath will be used.
643 * @return string the URL
644 * @access public
645 */
646 function getLocalURL( $query = '' ) {
647 global $wgLang, $wgArticlePath, $wgScript;
648
649 if ( $this->isExternal() ) {
650 return $this->getFullURL();
651 }
652
653 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
654 if ( $query == '' ) {
655 $url = str_replace( '$1', $dbkey, $wgArticlePath );
656 } else {
657 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
658 global $wgActionPaths;
659 $action = urldecode( $matches[2] );
660 if( isset( $wgActionPaths[$action] ) ) {
661 $query = $matches[1];
662 if( isset( $matches[4] ) ) $query .= $matches[4];
663 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
664 if( $query != '' ) $url .= '?' . $query;
665 return $url;
666 }
667 }
668 if ( $query == '-' ) {
669 $query = '';
670 }
671 $url = "{$wgScript}?title={$dbkey}&{$query}";
672 }
673 return $url;
674 }
675
676 /**
677 * Get an HTML-escaped version of the URL form, suitable for
678 * using in a link, without a server name or fragment
679 * @param string $query an optional query string
680 * @return string the URL
681 * @access public
682 */
683 function escapeLocalURL( $query = '' ) {
684 return htmlspecialchars( $this->getLocalURL( $query ) );
685 }
686
687 /**
688 * Get an HTML-escaped version of the URL form, suitable for
689 * using in a link, including the server name and fragment
690 *
691 * @return string the URL
692 * @param string $query an optional query string
693 * @access public
694 */
695 function escapeFullURL( $query = '' ) {
696 return htmlspecialchars( $this->getFullURL( $query ) );
697 }
698
699 /**
700 * Get the URL form for an internal link.
701 * - Used in various Squid-related code, in case we have a different
702 * internal hostname for the server from the exposed one.
703 *
704 * @param string $query an optional query string
705 * @return string the URL
706 * @access public
707 */
708 function getInternalURL( $query = '' ) {
709 global $wgInternalServer;
710 return $wgInternalServer . $this->getLocalURL( $query );
711 }
712
713 /**
714 * Get the edit URL for this Title
715 * @return string the URL, or a null string if this is an
716 * interwiki link
717 * @access public
718 */
719 function getEditURL() {
720 global $wgServer, $wgScript;
721
722 if ( '' != $this->mInterwiki ) { return ''; }
723 $s = $this->getLocalURL( 'action=edit' );
724
725 return $s;
726 }
727
728 /**
729 * Get the HTML-escaped displayable text form.
730 * Used for the title field in <a> tags.
731 * @return string the text, including any prefixes
732 * @access public
733 */
734 function getEscapedText() {
735 return htmlspecialchars( $this->getPrefixedText() );
736 }
737
738 /**
739 * Is this Title interwiki?
740 * @return boolean
741 * @access public
742 */
743 function isExternal() { return ( '' != $this->mInterwiki ); }
744
745 /**
746 * Does the title correspond to a protected article?
747 * @param string $what the action the page is protected from,
748 * by default checks move and edit
749 * @return boolean
750 * @access public
751 */
752 function isProtected($action = '') {
753 if ( -1 == $this->mNamespace ) { return true; }
754 if($action == 'edit' || $action == '') {
755 $a = $this->getRestrictions("edit");
756 if ( in_array( 'sysop', $a ) ) { return true; }
757 }
758 if($action == 'move' || $action == '') {
759 $a = $this->getRestrictions("move");
760 if ( in_array( 'sysop', $a ) ) { return true; }
761 }
762 return false;
763 }
764
765 /**
766 * Is $wgUser is watching this page?
767 * @return boolean
768 * @access public
769 */
770 function userIsWatching() {
771 global $wgUser;
772
773 if ( -1 == $this->mNamespace ) { return false; }
774 if ( 0 == $wgUser->getID() ) { return false; }
775
776 return $wgUser->isWatched( $this );
777 }
778
779 /**
780 * Is $wgUser perform $action this page?
781 * @param string $action action that permission needs to be checked for
782 * @return boolean
783 * @access private
784 */
785 function userCan($action) {
786 $fname = 'Title::userCanEdit';
787 wfProfileIn( $fname );
788
789 global $wgUser;
790 if( NS_SPECIAL == $this->mNamespace ) {
791 wfProfileOut( $fname );
792 return false;
793 }
794 if( NS_MEDIAWIKI == $this->mNamespace &&
795 !$wgUser->isAllowed('editinterface') ) {
796 wfProfileOut( $fname );
797 return false;
798 }
799 if( $this->mDbkeyform == '_' ) {
800 # FIXME: Is this necessary? Shouldn't be allowed anyway...
801 wfProfileOut( $fname );
802 return false;
803 }
804
805 # protect global styles and js
806 if ( NS_MEDIAWIKI == $this->mNamespace
807 && preg_match("/\\.(css|js)$/", $this->mTextform )
808 && !$wgUser->isAllowed('editinterface') ) {
809 wfProfileOut( $fname );
810 return false;
811 }
812
813 # protect css/js subpages of user pages
814 # XXX: this might be better using restrictions
815 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
816 if( NS_USER == $this->mNamespace
817 && preg_match("/\\.(css|js)$/", $this->mTextform )
818 && !$wgUser->isAllowed('editinterface')
819 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
820 wfProfileOut( $fname );
821 return false;
822 }
823
824 foreach( $this->getRestrictions($action) as $right ) {
825 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
826 wfProfileOut( $fname );
827 return false;
828 }
829 }
830 wfProfileOut( $fname );
831 return true;
832 }
833
834 /**
835 * Can $wgUser edit this page?
836 * @return boolean
837 * @access public
838 */
839 function userCanEdit() {
840 return $this->userCan('edit');
841 }
842
843 /**
844 * Can $wgUser move this page?
845 * @return boolean
846 * @access public
847 */
848 function userCanMove() {
849 return $this->userCan('move');
850 }
851
852 /**
853 * Can $wgUser read this page?
854 * @return boolean
855 * @access public
856 */
857 function userCanRead() {
858 global $wgUser;
859
860 if( $wgUser->isAllowed('read') ) {
861 return true;
862 } else {
863 global $wgWhitelistRead;
864
865 /** If anon users can create an account,
866 they need to reach the login page first! */
867 if( $wgUser->isAllowed( 'createaccount' )
868 && $this->mId == NS_SPECIAL
869 && $this->getText() == 'Userlogin' ) {
870 return true;
871 }
872
873 /** some pages are explicitly allowed */
874 $name = $this->getPrefixedText();
875 if( in_array( $name, $wgWhitelistRead ) ) {
876 return true;
877 }
878
879 # Compatibility with old settings
880 if( $this->getNamespace() == NS_MAIN ) {
881 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
882 return true;
883 }
884 }
885 }
886 return false;
887 }
888
889 /**
890 * Is this a talk page of some sort?
891 * @return bool
892 * @access public
893 */
894 function isTalkPage() {
895 return Namespace::isTalk( $this->getNamespace() );
896 }
897
898 /**
899 * Is this a .css or .js subpage of a user page?
900 * @return bool
901 * @access public
902 */
903 function isCssJsSubpage() {
904 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
905 }
906 /**
907 * Is this a .css subpage of a user page?
908 * @return bool
909 * @access public
910 */
911 function isCssSubpage() {
912 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
913 }
914 /**
915 * Is this a .js subpage of a user page?
916 * @return bool
917 * @access public
918 */
919 function isJsSubpage() {
920 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
921 }
922 /**
923 * Protect css/js subpages of user pages: can $wgUser edit
924 * this page?
925 *
926 * @return boolean
927 * @todo XXX: this might be better using restrictions
928 * @access public
929 */
930 function userCanEditCssJsSubpage() {
931 global $wgUser;
932 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
933 }
934
935 /**
936 * Loads a string into mRestrictions array
937 * @param string $res restrictions in string format
938 * @access public
939 */
940 function loadRestrictions( $res ) {
941 foreach( explode( ':', trim( $res ) ) as $restrict ) {
942 $temp = explode( '=', trim( $restrict ) );
943 if(count($temp) == 1) {
944 // old format should be treated as edit/move restriction
945 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
946 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
947 } else {
948 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
949 }
950 }
951 $this->mRestrictionsLoaded = true;
952 }
953
954 /**
955 * Accessor/initialisation for mRestrictions
956 * @param string $action action that permission needs to be checked for
957 * @return array the array of groups allowed to edit this article
958 * @access public
959 */
960 function getRestrictions($action) {
961 $id = $this->getArticleID();
962 if ( 0 == $id ) { return array(); }
963
964 if ( ! $this->mRestrictionsLoaded ) {
965 $dbr =& wfGetDB( DB_SLAVE );
966 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
967 $this->loadRestrictions( $res );
968 }
969 if( isset( $this->mRestrictions[$action] ) ) {
970 return $this->mRestrictions[$action];
971 }
972 return array();
973 }
974
975 /**
976 * Is there a version of this page in the deletion archive?
977 * @return int the number of archived revisions
978 * @access public
979 */
980 function isDeleted() {
981 $fname = 'Title::isDeleted';
982 $dbr =& wfGetDB( DB_SLAVE );
983 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
984 'ar_title' => $this->getDBkey() ), $fname );
985 return (int)$n;
986 }
987
988 /**
989 * Get the article ID for this Title from the link cache,
990 * adding it if necessary
991 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
992 * for update
993 * @return int the ID
994 * @access public
995 */
996 function getArticleID( $flags = 0 ) {
997 global $wgLinkCache;
998
999 if ( $flags & GAID_FOR_UPDATE ) {
1000 $oldUpdate = $wgLinkCache->forUpdate( true );
1001 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1002 $wgLinkCache->forUpdate( $oldUpdate );
1003 } else {
1004 if ( -1 == $this->mArticleID ) {
1005 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1006 }
1007 }
1008 return $this->mArticleID;
1009 }
1010
1011 /**
1012 * This clears some fields in this object, and clears any associated
1013 * keys in the "bad links" section of $wgLinkCache.
1014 *
1015 * - This is called from Article::insertNewArticle() to allow
1016 * loading of the new page_id. It's also called from
1017 * Article::doDeleteArticle()
1018 *
1019 * @param int $newid the new Article ID
1020 * @access public
1021 */
1022 function resetArticleID( $newid ) {
1023 global $wgLinkCache;
1024 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1025
1026 if ( 0 == $newid ) { $this->mArticleID = -1; }
1027 else { $this->mArticleID = $newid; }
1028 $this->mRestrictionsLoaded = false;
1029 $this->mRestrictions = array();
1030 }
1031
1032 /**
1033 * Updates page_touched for this page; called from LinksUpdate.php
1034 * @return bool true if the update succeded
1035 * @access public
1036 */
1037 function invalidateCache() {
1038 $now = wfTimestampNow();
1039 $dbw =& wfGetDB( DB_MASTER );
1040 $success = $dbw->update( 'page',
1041 array( /* SET */
1042 'page_touched' => $dbw->timestamp()
1043 ), array( /* WHERE */
1044 'page_namespace' => $this->getNamespace() ,
1045 'page_title' => $this->getDBkey()
1046 ), 'Title::invalidateCache'
1047 );
1048 return $success;
1049 }
1050
1051 /**
1052 * Prefix some arbitrary text with the namespace or interwiki prefix
1053 * of this object
1054 *
1055 * @param string $name the text
1056 * @return string the prefixed text
1057 * @access private
1058 */
1059 /* private */ function prefix( $name ) {
1060 global $wgContLang;
1061
1062 $p = '';
1063 if ( '' != $this->mInterwiki ) {
1064 $p = $this->mInterwiki . ':';
1065 }
1066 if ( 0 != $this->mNamespace ) {
1067 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1068 }
1069 return $p . $name;
1070 }
1071
1072 /**
1073 * Secure and split - main initialisation function for this object
1074 *
1075 * Assumes that mDbkeyform has been set, and is urldecoded
1076 * and uses underscores, but not otherwise munged. This function
1077 * removes illegal characters, splits off the interwiki and
1078 * namespace prefixes, sets the other forms, and canonicalizes
1079 * everything.
1080 * @return bool true on success
1081 * @access private
1082 */
1083 /* private */ function secureAndSplit() {
1084 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1085 $fname = 'Title::secureAndSplit';
1086 wfProfileIn( $fname );
1087
1088 # Initialisation
1089 static $rxTc = false;
1090 if( !$rxTc ) {
1091 # % is needed as well
1092 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1093 }
1094
1095 $this->mInterwiki = $this->mFragment = '';
1096 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1097
1098 # Clean up whitespace
1099 #
1100 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1101 $t = trim( $t, '_' );
1102
1103 if ( '' == $t ) {
1104 wfProfileOut( $fname );
1105 return false;
1106 }
1107
1108 global $wgUseLatin1;
1109 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1110 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1111 wfProfileOut( $fname );
1112 return false;
1113 }
1114
1115 $this->mDbkeyform = $t;
1116
1117 # Initial colon indicating main namespace
1118 if ( ':' == $t{0} ) {
1119 $r = substr( $t, 1 );
1120 $this->mNamespace = NS_MAIN;
1121 } else {
1122 # Namespace or interwiki prefix
1123 $firstPass = true;
1124 do {
1125 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1126 $p = $m[1];
1127 $lowerNs = strtolower( $p );
1128 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1129 # Canonical namespace
1130 $t = $m[2];
1131 $this->mNamespace = $ns;
1132 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1133 # Ordinary namespace
1134 $t = $m[2];
1135 $this->mNamespace = $ns;
1136 } elseif( $this->getInterwikiLink( $p ) ) {
1137 if( !$firstPass ) {
1138 # Can't make a local interwiki link to an interwiki link.
1139 # That's just crazy!
1140 wfProfileOut( $fname );
1141 return false;
1142 }
1143
1144 # Interwiki link
1145 $t = $m[2];
1146 $this->mInterwiki = $p;
1147
1148 # Redundant interwiki prefix to the local wiki
1149 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1150 if( $t == '' ) {
1151 # Can't have an empty self-link
1152 wfProfileOut( $fname );
1153 return false;
1154 }
1155 $this->mInterwiki = '';
1156 $firstPass = false;
1157 # Do another namespace split...
1158 continue;
1159 }
1160 }
1161 # If there's no recognized interwiki or namespace,
1162 # then let the colon expression be part of the title.
1163 }
1164 break;
1165 } while( true );
1166 $r = $t;
1167 }
1168
1169 # We already know that some pages won't be in the database!
1170 #
1171 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1172 $this->mArticleID = 0;
1173 }
1174 $f = strstr( $r, '#' );
1175 if ( false !== $f ) {
1176 $this->mFragment = substr( $f, 1 );
1177 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1178 # remove whitespace again: prevents "Foo_bar_#"
1179 # becoming "Foo_bar_"
1180 $r = preg_replace( '/_*$/', '', $r );
1181 }
1182
1183 # Reject illegal characters.
1184 #
1185 if( preg_match( $rxTc, $r ) ) {
1186 wfProfileOut( $fname );
1187 return false;
1188 }
1189
1190 /**
1191 * Pages with "/./" or "/../" appearing in the URLs will
1192 * often be unreachable due to the way web browsers deal
1193 * with 'relative' URLs. Forbid them explicitly.
1194 */
1195 if ( strpos( $r, '.' ) !== false &&
1196 ( $r === '.' || $r === '..' ||
1197 strpos( $r, './' ) === 0 ||
1198 strpos( $r, '../' ) === 0 ||
1199 strpos( $r, '/./' ) !== false ||
1200 strpos( $r, '/../' ) !== false ) )
1201 {
1202 wfProfileOut( $fname );
1203 return false;
1204 }
1205
1206 # We shouldn't need to query the DB for the size.
1207 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1208 if ( strlen( $r ) > 255 ) {
1209 wfProfileOut( $fname );
1210 return false;
1211 }
1212
1213 /**
1214 * Normally, all wiki links are forced to have
1215 * an initial capital letter so [[foo]] and [[Foo]]
1216 * point to the same place.
1217 *
1218 * Don't force it for interwikis, since the other
1219 * site might be case-sensitive.
1220 */
1221 if( $wgCapitalLinks && $this->mInterwiki == '') {
1222 $t = $wgContLang->ucfirst( $r );
1223 } else {
1224 $t = $r;
1225 }
1226
1227 /**
1228 * Can't make a link to a namespace alone...
1229 * "empty" local links can only be self-links
1230 * with a fragment identifier.
1231 */
1232 if( $t == '' &&
1233 $this->mInterwiki == '' &&
1234 $this->mNamespace != NS_MAIN ) {
1235 wfProfileOut( $fname );
1236 return false;
1237 }
1238
1239 if( $wgUseLatin1 && $this->mInterwiki != '' ) {
1240 # On a Latin-1 wiki, numbered character entities may have
1241 # left us with a mix of 8-bit and UTF-8 characters, and
1242 # some of those might be Windows-1252 special chars.
1243 # Normalize interwikis to pure UTF-8.
1244 $t = Title::mergeLatin1Utf8( $t );
1245 }
1246
1247 # Fill fields
1248 $this->mDbkeyform = $t;
1249 $this->mUrlform = wfUrlencode( $t );
1250
1251 $this->mTextform = str_replace( '_', ' ', $t );
1252
1253 wfProfileOut( $fname );
1254 return true;
1255 }
1256
1257 /**
1258 * Get a Title object associated with the talk page of this article
1259 * @return Title the object for the talk page
1260 * @access public
1261 */
1262 function getTalkPage() {
1263 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1264 }
1265
1266 /**
1267 * Get a title object associated with the subject page of this
1268 * talk page
1269 *
1270 * @return Title the object for the subject page
1271 * @access public
1272 */
1273 function getSubjectPage() {
1274 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1275 }
1276
1277 /**
1278 * Get an array of Title objects linking to this Title
1279 * - Also stores the IDs in the link cache.
1280 *
1281 * @param string $options may be FOR UPDATE
1282 * @return array the Title objects linking here
1283 * @access public
1284 */
1285 function getLinksTo( $options = '' ) {
1286 global $wgLinkCache;
1287 $id = $this->getArticleID();
1288
1289 if ( $options ) {
1290 $db =& wfGetDB( DB_MASTER );
1291 } else {
1292 $db =& wfGetDB( DB_SLAVE );
1293 }
1294 $page = $db->tableName( 'page' );
1295 $links = $db->tableName( 'links' );
1296
1297 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$links WHERE l_from=page_id AND l_to={$id} $options";
1298 $res = $db->query( $sql, 'Title::getLinksTo' );
1299 $retVal = array();
1300 if ( $db->numRows( $res ) ) {
1301 while ( $row = $db->fetchObject( $res ) ) {
1302 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1303 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1304 $retVal[] = $titleObj;
1305 }
1306 }
1307 }
1308 $db->freeResult( $res );
1309 return $retVal;
1310 }
1311
1312 /**
1313 * Get an array of Title objects linking to this non-existent title.
1314 * - Also stores the IDs in the link cache.
1315 *
1316 * @param string $options may be FOR UPDATE
1317 * @return array the Title objects linking here
1318 * @access public
1319 */
1320 function getBrokenLinksTo( $options = '' ) {
1321 global $wgLinkCache;
1322
1323 if ( $options ) {
1324 $db =& wfGetDB( DB_MASTER );
1325 } else {
1326 $db =& wfGetDB( DB_SLAVE );
1327 }
1328 $page = $db->tableName( 'page' );
1329 $brokenlinks = $db->tableName( 'brokenlinks' );
1330 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1331
1332 $sql = "SELECT page_namespace,page_title,page_id FROM $brokenlinks,$page " .
1333 "WHERE bl_from=page_id AND bl_to='$encTitle' $options";
1334 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1335 $retVal = array();
1336 if ( $db->numRows( $res ) ) {
1337 while ( $row = $db->fetchObject( $res ) ) {
1338 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
1339 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1340 $retVal[] = $titleObj;
1341 }
1342 }
1343 $db->freeResult( $res );
1344 return $retVal;
1345 }
1346
1347 /**
1348 * Get a list of URLs to purge from the Squid cache when this
1349 * page changes
1350 *
1351 * @return array the URLs
1352 * @access public
1353 */
1354 function getSquidURLs() {
1355 return array(
1356 $this->getInternalURL(),
1357 $this->getInternalURL( 'action=history' )
1358 );
1359 }
1360
1361 /**
1362 * Move this page without authentication
1363 * @param Title &$nt the new page Title
1364 * @access public
1365 */
1366 function moveNoAuth( &$nt ) {
1367 return $this->moveTo( $nt, false );
1368 }
1369
1370 /**
1371 * Move a title to a new location
1372 * @param Title &$nt the new title
1373 * @param bool $auth indicates whether $wgUser's permissions
1374 * should be checked
1375 * @return mixed true on success, message name on failure
1376 * @access public
1377 */
1378 function moveTo( &$nt, $auth = true ) {
1379 global $wgUser;
1380 if( !$this or !$nt ) {
1381 return 'badtitletext';
1382 }
1383
1384 $fname = 'Title::move';
1385 $oldid = $this->getArticleID();
1386 $newid = $nt->getArticleID();
1387
1388 if ( strlen( $nt->getDBkey() ) < 1 ) {
1389 return 'articleexists';
1390 }
1391 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1392 ( '' == $this->getDBkey() ) ||
1393 ( '' != $this->getInterwiki() ) ||
1394 ( !$oldid ) ||
1395 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1396 ( '' == $nt->getDBkey() ) ||
1397 ( '' != $nt->getInterwiki() ) ) {
1398 return 'badarticleerror';
1399 }
1400
1401 if ( $auth && (
1402 !$this->userCanEdit() || !$nt->userCanEdit() ||
1403 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1404 return 'protectedpage';
1405 }
1406
1407 # The move is allowed only if (1) the target doesn't exist, or
1408 # (2) the target is a redirect to the source, and has no history
1409 # (so we can undo bad moves right after they're done).
1410
1411 if ( 0 != $newid ) { # Target exists; check for validity
1412 if ( ! $this->isValidMoveTarget( $nt ) ) {
1413 return 'articleexists';
1414 }
1415 $this->moveOverExistingRedirect( $nt );
1416 } else { # Target didn't exist, do normal move.
1417 $this->moveToNewTitle( $nt, $newid );
1418 }
1419
1420 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1421
1422 $dbw =& wfGetDB( DB_MASTER );
1423 $categorylinks = $dbw->tableName( 'categorylinks' );
1424 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1425 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1426 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1427 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1428
1429 # Update watchlists
1430
1431 $oldnamespace = $this->getNamespace() & ~1;
1432 $newnamespace = $nt->getNamespace() & ~1;
1433 $oldtitle = $this->getDBkey();
1434 $newtitle = $nt->getDBkey();
1435
1436 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1437 WatchedItem::duplicateEntries( $this, $nt );
1438 }
1439
1440 # Update search engine
1441 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1442 $u->doUpdate();
1443 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1444 $u->doUpdate();
1445
1446 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1447 return true;
1448 }
1449
1450 /**
1451 * Move page to a title which is at present a redirect to the
1452 * source page
1453 *
1454 * @param Title &$nt the page to move to, which should currently
1455 * be a redirect
1456 * @access private
1457 */
1458 /* private */ function moveOverExistingRedirect( &$nt ) {
1459 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1460 $fname = 'Title::moveOverExistingRedirect';
1461 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1462
1463 $now = wfTimestampNow();
1464 $rand = wfRandom();
1465 $newid = $nt->getArticleID();
1466 $oldid = $this->getArticleID();
1467 $dbw =& wfGetDB( DB_MASTER );
1468 $links = $dbw->tableName( 'links' );
1469
1470 # Delete the old redirect. We don't save it to history since
1471 # by definition if we've got here it's rather uninteresting.
1472 # We have to remove it so that the next step doesn't trigger
1473 # a conflict on the unique namespace+title index...
1474 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1475
1476 # Change the name of the target page:
1477 $dbw->update( 'page',
1478 /* SET */ array(
1479 'page_touched' => $dbw->timestamp($now),
1480 'page_namespace' => $nt->getNamespace(),
1481 'page_title' => $nt->getDBkey()
1482 ),
1483 /* WHERE */ array( 'page_id' => $oldid ),
1484 $fname
1485 );
1486 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1487
1488 # Recreate the redirect, this time in the other direction.
1489 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1490 $redirectArticle = new Article( $this );
1491 $newid = $redirectArticle->insertOn( $dbw );
1492 $redirectRevision = new Revision( array(
1493 'page' => $newid,
1494 'comment' => $comment,
1495 'text' => $redirectText ) );
1496 $revid = $redirectRevision->insertOn( $dbw );
1497 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1498 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1499
1500 # Record in RC
1501 // Replaced by a log entry
1502 // RecentChange::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1503
1504 # Log the move
1505 $log = new LogPage( 'move' );
1506 $log->addEntry( 'move_redir', $this, '', array(1 => $nt->getText()) );
1507
1508 # Swap links
1509
1510 # Load titles and IDs
1511 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1512 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1513
1514 # Delete them all
1515 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1516 $dbw->query( $sql, $fname );
1517
1518 # Reinsert
1519 if ( count( $linksToOld ) || count( $linksToNew )) {
1520 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1521 $first = true;
1522
1523 # Insert links to old title
1524 foreach ( $linksToOld as $linkTitle ) {
1525 if ( $first ) {
1526 $first = false;
1527 } else {
1528 $sql .= ',';
1529 }
1530 $id = $linkTitle->getArticleID();
1531 $sql .= "($id,$newid)";
1532 }
1533
1534 # Insert links to new title
1535 foreach ( $linksToNew as $linkTitle ) {
1536 if ( $first ) {
1537 $first = false;
1538 } else {
1539 $sql .= ',';
1540 }
1541 $id = $linkTitle->getArticleID();
1542 $sql .= "($id, $oldid)";
1543 }
1544
1545 $dbw->query( $sql, DB_MASTER, $fname );
1546 }
1547
1548 # Now, we record the link from the redirect to the new title.
1549 # It should have no other outgoing links...
1550 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1551 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1552
1553 # Clear linkscc
1554 LinkCache::linksccClearLinksTo( $oldid );
1555 LinkCache::linksccClearLinksTo( $newid );
1556
1557 # Purge squid
1558 if ( $wgUseSquid ) {
1559 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1560 $u = new SquidUpdate( $urls );
1561 $u->doUpdate();
1562 }
1563 }
1564
1565 /**
1566 * Move page to non-existing title.
1567 * @param Title &$nt the new Title
1568 * @param int &$newid set to be the new article ID
1569 * @access private
1570 */
1571 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1572 global $wgUser, $wgLinkCache, $wgUseSquid;
1573 global $wgMwRedir;
1574 $fname = 'MovePageForm::moveToNewTitle';
1575 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1576
1577 $newid = $nt->getArticleID();
1578 $oldid = $this->getArticleID();
1579 $dbw =& wfGetDB( DB_MASTER );
1580 $now = $dbw->timestamp();
1581 wfSeedRandom();
1582 $rand = wfRandom();
1583
1584 # Rename cur entry
1585 $dbw->update( 'page',
1586 /* SET */ array(
1587 'page_touched' => $now,
1588 'page_namespace' => $nt->getNamespace(),
1589 'page_title' => $nt->getDBkey()
1590 ),
1591 /* WHERE */ array( 'page_id' => $oldid ),
1592 $fname
1593 );
1594
1595 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1596
1597 # Insert redirect
1598 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1599 $redirectArticle = new Article( $this );
1600 $newid = $redirectArticle->insertOn( $dbw );
1601 $redirectRevision = new Revision( array(
1602 'page' => $newid,
1603 'comment' => $comment,
1604 'text' => $redirectText ) );
1605 $revid = $redirectRevision->insertOn( $dbw );
1606 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1607 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1608
1609 # Record in RC
1610 // Replaced by a log entry
1611 // RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1612
1613 # Log the move
1614 $log = new LogPage( 'move' );
1615 $log->addEntry( 'move', $this, '', array(1 => $nt->getText()) );
1616
1617 # Purge squid and linkscc as per article creation
1618 Article::onArticleCreate( $nt );
1619
1620 # Any text links to the old title must be reassigned to the redirect
1621 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1622 LinkCache::linksccClearLinksTo( $oldid );
1623
1624 # Record the just-created redirect's linking to the page
1625 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1626
1627 # Non-existent target may have had broken links to it; these must
1628 # now be removed and made into good links.
1629 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1630 $update->fixBrokenLinks();
1631
1632 # Purge old title from squid
1633 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1634 $titles = $nt->getLinksTo();
1635 if ( $wgUseSquid ) {
1636 $urls = $this->getSquidURLs();
1637 foreach ( $titles as $linkTitle ) {
1638 $urls[] = $linkTitle->getInternalURL();
1639 }
1640 $u = new SquidUpdate( $urls );
1641 $u->doUpdate();
1642 }
1643 }
1644
1645 /**
1646 * Checks if $this can be moved to a given Title
1647 * - Selects for update, so don't call it unless you mean business
1648 *
1649 * @param Title &$nt the new title to check
1650 * @access public
1651 */
1652 function isValidMoveTarget( $nt ) {
1653
1654 $fname = 'Title::isValidMoveTarget';
1655 $dbw =& wfGetDB( DB_MASTER );
1656
1657 # Is it a redirect?
1658 $id = $nt->getArticleID();
1659 $obj = $dbw->selectRow( array( 'page', 'text') ,
1660 array( 'page_is_redirect','old_text' ),
1661 array( 'page_id' => $id, 'page_latest=old_id' ),
1662 $fname, 'FOR UPDATE' );
1663
1664 if ( !$obj || 0 == $obj->page_is_redirect ) {
1665 # Not a redirect
1666 return false;
1667 }
1668
1669 # Does the redirect point to the source?
1670 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1671 $redirTitle = Title::newFromText( $m[1] );
1672 if( !is_object( $redirTitle ) ||
1673 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1674 return false;
1675 }
1676 }
1677
1678 # Does the article have a history?
1679 $row = $dbw->selectRow( array( 'page', 'revision'),
1680 array( 'rev_id' ),
1681 array( 'page_namespace' => $nt->getNamespace(),
1682 'page_title' => $nt->getDBkey(),
1683 'page_id=rev_page AND page_latest != rev_id'
1684 ), $fname, 'FOR UPDATE'
1685 );
1686
1687 # Return true if there was no history
1688 return $row === false;
1689 }
1690
1691 /**
1692 * Create a redirect; fails if the title already exists; does
1693 * not notify RC
1694 *
1695 * @param Title $dest the destination of the redirect
1696 * @param string $comment the comment string describing the move
1697 * @return bool true on success
1698 * @access public
1699 */
1700 function createRedirect( $dest, $comment ) {
1701 global $wgUser;
1702 if ( $this->getArticleID() ) {
1703 return false;
1704 }
1705
1706 $fname = 'Title::createRedirect';
1707 $dbw =& wfGetDB( DB_MASTER );
1708
1709 $article = new Article( $this );
1710 $newid = $article->insertOn( $dbw );
1711 $revision = new Revision( array(
1712 'page' => $newid,
1713 'comment' => $comment,
1714 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1715 ) );
1716 $revisionId = $revision->insertOn( $dbw );
1717 $article->updateRevisionOn( $dbw, $revision, 0 );
1718
1719 # Link table
1720 if ( $dest->getArticleID() ) {
1721 $dbw->insert( 'links',
1722 array(
1723 'l_to' => $dest->getArticleID(),
1724 'l_from' => $newid
1725 ), $fname
1726 );
1727 } else {
1728 $dbw->insert( 'brokenlinks',
1729 array(
1730 'bl_to' => $dest->getPrefixedDBkey(),
1731 'bl_from' => $newid
1732 ), $fname
1733 );
1734 }
1735
1736 Article::onArticleCreate( $this );
1737 return true;
1738 }
1739
1740 /**
1741 * Get categories to which this Title belongs and return an array of
1742 * categories' names.
1743 *
1744 * @return array an array of parents in the form:
1745 * $parent => $currentarticle
1746 * @access public
1747 */
1748 function getParentCategories() {
1749 global $wgContLang,$wgUser;
1750
1751 $titlekey = $this->getArticleId();
1752 $sk =& $wgUser->getSkin();
1753 $parents = array();
1754 $dbr =& wfGetDB( DB_SLAVE );
1755 $categorylinks = $dbr->tableName( 'categorylinks' );
1756
1757 # NEW SQL
1758 $sql = "SELECT * FROM $categorylinks"
1759 ." WHERE cl_from='$titlekey'"
1760 ." AND cl_from <> '0'"
1761 ." ORDER BY cl_sortkey";
1762
1763 $res = $dbr->query ( $sql ) ;
1764
1765 if($dbr->numRows($res) > 0) {
1766 while ( $x = $dbr->fetchObject ( $res ) )
1767 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1768 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1769 $dbr->freeResult ( $res ) ;
1770 } else {
1771 $data = '';
1772 }
1773 return $data;
1774 }
1775
1776 /**
1777 * Get a tree of parent categories
1778 * @param array $children an array with the children in the keys, to check for circular refs
1779 * @return array
1780 * @access public
1781 */
1782 function getParentCategoryTree( $children = array() ) {
1783 $parents = $this->getParentCategories();
1784
1785 if($parents != '') {
1786 foreach($parents as $parent => $current)
1787 {
1788 if ( array_key_exists( $parent, $children ) ) {
1789 # Circular reference
1790 $stack[$parent] = array();
1791 } else {
1792 $nt = Title::newFromText($parent);
1793 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1794 }
1795 }
1796 return $stack;
1797 } else {
1798 return array();
1799 }
1800 }
1801
1802
1803 /**
1804 * Get an associative array for selecting this title from
1805 * the "cur" table
1806 *
1807 * @return array
1808 * @access public
1809 */
1810 function curCond() {
1811 wfDebugDieBacktrace( 'curCond called' );
1812 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1813 }
1814
1815 /**
1816 * Get an associative array for selecting this title from the
1817 * "old" table
1818 *
1819 * @return array
1820 * @access public
1821 */
1822 function oldCond() {
1823 wfDebugDieBacktrace( 'oldCond called' );
1824 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1825 }
1826
1827 /**
1828 * Get the revision ID of the previous revision
1829 *
1830 * @param integer $revision Revision ID. Get the revision that was before this one.
1831 * @return interger $oldrevision|false
1832 */
1833 function getPreviousRevisionID( $revision ) {
1834 $dbr =& wfGetDB( DB_SLAVE );
1835 return $dbr->selectField( 'revision', 'rev_id',
1836 'rev_page=' . IntVal( $this->getArticleId() ) .
1837 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1838 }
1839
1840 /**
1841 * Get the revision ID of the next revision
1842 *
1843 * @param integer $revision Revision ID. Get the revision that was after this one.
1844 * @return interger $oldrevision|false
1845 */
1846 function getNextRevisionID( $revision ) {
1847 $dbr =& wfGetDB( DB_SLAVE );
1848 return $dbr->selectField( 'revision', 'rev_id',
1849 'rev_page=' . IntVal( $this->getArticleId() ) .
1850 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1851 }
1852
1853 /**
1854 * Compare with another title.
1855 *
1856 * @param Title $title
1857 * @return bool
1858 */
1859 function equals( &$title ) {
1860 return $this->getInterwiki() == $title->getInterwiki()
1861 && $this->getNamespace() == $title->getNamespace()
1862 && $this->getDbkey() == $title->getDbkey();
1863 }
1864
1865 /**
1866 * Convert Windows-1252 extended codepoints to their real Unicode points.
1867 * @param int $codepoint
1868 * @return int
1869 * @access private
1870 */
1871 function cp1252toUnicode( $codepoint ) {
1872 # Mappings from:
1873 # http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
1874 static $cp1252 = array(
1875 0x80 => 0x20AC, #EURO SIGN
1876 0x81 => UNICODE_REPLACEMENT,
1877 0x82 => 0x201A, #SINGLE LOW-9 QUOTATION MARK
1878 0x83 => 0x0192, #LATIN SMALL LETTER F WITH HOOK
1879 0x84 => 0x201E, #DOUBLE LOW-9 QUOTATION MARK
1880 0x85 => 0x2026, #HORIZONTAL ELLIPSIS
1881 0x86 => 0x2020, #DAGGER
1882 0x87 => 0x2021, #DOUBLE DAGGER
1883 0x88 => 0x02C6, #MODIFIER LETTER CIRCUMFLEX ACCENT
1884 0x89 => 0x2030, #PER MILLE SIGN
1885 0x8A => 0x0160, #LATIN CAPITAL LETTER S WITH CARON
1886 0x8B => 0x2039, #SINGLE LEFT-POINTING ANGLE QUOTATION MARK
1887 0x8C => 0x0152, #LATIN CAPITAL LIGATURE OE
1888 0x8D => UNICODE_REPLACEMENT,
1889 0x8E => 0x017D, #LATIN CAPITAL LETTER Z WITH CARON
1890 0x8F => UNICODE_REPLACEMENT,
1891 0x90 => UNICODE_REPLACEMENT,
1892 0x91 => 0x2018, #LEFT SINGLE QUOTATION MARK
1893 0x92 => 0x2019, #RIGHT SINGLE QUOTATION MARK
1894 0x93 => 0x201C, #LEFT DOUBLE QUOTATION MARK
1895 0x94 => 0x201D, #RIGHT DOUBLE QUOTATION MARK
1896 0x95 => 0x2022, #BULLET
1897 0x96 => 0x2013, #EN DASH
1898 0x97 => 0x2014, #EM DASH
1899 0x98 => 0x02DC, #SMALL TILDE
1900 0x99 => 0x2122, #TRADE MARK SIGN
1901 0x9A => 0x0161, #LATIN SMALL LETTER S WITH CARON
1902 0x9B => 0x203A, #SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
1903 0x9C => 0x0153, #LATIN SMALL LIGATURE OE
1904 0x9D => UNICODE_REPLACEMENT,
1905 0x9E => 0x017E, #LATIN SMALL LETTER Z WITH CARON
1906 0x9F => 0x0178, #LATIN CAPITAL LETTER Y WITH DIAERESIS
1907 );
1908 return isset( $cp1252[$codepoint] )
1909 ? $cp1252[$codepoint]
1910 : $codepoint;
1911 }
1912
1913 /**
1914 * HACKHACKHACK
1915 * Take a string containing a mix of CP1252 characters and UTF-8 and try
1916 * to convert it completely to UTF-8.
1917 *
1918 * @param string $string
1919 * @return string
1920 * @access private
1921 */
1922 function mergeLatin1Utf8( $string ) {
1923 return preg_replace_callback(
1924 # Windows CP1252 extends ISO-8859-1 by putting extra characters
1925 # into the high control chars area. We have to convert these
1926 # to their proper Unicode counterparts.
1927 '/([\x80-\x9f])/u',
1928 create_function( '$matches',
1929 'return codepointToUtf8(
1930 Title::cp1252toUnicode(
1931 utf8ToCodepoint( $matches[1] ) ) );' ),
1932 preg_replace_callback(
1933 # Up-convert everything from 8-bit to UTF-8, then
1934 # filter the valid-looking UTF-8 back from the
1935 # double-converted form.
1936 '/((?:[\xc0-\xdf][\x80-\xbf]
1937 |[\xe0-\xef][\x80-\xbf]{2}
1938 |[\xf0-\xf7][\x80-\xbf]{3})+)/ux',
1939 create_function( '$matches',
1940 'return utf8_decode( $matches[1] );' ),
1941 utf8_encode( $string ) ) );
1942 }
1943
1944 }
1945 ?>