Merge SCHEMA_WORK into HEAD. Lots of changes, some things are probably broken:
[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 page row is requested
169 * but not used for anything else
170 * @param int $id the page_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( 'page', array( 'page_namespace', 'page_title' ),
178 array( 'page_id' => $id ), $fname );
179 if ( $row !== false ) {
180 $title = Title::makeTitle( $row->page_namespace, $row->page_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 page_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( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
289 if ( $s === false ) { return NULL; }
290
291 $n = Title::makeName( $s->page_namespace, $s->page_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 page_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 $page = $dbw->tableName( 'page' );
457 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_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( 'page', 'page_restrictions', 'page_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 page_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 page_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( 'page',
1004 array( /* SET */
1005 'page_touched' => $dbw->timestamp()
1006 ), array( /* WHERE */
1007 'page_namespace' => $this->getNamespace() ,
1008 'page_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( 'page', 'page_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 $page = $db->tableName( 'page' );
1237 $links = $db->tableName( 'links' );
1238
1239 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$links WHERE l_from=page_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->page_namespace, $row->page_title ) ) {
1245 $wgLinkCache->addGoodLink( $row->page_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 $page = $db->tableName( 'page' );
1271 $brokenlinks = $db->tableName( 'brokenlinks' );
1272 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1273
1274 $sql = "SELECT page_namespace,page_title,page_id FROM $brokenlinks,$page " .
1275 "WHERE bl_from=page_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->page_namespace, $row->page_title );
1281 $wgLinkCache->addGoodLink( $row->page_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 $rand = wfRandom();
1404 $newid = $nt->getArticleID();
1405 $oldid = $this->getArticleID();
1406 $dbw =& wfGetDB( DB_MASTER );
1407 $links = $dbw->tableName( 'links' );
1408
1409 # Delete the old redirect. We don't save it to history since
1410 # by definition if we've got here it's rather uninteresting.
1411 # We have to remove it so that the next step doesn't trigger
1412 # a conflict on the unique namespace+title index...
1413 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1414
1415 # Change the name of the target page:
1416 $dbw->update( 'page',
1417 /* SET */ array(
1418 'page_touched' => $dbw->timestamp($now),
1419 'page_namespace' => $nt->getNamespace(),
1420 'page_title' => $nt->getDBkey()
1421 ),
1422 /* WHERE */ array( 'page_id' => $oldid ),
1423 $fname
1424 );
1425 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1426
1427 # Recreate the redirect, this time in the other direction.
1428 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1429 $dbw->insert( 'revision', array(
1430 'rev_id' => $dbw->nextSequenceValue('rev_rev_id_seq'),
1431 'rev_comment' => $comment,
1432 'rev_user' => $wgUser->getID(),
1433 'rev_user_text' => $wgUser->getName(),
1434 'rev_timestamp' => $now,
1435 'inverse_timestamp' => $won ), $fname
1436 );
1437 $revid = $dbw->insertId();
1438 $dbw->insert( 'text', array(
1439 'old_id' => $revid,
1440 'old_flags' => '',
1441 'old_text' => $redirectText,
1442 ), $fname
1443 );
1444 $dbw->insert( 'page', array(
1445 'page_id' => $dbw->nextSequenceValue('page_page_id_seq'),
1446 'page_namespace' => $this->getNamespace(),
1447 'page_title' => $this->getDBkey(),
1448 'page_touched' => $now,
1449 'page_is_redirect' => 1,
1450 'page_random' => $rand,
1451 'page_is_new' => 1,
1452 'page_latest' => $revid), $fname
1453 );
1454 $newid = $dbw->insertId();
1455 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
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 global $wgMwRedir;
1525 $fname = 'MovePageForm::moveToNewTitle';
1526 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1527
1528 $newid = $nt->getArticleID();
1529 $oldid = $this->getArticleID();
1530 $dbw =& wfGetDB( DB_MASTER );
1531 $now = $dbw->timestamp();
1532 $won = wfInvertTimestamp( wfTimestamp(TS_MW,$now) );
1533 wfSeedRandom();
1534 $rand = wfRandom();
1535
1536 # Rename cur entry
1537 $dbw->update( 'page',
1538 /* SET */ array(
1539 'page_touched' => $now,
1540 'page_namespace' => $nt->getNamespace(),
1541 'page_title' => $nt->getDBkey()
1542 ),
1543 /* WHERE */ array( 'page_id' => $oldid ),
1544 $fname
1545 );
1546
1547 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1548
1549 # Insert redirect
1550 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1551 $dbw->insert( 'revision', array(
1552 'rev_id' => $dbw->nextSequenceValue('rev_rev_id_seq'),
1553 'rev_comment' => $comment,
1554 'rev_user' => $wgUser->getID(),
1555 'rev_user_text' => $wgUser->getName(),
1556 'rev_timestamp' => $now,
1557 'inverse_timestamp' => $won ), $fname
1558 );
1559 $revid = $dbw->insertId();
1560 $dbw->insert( 'text', array(
1561 'old_id' => $revid,
1562 'old_flags' => '',
1563 'old_text' => $redirectText
1564 ), $fname
1565 );
1566 $dbw->insert( 'page', array(
1567 'page_id' => $dbw->nextSequenceValue('page_page_id_seq'),
1568 'page_namespace' => $this->getNamespace(),
1569 'page_title' => $this->getDBkey(),
1570 'page_touched' => $now,
1571 'page_is_redirect' => 1,
1572 'page_random' => $rand,
1573 'page_is_new' => 1,
1574 'page_latest' => $revid), $fname
1575 );
1576 $newid = $dbw->insertId();
1577 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1578
1579 # Record in RC
1580 RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1581
1582 # Purge squid and linkscc as per article creation
1583 Article::onArticleCreate( $nt );
1584
1585 # Any text links to the old title must be reassigned to the redirect
1586 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1587 LinkCache::linksccClearLinksTo( $oldid );
1588
1589 # Record the just-created redirect's linking to the page
1590 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1591
1592 # Non-existent target may have had broken links to it; these must
1593 # now be removed and made into good links.
1594 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1595 $update->fixBrokenLinks();
1596
1597 # Purge old title from squid
1598 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1599 $titles = $nt->getLinksTo();
1600 if ( $wgUseSquid ) {
1601 $urls = $this->getSquidURLs();
1602 foreach ( $titles as $linkTitle ) {
1603 $urls[] = $linkTitle->getInternalURL();
1604 }
1605 $u = new SquidUpdate( $urls );
1606 $u->doUpdate();
1607 }
1608 }
1609
1610 /**
1611 * Checks if $this can be moved to a given Title
1612 * - Selects for update, so don't call it unless you mean business
1613 *
1614 * @param Title &$nt the new title to check
1615 * @access public
1616 */
1617 function isValidMoveTarget( $nt ) {
1618
1619 $fname = 'Title::isValidMoveTarget';
1620 $dbw =& wfGetDB( DB_MASTER );
1621
1622 # Is it a redirect?
1623 $id = $nt->getArticleID();
1624 $obj = $dbw->selectRow( array( 'page', 'text') ,
1625 array( 'page_is_redirect','old_text' ),
1626 array( 'page_id' => $id, 'page_latest=old_id' ),
1627 $fname, 'FOR UPDATE' );
1628
1629 if ( !$obj || 0 == $obj->page_is_redirect ) {
1630 # Not a redirect
1631 return false;
1632 }
1633
1634 # Does the redirect point to the source?
1635 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1636 $redirTitle = Title::newFromText( $m[1] );
1637 if( !is_object( $redirTitle ) ||
1638 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1639 return false;
1640 }
1641 }
1642
1643 # Does the article have a history?
1644 $row = $dbw->selectRow( array( 'page', 'revision'),
1645 array( 'rev_id' ),
1646 array( 'page_namespace' => $nt->getNamespace(),
1647 'page_title' => $nt->getDBkey(),
1648 'page_id=rev_page AND page_latest != rev_id'
1649 ), $fname, 'FOR UPDATE'
1650 );
1651
1652 # Return true if there was no history
1653 return $row === false;
1654 }
1655
1656 /**
1657 * Create a redirect; fails if the title already exists; does
1658 * not notify RC
1659 *
1660 * @param Title $dest the destination of the redirect
1661 * @param string $comment the comment string describing the move
1662 * @return bool true on success
1663 * @access public
1664 */
1665 function createRedirect( $dest, $comment ) {
1666 global $wgUser;
1667 if ( $this->getArticleID() ) {
1668 return false;
1669 }
1670
1671 $fname = 'Title::createRedirect';
1672 $dbw =& wfGetDB( DB_MASTER );
1673 $now = wfTimestampNow();
1674 $won = wfInvertTimestamp( $now );
1675
1676 $seqVal = $dbw->nextSequenceValue( 'page_page_id_seq' );
1677 $dbw->insert( 'page', array(
1678 'page_id' => $seqVal,
1679 'page_namespace' => $this->getNamespace(),
1680 'page_title' => $this->getDBkey(),
1681 'page_touched' => $now,
1682 'page_is_redirect' => 1,
1683 'page_is_new' => 1,
1684 'page_latest' => NULL,
1685 ), $fname );
1686 $newid = $dbw->insertId();
1687
1688 $seqVal = $dbw->nextSequenceValue( 'text_old_id_seq' );
1689 $dbw->insert( 'text', array(
1690 'old_id' => $seqVal,
1691 'old_flags' => '',
1692 'old_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1693 ), $fname );
1694 $revisionId = $dbw->insertId();
1695
1696 $dbw->insert( 'revision', array(
1697 'rev_id' => $seqVal,
1698 'rev_page' => $newid,
1699 'rev_comment' => $comment,
1700 'rev_user' => $wgUser->getID(),
1701 'rev_user_text' => $wgUser->getName(),
1702 'rev_timestamp' => $now,
1703 'inverse_timestamp' => $won,
1704 ), $fname );
1705
1706 $dbw->update( 'page',
1707 /* SET */ array( 'page_latest' => $revisionId ),
1708 /* WHERE */ array( 'page_id' => $newid ),
1709 $fname );
1710 $this->resetArticleID( $newid );
1711
1712 # Link table
1713 if ( $dest->getArticleID() ) {
1714 $dbw->insert( 'links',
1715 array(
1716 'l_to' => $dest->getArticleID(),
1717 'l_from' => $newid
1718 ), $fname
1719 );
1720 } else {
1721 $dbw->insert( 'brokenlinks',
1722 array(
1723 'bl_to' => $dest->getPrefixedDBkey(),
1724 'bl_from' => $newid
1725 ), $fname
1726 );
1727 }
1728
1729 Article::onArticleCreate( $this );
1730 return true;
1731 }
1732
1733 /**
1734 * Get categories to which this Title belongs and return an array of
1735 * categories' names.
1736 *
1737 * @return array an array of parents in the form:
1738 * $parent => $currentarticle
1739 * @access public
1740 */
1741 function getParentCategories() {
1742 global $wgContLang,$wgUser;
1743
1744 $titlekey = $this->getArticleId();
1745 $sk =& $wgUser->getSkin();
1746 $parents = array();
1747 $dbr =& wfGetDB( DB_SLAVE );
1748 $categorylinks = $dbr->tableName( 'categorylinks' );
1749
1750 # NEW SQL
1751 $sql = "SELECT * FROM $categorylinks"
1752 ." WHERE cl_from='$titlekey'"
1753 ." AND cl_from <> '0'"
1754 ." ORDER BY cl_sortkey";
1755
1756 $res = $dbr->query ( $sql ) ;
1757
1758 if($dbr->numRows($res) > 0) {
1759 while ( $x = $dbr->fetchObject ( $res ) )
1760 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1761 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1762 $dbr->freeResult ( $res ) ;
1763 } else {
1764 $data = '';
1765 }
1766 return $data;
1767 }
1768
1769 /**
1770 * Get a tree of parent categories
1771 * @param array $children an array with the children in the keys, to check for circular refs
1772 * @return array
1773 * @access public
1774 */
1775 function getParentCategoryTree( $children = array() ) {
1776 $parents = $this->getParentCategories();
1777
1778 if($parents != '') {
1779 foreach($parents as $parent => $current)
1780 {
1781 if ( array_key_exists( $parent, $children ) ) {
1782 # Circular reference
1783 $stack[$parent] = array();
1784 } else {
1785 $nt = Title::newFromText($parent);
1786 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1787 }
1788 }
1789 return $stack;
1790 } else {
1791 return array();
1792 }
1793 }
1794
1795
1796 /**
1797 * Get an associative array for selecting this title from
1798 * the "cur" table
1799 *
1800 * @return array
1801 * @access public
1802 */
1803 function curCond() {
1804 wfDebugDieBacktrace( 'curCond called' );
1805 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1806 }
1807
1808 /**
1809 * Get an associative array for selecting this title from the
1810 * "old" table
1811 *
1812 * @return array
1813 * @access public
1814 */
1815 function oldCond() {
1816 wfDebugDieBacktrace( 'oldCond called' );
1817 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1818 }
1819
1820 /**
1821 * Get the revision ID of the previous revision
1822 *
1823 * @param integer $revision Revision ID. Get the revision that was before this one.
1824 * @return interger $oldrevision|false
1825 */
1826 function getPreviousRevisionID( $revision ) {
1827 $dbr =& wfGetDB( DB_SLAVE );
1828 return $dbr->selectField( 'revision', 'rev_id',
1829 'rev_page=' . IntVal( $this->getArticleId() ) .
1830 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1831 }
1832
1833 /**
1834 * Get the revision ID of the next revision
1835 *
1836 * @param integer $revision Revision ID. Get the revision that was after this one.
1837 * @return interger $oldrevision|false
1838 */
1839 function getNextRevisionID( $revision ) {
1840 $dbr =& wfGetDB( DB_SLAVE );
1841 return $dbr->selectField( 'revision', 'rev_id',
1842 'rev_page=' . IntVal( $this->getArticleId() ) .
1843 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1844 }
1845
1846 }
1847 ?>