Removed uncalled method Title::getURL whose only purpose was to tell
[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 * Set the namespace index
471 * @param int $n the namespace index, one of the NS_xxxx constants
472 * @access public
473 */
474 function setNamespace( $n ) { $this->mNamespace = IntVal( $n ); }
475 /**
476 * Get the interwiki prefix (or null string)
477 * @return string
478 * @access public
479 */
480 function getInterwiki() { return $this->mInterwiki; }
481 /**
482 * Get the Title fragment (i.e. the bit after the #)
483 * @return string
484 * @access public
485 */
486 function getFragment() { return $this->mFragment; }
487 /**
488 * Get the default namespace index, for when there is no namespace
489 * @return int
490 * @access public
491 */
492 function getDefaultNamespace() { return $this->mDefaultNamespace; }
493
494 /**
495 * Get title for search index
496 * @return string a stripped-down title string ready for the
497 * search index
498 */
499 function getIndexTitle() {
500 return Title::indexTitle( $this->mNamespace, $this->mTextform );
501 }
502
503 /**
504 * Get the prefixed database key form
505 * @return string the prefixed title, with underscores and
506 * any interwiki and namespace prefixes
507 * @access public
508 */
509 function getPrefixedDBkey() {
510 $s = $this->prefix( $this->mDbkeyform );
511 $s = str_replace( ' ', '_', $s );
512 return $s;
513 }
514
515 /**
516 * Get the prefixed title with spaces.
517 * This is the form usually used for display
518 * @return string the prefixed title, with spaces
519 * @access public
520 */
521 function getPrefixedText() {
522 global $wgContLang;
523 if ( empty( $this->mPrefixedText ) ) {
524 $s = $this->prefix( $this->mTextform );
525 $s = str_replace( '_', ' ', $s );
526 $this->mPrefixedText = $s;
527 }
528 return $this->mPrefixedText;
529 }
530
531 /**
532 * Get the prefixed title with spaces, plus any fragment
533 * (part beginning with '#')
534 * @return string the prefixed title, with spaces and
535 * the fragment, including '#'
536 * @access public
537 */
538 function getFullText() {
539 global $wgContLang;
540 $text = $this->getPrefixedText();
541 if( '' != $this->mFragment ) {
542 $text .= '#' . $this->mFragment;
543 }
544 return $text;
545 }
546
547 /**
548 * Get a URL-encoded title (not an actual URL) including interwiki
549 * @return string the URL-encoded form
550 * @access public
551 */
552 function getPrefixedURL() {
553 $s = $this->prefix( $this->mDbkeyform );
554 $s = str_replace( ' ', '_', $s );
555
556 $s = wfUrlencode ( $s ) ;
557
558 # Cleaning up URL to make it look nice -- is this safe?
559 $s = preg_replace( '/%3[Aa]/', ':', $s );
560 $s = preg_replace( '/%2[Ff]/', '/', $s );
561 $s = str_replace( '%28', '(', $s );
562 $s = str_replace( '%29', ')', $s );
563
564 return $s;
565 }
566
567 /**
568 * Get a real URL referring to this title, with interwiki link and
569 * fragment
570 *
571 * @param string $query an optional query string, not used
572 * for interwiki links
573 * @return string the URL
574 * @access public
575 */
576 function getFullURL( $query = '' ) {
577 global $wgContLang, $wgArticlePath, $wgServer, $wgScript;
578
579 if ( '' == $this->mInterwiki ) {
580 $p = $wgArticlePath;
581 return $wgServer . $this->getLocalUrl( $query );
582 } else {
583 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
584 $namespace = $wgContLang->getNsText( $this->mNamespace );
585 if ( '' != $namespace ) {
586 # Can this actually happen? Interwikis shouldn't be parsed.
587 $namepace .= ':';
588 }
589 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
590 if ( '' != $this->mFragment ) {
591 $url .= '#' . $this->mFragment;
592 }
593 return $url;
594 }
595 }
596
597 /**
598 * Get a URL with no fragment or server name
599 * @param string $query an optional query string; if not specified,
600 * $wgArticlePath will be used.
601 * @return string the URL
602 * @access public
603 */
604 function getLocalURL( $query = '' ) {
605 global $wgLang, $wgArticlePath, $wgScript;
606
607 if ( $this->isExternal() ) {
608 return $this->getFullURL();
609 }
610
611 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
612 if ( $query == '' ) {
613 $url = str_replace( '$1', $dbkey, $wgArticlePath );
614 } else {
615 if ( $query == '-' ) {
616 $query = '';
617 }
618 $url = "{$wgScript}?title={$dbkey}&{$query}";
619 }
620 return $url;
621 }
622
623 /**
624 * Get an HTML-escaped version of the URL form, suitable for
625 * using in a link, without a server name or fragment
626 * @param string $query an optional query string
627 * @return string the URL
628 * @access public
629 */
630 function escapeLocalURL( $query = '' ) {
631 return htmlspecialchars( $this->getLocalURL( $query ) );
632 }
633
634 /**
635 * Get an HTML-escaped version of the URL form, suitable for
636 * using in a link, including the server name and fragment
637 *
638 * @return string the URL
639 * @param string $query an optional query string
640 * @access public
641 */
642 function escapeFullURL( $query = '' ) {
643 return htmlspecialchars( $this->getFullURL( $query ) );
644 }
645
646 /**
647 * Get the URL form for an internal link.
648 * - Used in various Squid-related code, in case we have a different
649 * internal hostname for the server from the exposed one.
650 *
651 * @param string $query an optional query string
652 * @return string the URL
653 * @access public
654 */
655 function getInternalURL( $query = '' ) {
656 global $wgInternalServer;
657 return $wgInternalServer . $this->getLocalURL( $query );
658 }
659
660 /**
661 * Get the edit URL for this Title
662 * @return string the URL, or a null string if this is an
663 * interwiki link
664 * @access public
665 */
666 function getEditURL() {
667 global $wgServer, $wgScript;
668
669 if ( '' != $this->mInterwiki ) { return ''; }
670 $s = $this->getLocalURL( 'action=edit' );
671
672 return $s;
673 }
674
675 /**
676 * Get the HTML-escaped displayable text form.
677 * Used for the title field in <a> tags.
678 * @return string the text, including any prefixes
679 * @access public
680 */
681 function getEscapedText() {
682 return htmlspecialchars( $this->getPrefixedText() );
683 }
684
685 /**
686 * Is this Title interwiki?
687 * @return boolean
688 * @access public
689 */
690 function isExternal() { return ( '' != $this->mInterwiki ); }
691
692 /**
693 * Does the title correspond to a protected article?
694 * @return boolean
695 * @access public
696 */
697 function isProtected() {
698 if ( -1 == $this->mNamespace ) { return true; }
699 $a = $this->getRestrictions();
700 if ( in_array( 'sysop', $a ) ) { return true; }
701 return false;
702 }
703
704 /**
705 * Is the page a log page, i.e. one where the history is messed up by
706 * LogPage.php? This used to be used for suppressing diff links in
707 * recent changes, but now that's done by setting a flag in the
708 * recentchanges table. Hence, this probably is no longer used.
709 *
710 * @deprecated
711 * @access public
712 */
713 function isLog() {
714 if ( $this->mNamespace != Namespace::getWikipedia() ) {
715 return false;
716 }
717 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform ) ) ||
718 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform ) ) ) {
719 return true;
720 }
721 return false;
722 }
723
724 /**
725 * Is $wgUser is watching this page?
726 * @return boolean
727 * @access public
728 */
729 function userIsWatching() {
730 global $wgUser;
731
732 if ( -1 == $this->mNamespace ) { return false; }
733 if ( 0 == $wgUser->getID() ) { return false; }
734
735 return $wgUser->isWatched( $this );
736 }
737
738 /**
739 * Can $wgUser edit this page?
740 * @return boolean
741 * @access public
742 */
743 function userCanEdit() {
744 global $wgUser;
745 if( NS_SPECIAL == $this->mNamespace ) {
746 return false;
747 }
748 if( NS_MEDIAWIKI == $this->mNamespace &&
749 !$wgUser->isAllowed('editinterface') ) {
750 return false;
751 }
752 if( $this->mDbkeyform == '_' ) {
753 # FIXME: Is this necessary? Shouldn't be allowed anyway...
754 return false;
755 }
756
757 # protect global styles and js
758 if ( NS_MEDIAWIKI == $this->mNamespace
759 && preg_match("/\\.(css|js)$/", $this->mTextform )
760 && !$wgUser->isAllowed('editinterface') ) {
761 return false;
762 }
763
764 # protect css/js subpages of user pages
765 # XXX: this might be better using restrictions
766 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
767 if( NS_USER == $this->mNamespace
768 && preg_match("/\\.(css|js)$/", $this->mTextform )
769 && !$wgUser->isAllowed('editinterface')
770 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
771 return false;
772 }
773
774 foreach( $this->getRestrictions() as $right ) {
775 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
776 return false;
777 }
778 }
779 return true;
780 }
781
782 /**
783 * Can $wgUser read this page?
784 * @return boolean
785 * @access public
786 */
787 function userCanRead() {
788 global $wgUser;
789
790 if( $wgUser->isAllowed('read') ) {
791 return true;
792 } else {
793 global $wgWhitelistRead;
794
795 /** If anon users can create an account,
796 they need to reach the login page first! */
797 if( $wgUser->isAllowed( 'createaccount' )
798 && $this->mId == NS_SPECIAL
799 && $this->getText() == 'Userlogin' ) {
800 return true;
801 }
802
803 /** some pages are explicitly allowed */
804 $name = $this->getPrefixedText();
805 if( in_array( $name, $wgWhitelistRead ) ) {
806 return true;
807 }
808
809 # Compatibility with old settings
810 if( $this->getNamespace() == NS_MAIN ) {
811 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
812 return true;
813 }
814 }
815 }
816 return false;
817 }
818
819 /**
820 * Is this a .css or .js subpage of a user page?
821 * @return bool
822 * @access public
823 */
824 function isCssJsSubpage() {
825 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
826 }
827 /**
828 * Is this a .css subpage of a user page?
829 * @return bool
830 * @access public
831 */
832 function isCssSubpage() {
833 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
834 }
835 /**
836 * Is this a .js subpage of a user page?
837 * @return bool
838 * @access public
839 */
840 function isJsSubpage() {
841 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
842 }
843 /**
844 * Protect css/js subpages of user pages: can $wgUser edit
845 * this page?
846 *
847 * @return boolean
848 * @todo XXX: this might be better using restrictions
849 * @access public
850 */
851 function userCanEditCssJsSubpage() {
852 global $wgUser;
853 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
854 }
855
856 /**
857 * Accessor/initialisation for mRestrictions
858 * @return array the array of groups allowed to edit this article
859 * @access public
860 */
861 function getRestrictions() {
862 $id = $this->getArticleID();
863 if ( 0 == $id ) { return array(); }
864
865 if ( ! $this->mRestrictionsLoaded ) {
866 $dbr =& wfGetDB( DB_SLAVE );
867 $res = $dbr->selectField( 'cur', 'cur_restrictions', 'cur_id='.$id );
868 $this->mRestrictions = explode( ',', trim( $res ) );
869 $this->mRestrictionsLoaded = true;
870 }
871 return $this->mRestrictions;
872 }
873
874 /**
875 * Is there a version of this page in the deletion archive?
876 * @return int the number of archived revisions
877 * @access public
878 */
879 function isDeleted() {
880 $fname = 'Title::isDeleted';
881 $dbr =& wfGetDB( DB_SLAVE );
882 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
883 'ar_title' => $this->getDBkey() ), $fname );
884 return (int)$n;
885 }
886
887 /**
888 * Get the article ID for this Title from the link cache,
889 * adding it if necessary
890 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
891 * for update
892 * @return int the ID
893 * @access public
894 */
895 function getArticleID( $flags = 0 ) {
896 global $wgLinkCache;
897
898 if ( $flags & GAID_FOR_UPDATE ) {
899 $oldUpdate = $wgLinkCache->forUpdate( true );
900 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
901 $wgLinkCache->forUpdate( $oldUpdate );
902 } else {
903 if ( -1 == $this->mArticleID ) {
904 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
905 }
906 }
907 return $this->mArticleID;
908 }
909
910 /**
911 * This clears some fields in this object, and clears any associated
912 * keys in the "bad links" section of $wgLinkCache.
913 *
914 * - This is called from Article::insertNewArticle() to allow
915 * loading of the new cur_id. It's also called from
916 * Article::doDeleteArticle()
917 *
918 * @param int $newid the new Article ID
919 * @access public
920 */
921 function resetArticleID( $newid ) {
922 global $wgLinkCache;
923 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
924
925 if ( 0 == $newid ) { $this->mArticleID = -1; }
926 else { $this->mArticleID = $newid; }
927 $this->mRestrictionsLoaded = false;
928 $this->mRestrictions = array();
929 }
930
931 /**
932 * Updates cur_touched for this page; called from LinksUpdate.php
933 * @return bool true if the update succeded
934 * @access public
935 */
936 function invalidateCache() {
937 $now = wfTimestampNow();
938 $dbw =& wfGetDB( DB_MASTER );
939 $success = $dbw->update( 'cur',
940 array( /* SET */
941 'cur_touched' => $dbw->timestamp()
942 ), array( /* WHERE */
943 'cur_namespace' => $this->getNamespace() ,
944 'cur_title' => $this->getDBkey()
945 ), 'Title::invalidateCache'
946 );
947 return $success;
948 }
949
950 /**
951 * Prefix some arbitrary text with the namespace or interwiki prefix
952 * of this object
953 *
954 * @param string $name the text
955 * @return string the prefixed text
956 * @access private
957 */
958 /* private */ function prefix( $name ) {
959 global $wgContLang;
960
961 $p = '';
962 if ( '' != $this->mInterwiki ) {
963 $p = $this->mInterwiki . ':';
964 }
965 if ( 0 != $this->mNamespace ) {
966 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
967 }
968 return $p . $name;
969 }
970
971 /**
972 * Secure and split - main initialisation function for this object
973 *
974 * Assumes that mDbkeyform has been set, and is urldecoded
975 * and uses underscores, but not otherwise munged. This function
976 * removes illegal characters, splits off the interwiki and
977 * namespace prefixes, sets the other forms, and canonicalizes
978 * everything.
979 * @return bool true on success
980 * @access private
981 */
982 /* private */ function secureAndSplit()
983 {
984 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
985 $fname = 'Title::secureAndSplit';
986 wfProfileIn( $fname );
987
988 static $imgpre = false;
989 static $rxTc = false;
990
991 # Initialisation
992 if ( $imgpre === false ) {
993 $imgpre = ':' . $wgContLang->getNsText( Namespace::getImage() ) . ':';
994 # % is needed as well
995 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/';
996 }
997
998 $this->mInterwiki = $this->mFragment = '';
999 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1000
1001 # Clean up whitespace
1002 #
1003 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform );
1004 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
1005
1006 if ( '' == $t ) {
1007 wfProfileOut( $fname );
1008 return false;
1009 }
1010
1011 global $wgUseLatin1;
1012 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1013 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1014 wfProfileOut( $fname );
1015 return false;
1016 }
1017
1018 $this->mDbkeyform = $t;
1019 $done = false;
1020
1021 # :Image: namespace
1022 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
1023 $t = substr( $t, 1 );
1024 }
1025
1026 # Initial colon indicating main namespace
1027 if ( ':' == $t{0} ) {
1028 $r = substr( $t, 1 );
1029 $this->mNamespace = NS_MAIN;
1030 } else {
1031 # Namespace or interwiki prefix
1032 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
1033 #$p = strtolower( $m[1] );
1034 $p = $m[1];
1035 $lowerNs = strtolower( $p );
1036 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1037 # Canonical namespace
1038 $t = $m[2];
1039 $this->mNamespace = $ns;
1040 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1041 # Ordinary namespace
1042 $t = $m[2];
1043 $this->mNamespace = $ns;
1044 } elseif ( $this->getInterwikiLink( $p ) ) {
1045 # Interwiki link
1046 $t = $m[2];
1047 $this->mInterwiki = $p;
1048
1049 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
1050 $done = true;
1051 } elseif($this->mInterwiki != $wgLocalInterwiki) {
1052 $done = true;
1053 }
1054 }
1055 }
1056 $r = $t;
1057 }
1058
1059 # Redundant interwiki prefix to the local wiki
1060 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1061 $this->mInterwiki = '';
1062 }
1063 # We already know that some pages won't be in the database!
1064 #
1065 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1066 $this->mArticleID = 0;
1067 }
1068 $f = strstr( $r, '#' );
1069 if ( false !== $f ) {
1070 $this->mFragment = substr( $f, 1 );
1071 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1072 # remove whitespace again: prevents "Foo_bar_#"
1073 # becoming "Foo_bar_"
1074 $r = preg_replace( '/_*$/', '', $r );
1075 }
1076
1077 # Reject illegal characters.
1078 #
1079 if( preg_match( $rxTc, $r ) ) {
1080 wfProfileOut( $fname );
1081 return false;
1082 }
1083
1084 # "." and ".." conflict with the directories of those namesa
1085 if ( strpos( $r, '.' ) !== false &&
1086 ( $r === '.' || $r === '..' ||
1087 strpos( $r, './' ) === 0 ||
1088 strpos( $r, '../' ) === 0 ||
1089 strpos( $r, '/./' ) !== false ||
1090 strpos( $r, '/../' ) !== false ) )
1091 {
1092 wfProfileOut( $fname );
1093 return false;
1094 }
1095
1096 # We shouldn't need to query the DB for the size.
1097 #$maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
1098 if ( strlen( $r ) > 255 ) {
1099 return false;
1100 }
1101
1102 # Initial capital letter
1103 if( $wgCapitalLinks && $this->mInterwiki == '') {
1104 $t = $wgContLang->ucfirst( $r );
1105 } else {
1106 $t = $r;
1107 }
1108
1109 # Fill fields
1110 $this->mDbkeyform = $t;
1111 $this->mUrlform = wfUrlencode( $t );
1112
1113 $this->mTextform = str_replace( '_', ' ', $t );
1114
1115 wfProfileOut( $fname );
1116 return true;
1117 }
1118
1119 /**
1120 * Get a Title object associated with the talk page of this article
1121 * @return Title the object for the talk page
1122 * @access public
1123 */
1124 function getTalkPage() {
1125 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1126 }
1127
1128 /**
1129 * Get a title object associated with the subject page of this
1130 * talk page
1131 *
1132 * @return Title the object for the subject page
1133 * @access public
1134 */
1135 function getSubjectPage() {
1136 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1137 }
1138
1139 /**
1140 * Get an array of Title objects linking to this Title
1141 * - Also stores the IDs in the link cache.
1142 *
1143 * @param string $options may be FOR UPDATE
1144 * @return array the Title objects linking here
1145 * @access public
1146 */
1147 function getLinksTo( $options = '' ) {
1148 global $wgLinkCache;
1149 $id = $this->getArticleID();
1150
1151 if ( $options ) {
1152 $db =& wfGetDB( DB_MASTER );
1153 } else {
1154 $db =& wfGetDB( DB_SLAVE );
1155 }
1156 $cur = $db->tableName( 'cur' );
1157 $links = $db->tableName( 'links' );
1158
1159 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
1160 $res = $db->query( $sql, 'Title::getLinksTo' );
1161 $retVal = array();
1162 if ( $db->numRows( $res ) ) {
1163 while ( $row = $db->fetchObject( $res ) ) {
1164 if ( $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title ) ) {
1165 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
1166 $retVal[] = $titleObj;
1167 }
1168 }
1169 }
1170 $db->freeResult( $res );
1171 return $retVal;
1172 }
1173
1174 /**
1175 * Get an array of Title objects linking to this non-existent title.
1176 * - Also stores the IDs in the link cache.
1177 *
1178 * @param string $options may be FOR UPDATE
1179 * @return array the Title objects linking here
1180 * @access public
1181 */
1182 function getBrokenLinksTo( $options = '' ) {
1183 global $wgLinkCache;
1184
1185 if ( $options ) {
1186 $db =& wfGetDB( DB_MASTER );
1187 } else {
1188 $db =& wfGetDB( DB_SLAVE );
1189 }
1190 $cur = $db->tableName( 'cur' );
1191 $brokenlinks = $db->tableName( 'brokenlinks' );
1192 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1193
1194 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
1195 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
1196 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1197 $retVal = array();
1198 if ( $db->numRows( $res ) ) {
1199 while ( $row = $db->fetchObject( $res ) ) {
1200 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
1201 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
1202 $retVal[] = $titleObj;
1203 }
1204 }
1205 $db->freeResult( $res );
1206 return $retVal;
1207 }
1208
1209 /**
1210 * Get a list of URLs to purge from the Squid cache when this
1211 * page changes
1212 *
1213 * @return array the URLs
1214 * @access public
1215 */
1216 function getSquidURLs() {
1217 return array(
1218 $this->getInternalURL(),
1219 $this->getInternalURL( 'action=history' )
1220 );
1221 }
1222
1223 /**
1224 * Move this page without authentication
1225 * @param Title &$nt the new page Title
1226 * @access public
1227 */
1228 function moveNoAuth( &$nt ) {
1229 return $this->moveTo( $nt, false );
1230 }
1231
1232 /**
1233 * Move a title to a new location
1234 * @param Title &$nt the new title
1235 * @param bool $auth indicates whether $wgUser's permissions
1236 * should be checked
1237 * @return mixed true on success, message name on failure
1238 * @access public
1239 */
1240 function moveTo( &$nt, $auth = true ) {
1241 if( !$this or !$nt ) {
1242 return 'badtitletext';
1243 }
1244
1245 $fname = 'Title::move';
1246 $oldid = $this->getArticleID();
1247 $newid = $nt->getArticleID();
1248
1249 if ( strlen( $nt->getDBkey() ) < 1 ) {
1250 return 'articleexists';
1251 }
1252 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1253 ( '' == $this->getDBkey() ) ||
1254 ( '' != $this->getInterwiki() ) ||
1255 ( !$oldid ) ||
1256 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1257 ( '' == $nt->getDBkey() ) ||
1258 ( '' != $nt->getInterwiki() ) ) {
1259 return 'badarticleerror';
1260 }
1261
1262 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
1263 return 'protectedpage';
1264 }
1265
1266 # The move is allowed only if (1) the target doesn't exist, or
1267 # (2) the target is a redirect to the source, and has no history
1268 # (so we can undo bad moves right after they're done).
1269
1270 if ( 0 != $newid ) { # Target exists; check for validity
1271 if ( ! $this->isValidMoveTarget( $nt ) ) {
1272 return 'articleexists';
1273 }
1274 $this->moveOverExistingRedirect( $nt );
1275 } else { # Target didn't exist, do normal move.
1276 $this->moveToNewTitle( $nt, $newid );
1277 }
1278
1279 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1280
1281 $dbw =& wfGetDB( DB_MASTER );
1282 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1283 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1284 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1285 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1286
1287 # Update watchlists
1288
1289 $oldnamespace = $this->getNamespace() & ~1;
1290 $newnamespace = $nt->getNamespace() & ~1;
1291 $oldtitle = $this->getDBkey();
1292 $newtitle = $nt->getDBkey();
1293
1294 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1295 WatchedItem::duplicateEntries( $this, $nt );
1296 }
1297
1298 # Update search engine
1299 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1300 $u->doUpdate();
1301 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1302 $u->doUpdate();
1303
1304 return true;
1305 }
1306
1307 /**
1308 * Move page to a title which is at present a redirect to the
1309 * source page
1310 *
1311 * @param Title &$nt the page to move to, which should currently
1312 * be a redirect
1313 * @access private
1314 */
1315 /* private */ function moveOverExistingRedirect( &$nt ) {
1316 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1317 $fname = 'Title::moveOverExistingRedirect';
1318 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1319
1320 $now = wfTimestampNow();
1321 $won = wfInvertTimestamp( $now );
1322 $newid = $nt->getArticleID();
1323 $oldid = $this->getArticleID();
1324 $dbw =& wfGetDB( DB_MASTER );
1325 $links = $dbw->tableName( 'links' );
1326
1327 # Change the name of the target page:
1328 $dbw->update( 'cur',
1329 /* SET */ array(
1330 'cur_touched' => $dbw->timestamp($now),
1331 'cur_namespace' => $nt->getNamespace(),
1332 'cur_title' => $nt->getDBkey()
1333 ),
1334 /* WHERE */ array( 'cur_id' => $oldid ),
1335 $fname
1336 );
1337 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1338
1339 # Repurpose the old redirect. We don't save it to history since
1340 # by definition if we've got here it's rather uninteresting.
1341
1342 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1343 $dbw->update( 'cur',
1344 /* SET */ array(
1345 'cur_touched' => $dbw->timestamp($now),
1346 'cur_timestamp' => $dbw->timestamp($now),
1347 'inverse_timestamp' => $won,
1348 'cur_namespace' => $this->getNamespace(),
1349 'cur_title' => $this->getDBkey(),
1350 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1351 'cur_comment' => $comment,
1352 'cur_user' => $wgUser->getID(),
1353 'cur_minor_edit' => 0,
1354 'cur_counter' => 0,
1355 'cur_restrictions' => '',
1356 'cur_user_text' => $wgUser->getName(),
1357 'cur_is_redirect' => 1,
1358 'cur_is_new' => 1
1359 ),
1360 /* WHERE */ array( 'cur_id' => $newid ),
1361 $fname
1362 );
1363
1364 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1365
1366 # Fix the redundant names for the past revisions of the target page.
1367 # The redirect should have no old revisions.
1368 $dbw->update(
1369 /* table */ 'old',
1370 /* SET */ array(
1371 'old_namespace' => $nt->getNamespace(),
1372 'old_title' => $nt->getDBkey(),
1373 ),
1374 /* WHERE */ array(
1375 'old_namespace' => $this->getNamespace(),
1376 'old_title' => $this->getDBkey(),
1377 ),
1378 $fname
1379 );
1380
1381 RecentChange::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1382
1383 # Swap links
1384
1385 # Load titles and IDs
1386 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1387 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1388
1389 # Delete them all
1390 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1391 $dbw->query( $sql, $fname );
1392
1393 # Reinsert
1394 if ( count( $linksToOld ) || count( $linksToNew )) {
1395 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1396 $first = true;
1397
1398 # Insert links to old title
1399 foreach ( $linksToOld as $linkTitle ) {
1400 if ( $first ) {
1401 $first = false;
1402 } else {
1403 $sql .= ',';
1404 }
1405 $id = $linkTitle->getArticleID();
1406 $sql .= "($id,$newid)";
1407 }
1408
1409 # Insert links to new title
1410 foreach ( $linksToNew as $linkTitle ) {
1411 if ( $first ) {
1412 $first = false;
1413 } else {
1414 $sql .= ',';
1415 }
1416 $id = $linkTitle->getArticleID();
1417 $sql .= "($id, $oldid)";
1418 }
1419
1420 $dbw->query( $sql, DB_MASTER, $fname );
1421 }
1422
1423 # Now, we record the link from the redirect to the new title.
1424 # It should have no other outgoing links...
1425 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1426 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1427
1428 # Clear linkscc
1429 LinkCache::linksccClearLinksTo( $oldid );
1430 LinkCache::linksccClearLinksTo( $newid );
1431
1432 # Purge squid
1433 if ( $wgUseSquid ) {
1434 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1435 $u = new SquidUpdate( $urls );
1436 $u->doUpdate();
1437 }
1438 }
1439
1440 /**
1441 * Move page to non-existing title.
1442 * @param Title &$nt the new Title
1443 * @param int &$newid set to be the new article ID
1444 * @access private
1445 */
1446 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1447 global $wgUser, $wgLinkCache, $wgUseSquid;
1448 $fname = 'MovePageForm::moveToNewTitle';
1449 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1450
1451 $newid = $nt->getArticleID();
1452 $oldid = $this->getArticleID();
1453 $dbw =& wfGetDB( DB_MASTER );
1454 $now = $dbw->timestamp();
1455 $won = wfInvertTimestamp( wfTimestamp(TS_MW,$now) );
1456 wfSeedRandom();
1457 $rand = wfRandom();
1458
1459 # Rename cur entry
1460 $dbw->update( 'cur',
1461 /* SET */ array(
1462 'cur_touched' => $now,
1463 'cur_namespace' => $nt->getNamespace(),
1464 'cur_title' => $nt->getDBkey()
1465 ),
1466 /* WHERE */ array( 'cur_id' => $oldid ),
1467 $fname
1468 );
1469
1470 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1471
1472 # Insert redirect
1473 $dbw->insert( 'cur', array(
1474 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1475 'cur_namespace' => $this->getNamespace(),
1476 'cur_title' => $this->getDBkey(),
1477 'cur_comment' => $comment,
1478 'cur_user' => $wgUser->getID(),
1479 'cur_user_text' => $wgUser->getName(),
1480 'cur_timestamp' => $now,
1481 'inverse_timestamp' => $won,
1482 'cur_touched' => $now,
1483 'cur_is_redirect' => 1,
1484 'cur_random' => $rand,
1485 'cur_is_new' => 1,
1486 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1487 );
1488 $newid = $dbw->insertId();
1489 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1490
1491 # Rename old entries
1492 $dbw->update(
1493 /* table */ 'old',
1494 /* SET */ array(
1495 'old_namespace' => $nt->getNamespace(),
1496 'old_title' => $nt->getDBkey()
1497 ),
1498 /* WHERE */ array(
1499 'old_namespace' => $this->getNamespace(),
1500 'old_title' => $this->getDBkey()
1501 ), $fname
1502 );
1503
1504 # Record in RC
1505 RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1506
1507 # Purge squid and linkscc as per article creation
1508 Article::onArticleCreate( $nt );
1509
1510 # Any text links to the old title must be reassigned to the redirect
1511 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1512 LinkCache::linksccClearLinksTo( $oldid );
1513
1514 # Record the just-created redirect's linking to the page
1515 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1516
1517 # Non-existent target may have had broken links to it; these must
1518 # now be removed and made into good links.
1519 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1520 $update->fixBrokenLinks();
1521
1522 # Purge old title from squid
1523 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1524 $titles = $nt->getLinksTo();
1525 if ( $wgUseSquid ) {
1526 $urls = $this->getSquidURLs();
1527 foreach ( $titles as $linkTitle ) {
1528 $urls[] = $linkTitle->getInternalURL();
1529 }
1530 $u = new SquidUpdate( $urls );
1531 $u->doUpdate();
1532 }
1533 }
1534
1535 /**
1536 * Checks if $this can be moved to a given Title
1537 * - Selects for update, so don't call it unless you mean business
1538 *
1539 * @param Title &$nt the new title to check
1540 * @access public
1541 */
1542 function isValidMoveTarget( $nt ) {
1543 $fname = 'Title::isValidMoveTarget';
1544 $dbw =& wfGetDB( DB_MASTER );
1545
1546 # Is it a redirect?
1547 $id = $nt->getArticleID();
1548 $obj = $dbw->selectRow( 'cur', array( 'cur_is_redirect','cur_text' ),
1549 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1550
1551 if ( !$obj || 0 == $obj->cur_is_redirect ) {
1552 # Not a redirect
1553 return false;
1554 }
1555
1556 # Does the redirect point to the source?
1557 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text, $m ) ) {
1558 $redirTitle = Title::newFromText( $m[1] );
1559 if( !is_object( $redirTitle ) ||
1560 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1561 return false;
1562 }
1563 }
1564
1565 # Does the article have a history?
1566 $row = $dbw->selectRow( 'old', array( 'old_id' ),
1567 array(
1568 'old_namespace' => $nt->getNamespace(),
1569 'old_title' => $nt->getDBkey()
1570 ), $fname, 'FOR UPDATE'
1571 );
1572
1573 # Return true if there was no history
1574 return $row === false;
1575 }
1576
1577 /**
1578 * Create a redirect; fails if the title already exists; does
1579 * not notify RC
1580 *
1581 * @param Title $dest the destination of the redirect
1582 * @param string $comment the comment string describing the move
1583 * @return bool true on success
1584 * @access public
1585 */
1586 function createRedirect( $dest, $comment ) {
1587 global $wgUser;
1588 if ( $this->getArticleID() ) {
1589 return false;
1590 }
1591
1592 $fname = 'Title::createRedirect';
1593 $dbw =& wfGetDB( DB_MASTER );
1594 $now = wfTimestampNow();
1595 $won = wfInvertTimestamp( $now );
1596 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1597
1598 $dbw->insert( 'cur', array(
1599 'cur_id' => $seqVal,
1600 'cur_namespace' => $this->getNamespace(),
1601 'cur_title' => $this->getDBkey(),
1602 'cur_comment' => $comment,
1603 'cur_user' => $wgUser->getID(),
1604 'cur_user_text' => $wgUser->getName(),
1605 'cur_timestamp' => $now,
1606 'inverse_timestamp' => $won,
1607 'cur_touched' => $now,
1608 'cur_is_redirect' => 1,
1609 'cur_is_new' => 1,
1610 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1611 ), $fname );
1612 $newid = $dbw->insertId();
1613 $this->resetArticleID( $newid );
1614
1615 # Link table
1616 if ( $dest->getArticleID() ) {
1617 $dbw->insert( 'links',
1618 array(
1619 'l_to' => $dest->getArticleID(),
1620 'l_from' => $newid
1621 ), $fname
1622 );
1623 } else {
1624 $dbw->insert( 'brokenlinks',
1625 array(
1626 'bl_to' => $dest->getPrefixedDBkey(),
1627 'bl_from' => $newid
1628 ), $fname
1629 );
1630 }
1631
1632 Article::onArticleCreate( $this );
1633 return true;
1634 }
1635
1636 /**
1637 * Get categories to which this Title belongs and return an array of
1638 * categories' names.
1639 *
1640 * @return array an array of parents in the form:
1641 * $parent => $currentarticle
1642 * @access public
1643 */
1644 function getParentCategories() {
1645 global $wgContLang,$wgUser;
1646
1647 $titlekey = $this->getArticleId();
1648 $sk =& $wgUser->getSkin();
1649 $parents = array();
1650 $dbr =& wfGetDB( DB_SLAVE );
1651 $cur = $dbr->tableName( 'cur' );
1652 $categorylinks = $dbr->tableName( 'categorylinks' );
1653
1654 # NEW SQL
1655 $sql = "SELECT * FROM categorylinks"
1656 ." WHERE cl_from='$titlekey'"
1657 ." AND cl_from <> '0'"
1658 ." ORDER BY cl_sortkey";
1659
1660 $res = $dbr->query ( $sql ) ;
1661
1662 if($dbr->numRows($res) > 0) {
1663 while ( $x = $dbr->fetchObject ( $res ) )
1664 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1665 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1666 $dbr->freeResult ( $res ) ;
1667 } else {
1668 $data = '';
1669 }
1670 return $data;
1671 }
1672
1673 /**
1674 * Go through all parent categories of this Title
1675 * @return array
1676 * @access public
1677 */
1678 function getCategorieBrowser() {
1679 $parents = $this->getParentCategories();
1680
1681 if($parents != '') {
1682 foreach($parents as $parent => $current)
1683 {
1684 $nt = Title::newFromText($parent);
1685 $stack[$parent] = $nt->getCategorieBrowser();
1686 }
1687 return $stack;
1688 } else {
1689 return array();
1690 }
1691 }
1692
1693
1694 /**
1695 * Get an associative array for selecting this title from
1696 * the "cur" table
1697 *
1698 * @return array
1699 * @access public
1700 */
1701 function curCond() {
1702 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1703 }
1704
1705 /**
1706 * Get an associative array for selecting this title from the
1707 * "old" table
1708 *
1709 * @return array
1710 * @access public
1711 */
1712 function oldCond() {
1713 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1714 }
1715
1716 /**
1717 * Get the revision ID of the previous revision
1718 *
1719 * @param integer $revision Revision ID. Get the revision that was before this one.
1720 * @return interger $oldrevision|false
1721 */
1722 function getPreviousRevisionID( $revision ) {
1723 $dbr =& wfGetDB( DB_SLAVE );
1724 return $dbr->selectField( 'old', 'old_id',
1725 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1726 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1727 ' AND old_id<' . IntVal( $revision ) . ' ORDER BY old_id DESC' );
1728 }
1729
1730 /**
1731 * Get the revision ID of the next revision
1732 *
1733 * @param integer $revision Revision ID. Get the revision that was after this one.
1734 * @return interger $oldrevision|false
1735 */
1736 function getNextRevisionID( $revision ) {
1737 $dbr =& wfGetDB( DB_SLAVE );
1738 return $dbr->selectField( 'old', 'old_id',
1739 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1740 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1741 ' AND old_id>' . IntVal( $revision ) . ' ORDER BY old_id' );
1742 }
1743
1744 }
1745 ?>