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