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