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