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