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