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