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