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