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