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