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