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