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