* Add wfClone() wrapper since we're still using PHP 4 on some servers.
[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, $wgRequest;
669
670 if ( '' == $this->mInterwiki ) {
671 $url = $this->getLocalUrl( $query );
672
673 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
674 // Correct fix would be to move the prepending elsewhere.
675 if ($wgRequest->getVal('action') != 'render') {
676 $url = $wgServer . $url;
677 }
678 } else {
679 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
680
681 $namespace = $wgContLang->getNsText( $this->mNamespace );
682 if ( '' != $namespace ) {
683 # Can this actually happen? Interwikis shouldn't be parsed.
684 $namespace .= ':';
685 }
686 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
687 if( $query != '' ) {
688 if( false === strpos( $url, '?' ) ) {
689 $url .= '?';
690 } else {
691 $url .= '&';
692 }
693 $url .= $query;
694 }
695 if ( '' != $this->mFragment ) {
696 $url .= '#' . $this->mFragment;
697 }
698 }
699 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
700 return $url;
701 }
702
703 /**
704 * Get a URL with no fragment or server name. If this page is generated
705 * with action=render, $wgServer is prepended.
706 * @param string $query an optional query string; if not specified,
707 * $wgArticlePath will be used.
708 * @return string the URL
709 * @access public
710 */
711 function getLocalURL( $query = '' ) {
712 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
713
714 if ( $this->isExternal() ) {
715 $url = $this->getFullURL();
716 } else {
717 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
718 if ( $query == '' ) {
719 $url = str_replace( '$1', $dbkey, $wgArticlePath );
720 } else {
721 global $wgActionPaths;
722 $url = false;
723 if( !empty( $wgActionPaths ) &&
724 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
725 {
726 $action = urldecode( $matches[2] );
727 if( isset( $wgActionPaths[$action] ) ) {
728 $query = $matches[1];
729 if( isset( $matches[4] ) ) $query .= $matches[4];
730 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
731 if( $query != '' ) $url .= '?' . $query;
732 }
733 }
734 if ( $url === false ) {
735 if ( $query == '-' ) {
736 $query = '';
737 }
738 $url = "{$wgScript}?title={$dbkey}&{$query}";
739 }
740 }
741
742 // FIXME: this causes breakage in various places when we
743 // actually expected a local URL and end up with dupe prefixes.
744 if ($wgRequest->getVal('action') == 'render') {
745 $url = $wgServer . $url;
746 }
747 }
748 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
749 return $url;
750 }
751
752 /**
753 * Get an HTML-escaped version of the URL form, suitable for
754 * using in a link, without a server name or fragment
755 * @param string $query an optional query string
756 * @return string the URL
757 * @access public
758 */
759 function escapeLocalURL( $query = '' ) {
760 return htmlspecialchars( $this->getLocalURL( $query ) );
761 }
762
763 /**
764 * Get an HTML-escaped version of the URL form, suitable for
765 * using in a link, including the server name and fragment
766 *
767 * @return string the URL
768 * @param string $query an optional query string
769 * @access public
770 */
771 function escapeFullURL( $query = '' ) {
772 return htmlspecialchars( $this->getFullURL( $query ) );
773 }
774
775 /**
776 * Get the URL form for an internal link.
777 * - Used in various Squid-related code, in case we have a different
778 * internal hostname for the server from the exposed one.
779 *
780 * @param string $query an optional query string
781 * @return string the URL
782 * @access public
783 */
784 function getInternalURL( $query = '' ) {
785 global $wgInternalServer;
786 $url = $wgInternalServer . $this->getLocalURL( $query );
787 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
788 return $url;
789 }
790
791 /**
792 * Get the edit URL for this Title
793 * @return string the URL, or a null string if this is an
794 * interwiki link
795 * @access public
796 */
797 function getEditURL() {
798 global $wgServer, $wgScript;
799
800 if ( '' != $this->mInterwiki ) { return ''; }
801 $s = $this->getLocalURL( 'action=edit' );
802
803 return $s;
804 }
805
806 /**
807 * Get the HTML-escaped displayable text form.
808 * Used for the title field in <a> tags.
809 * @return string the text, including any prefixes
810 * @access public
811 */
812 function getEscapedText() {
813 return htmlspecialchars( $this->getPrefixedText() );
814 }
815
816 /**
817 * Is this Title interwiki?
818 * @return boolean
819 * @access public
820 */
821 function isExternal() { return ( '' != $this->mInterwiki ); }
822
823 /**
824 * Does the title correspond to a protected article?
825 * @param string $what the action the page is protected from,
826 * by default checks move and edit
827 * @return boolean
828 * @access public
829 */
830 function isProtected($action = '') {
831 if ( -1 == $this->mNamespace ) { return true; }
832 if($action == 'edit' || $action == '') {
833 $a = $this->getRestrictions("edit");
834 if ( in_array( 'sysop', $a ) ) { return true; }
835 }
836 if($action == 'move' || $action == '') {
837 $a = $this->getRestrictions("move");
838 if ( in_array( 'sysop', $a ) ) { return true; }
839 }
840 return false;
841 }
842
843 /**
844 * Is $wgUser is watching this page?
845 * @return boolean
846 * @access public
847 */
848 function userIsWatching() {
849 global $wgUser;
850
851 if ( is_null( $this->mWatched ) ) {
852 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
853 $this->mWatched = false;
854 } else {
855 $this->mWatched = $wgUser->isWatched( $this );
856 }
857 }
858 return $this->mWatched;
859 }
860
861 /**
862 * Can $wgUser perform $action this page?
863 * @param string $action action that permission needs to be checked for
864 * @return boolean
865 * @access private
866 */
867 function userCan($action) {
868 $fname = 'Title::userCan';
869 wfProfileIn( $fname );
870
871 global $wgUser;
872 if( NS_SPECIAL == $this->mNamespace ) {
873 wfProfileOut( $fname );
874 return false;
875 }
876 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
877 // from taking effect -ævar
878 if( NS_MEDIAWIKI == $this->mNamespace &&
879 !$wgUser->isAllowed('editinterface') ) {
880 wfProfileOut( $fname );
881 return false;
882 }
883
884 if( $this->mDbkeyform == '_' ) {
885 # FIXME: Is this necessary? Shouldn't be allowed anyway...
886 wfProfileOut( $fname );
887 return false;
888 }
889
890 # protect global styles and js
891 if ( NS_MEDIAWIKI == $this->mNamespace
892 && preg_match("/\\.(css|js)$/", $this->mTextform )
893 && !$wgUser->isAllowed('editinterface') ) {
894 wfProfileOut( $fname );
895 return false;
896 }
897
898 # protect css/js subpages of user pages
899 # XXX: this might be better using restrictions
900 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
901 if( NS_USER == $this->mNamespace
902 && preg_match("/\\.(css|js)$/", $this->mTextform )
903 && !$wgUser->isAllowed('editinterface')
904 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
905 wfProfileOut( $fname );
906 return false;
907 }
908
909 foreach( $this->getRestrictions($action) as $right ) {
910 // Backwards compatibility, rewrite sysop -> protect
911 if ( $right == 'sysop' ) {
912 $right = 'protect';
913 }
914 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
915 wfProfileOut( $fname );
916 return false;
917 }
918 }
919
920 if( $action == 'move' &&
921 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
922 wfProfileOut( $fname );
923 return false;
924 }
925
926 if( $action == 'create' ) {
927 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
928 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
929 return false;
930 }
931 }
932
933 wfProfileOut( $fname );
934 return true;
935 }
936
937 /**
938 * Can $wgUser edit this page?
939 * @return boolean
940 * @access public
941 */
942 function userCanEdit() {
943 return $this->userCan('edit');
944 }
945
946 /**
947 * Can $wgUser move this page?
948 * @return boolean
949 * @access public
950 */
951 function userCanMove() {
952 return $this->userCan('move');
953 }
954
955 /**
956 * Would anybody with sufficient privileges be able to move this page?
957 * Some pages just aren't movable.
958 *
959 * @return boolean
960 * @access public
961 */
962 function isMovable() {
963 return Namespace::isMovable( $this->getNamespace() )
964 && $this->getInterwiki() == '';
965 }
966
967 /**
968 * Can $wgUser read this page?
969 * @return boolean
970 * @access public
971 */
972 function userCanRead() {
973 global $wgUser;
974
975 if( $wgUser->isAllowed('read') ) {
976 return true;
977 } else {
978 global $wgWhitelistRead;
979
980 /** If anon users can create an account,
981 they need to reach the login page first! */
982 if( $wgUser->isAllowed( 'createaccount' )
983 && $this->getNamespace() == NS_SPECIAL
984 && $this->getText() == 'Userlogin' ) {
985 return true;
986 }
987
988 /** some pages are explicitly allowed */
989 $name = $this->getPrefixedText();
990 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
991 return true;
992 }
993
994 # Compatibility with old settings
995 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
996 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
997 return true;
998 }
999 }
1000 }
1001 return false;
1002 }
1003
1004 /**
1005 * Is this a talk page of some sort?
1006 * @return bool
1007 * @access public
1008 */
1009 function isTalkPage() {
1010 return Namespace::isTalk( $this->getNamespace() );
1011 }
1012
1013 /**
1014 * Is this a .css or .js subpage of a user page?
1015 * @return bool
1016 * @access public
1017 */
1018 function isCssJsSubpage() {
1019 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1020 }
1021 /**
1022 * Is this a .css subpage of a user page?
1023 * @return bool
1024 * @access public
1025 */
1026 function isCssSubpage() {
1027 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1028 }
1029 /**
1030 * Is this a .js subpage of a user page?
1031 * @return bool
1032 * @access public
1033 */
1034 function isJsSubpage() {
1035 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1036 }
1037 /**
1038 * Protect css/js subpages of user pages: can $wgUser edit
1039 * this page?
1040 *
1041 * @return boolean
1042 * @todo XXX: this might be better using restrictions
1043 * @access public
1044 */
1045 function userCanEditCssJsSubpage() {
1046 global $wgUser;
1047 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1048 }
1049
1050 /**
1051 * Loads a string into mRestrictions array
1052 * @param string $res restrictions in string format
1053 * @access public
1054 */
1055 function loadRestrictions( $res ) {
1056 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1057 $temp = explode( '=', trim( $restrict ) );
1058 if(count($temp) == 1) {
1059 // old format should be treated as edit/move restriction
1060 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1061 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1062 } else {
1063 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1064 }
1065 }
1066 $this->mRestrictionsLoaded = true;
1067 }
1068
1069 /**
1070 * Accessor/initialisation for mRestrictions
1071 * @param string $action action that permission needs to be checked for
1072 * @return array the array of groups allowed to edit this article
1073 * @access public
1074 */
1075 function getRestrictions($action) {
1076 $id = $this->getArticleID();
1077 if ( 0 == $id ) { return array(); }
1078
1079 if ( ! $this->mRestrictionsLoaded ) {
1080 $dbr =& wfGetDB( DB_SLAVE );
1081 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1082 $this->loadRestrictions( $res );
1083 }
1084 if( isset( $this->mRestrictions[$action] ) ) {
1085 return $this->mRestrictions[$action];
1086 }
1087 return array();
1088 }
1089
1090 /**
1091 * Is there a version of this page in the deletion archive?
1092 * @return int the number of archived revisions
1093 * @access public
1094 */
1095 function isDeleted() {
1096 $fname = 'Title::isDeleted';
1097 if ( $this->getNamespace() < 0 ) {
1098 $n = 0;
1099 } else {
1100 $dbr =& wfGetDB( DB_SLAVE );
1101 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1102 'ar_title' => $this->getDBkey() ), $fname );
1103 }
1104 return (int)$n;
1105 }
1106
1107 /**
1108 * Get the article ID for this Title from the link cache,
1109 * adding it if necessary
1110 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1111 * for update
1112 * @return int the ID
1113 * @access public
1114 */
1115 function getArticleID( $flags = 0 ) {
1116 $linkCache =& LinkCache::singleton();
1117 if ( $flags & GAID_FOR_UPDATE ) {
1118 $oldUpdate = $linkCache->forUpdate( true );
1119 $this->mArticleID = $linkCache->addLinkObj( $this );
1120 $linkCache->forUpdate( $oldUpdate );
1121 } else {
1122 if ( -1 == $this->mArticleID ) {
1123 $this->mArticleID = $linkCache->addLinkObj( $this );
1124 }
1125 }
1126 return $this->mArticleID;
1127 }
1128
1129 function getLatestRevID() {
1130 if ($this->mLatestID !== false)
1131 return $this->mLatestID;
1132
1133 $db =& wfGetDB(DB_SLAVE);
1134 return $this->mLatestID = $db->selectField( 'revision',
1135 "max(rev_id)",
1136 array('rev_page' => $this->getArticleID()),
1137 'Title::getLatestRevID' );
1138 }
1139
1140 /**
1141 * This clears some fields in this object, and clears any associated
1142 * keys in the "bad links" section of the link cache.
1143 *
1144 * - This is called from Article::insertNewArticle() to allow
1145 * loading of the new page_id. It's also called from
1146 * Article::doDeleteArticle()
1147 *
1148 * @param int $newid the new Article ID
1149 * @access public
1150 */
1151 function resetArticleID( $newid ) {
1152 $linkCache =& LinkCache::singleton();
1153 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1154
1155 if ( 0 == $newid ) { $this->mArticleID = -1; }
1156 else { $this->mArticleID = $newid; }
1157 $this->mRestrictionsLoaded = false;
1158 $this->mRestrictions = array();
1159 }
1160
1161 /**
1162 * Updates page_touched for this page; called from LinksUpdate.php
1163 * @return bool true if the update succeded
1164 * @access public
1165 */
1166 function invalidateCache() {
1167 global $wgUseFileCache;
1168
1169 if ( wfReadOnly() ) {
1170 return;
1171 }
1172
1173 $dbw =& wfGetDB( DB_MASTER );
1174 $success = $dbw->update( 'page',
1175 array( /* SET */
1176 'page_touched' => $dbw->timestamp()
1177 ), array( /* WHERE */
1178 'page_namespace' => $this->getNamespace() ,
1179 'page_title' => $this->getDBkey()
1180 ), 'Title::invalidateCache'
1181 );
1182
1183 if ($wgUseFileCache) {
1184 $cache = new CacheManager($this);
1185 @unlink($cache->fileCacheName());
1186 }
1187
1188 return $success;
1189 }
1190
1191 /**
1192 * Prefix some arbitrary text with the namespace or interwiki prefix
1193 * of this object
1194 *
1195 * @param string $name the text
1196 * @return string the prefixed text
1197 * @access private
1198 */
1199 /* private */ function prefix( $name ) {
1200 global $wgContLang;
1201
1202 $p = '';
1203 if ( '' != $this->mInterwiki ) {
1204 $p = $this->mInterwiki . ':';
1205 }
1206 if ( 0 != $this->mNamespace ) {
1207 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1208 }
1209 return $p . $name;
1210 }
1211
1212 /**
1213 * Secure and split - main initialisation function for this object
1214 *
1215 * Assumes that mDbkeyform has been set, and is urldecoded
1216 * and uses underscores, but not otherwise munged. This function
1217 * removes illegal characters, splits off the interwiki and
1218 * namespace prefixes, sets the other forms, and canonicalizes
1219 * everything.
1220 * @return bool true on success
1221 * @access private
1222 */
1223 /* private */ function secureAndSplit() {
1224 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1225 $fname = 'Title::secureAndSplit';
1226 wfProfileIn( $fname );
1227
1228 # Initialisation
1229 static $rxTc = false;
1230 if( !$rxTc ) {
1231 # % is needed as well
1232 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1233 }
1234
1235 $this->mInterwiki = $this->mFragment = '';
1236 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1237
1238 # Clean up whitespace
1239 #
1240 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1241 $t = trim( $t, '_' );
1242
1243 if ( '' == $t ) {
1244 wfProfileOut( $fname );
1245 return false;
1246 }
1247
1248 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1249 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1250 wfProfileOut( $fname );
1251 return false;
1252 }
1253
1254 $this->mDbkeyform = $t;
1255
1256 # Initial colon indicates main namespace rather than specified default
1257 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1258 if ( ':' == $t{0} ) {
1259 $this->mNamespace = NS_MAIN;
1260 $t = substr( $t, 1 ); # remove the colon but continue processing
1261 }
1262
1263 # Namespace or interwiki prefix
1264 $firstPass = true;
1265 do {
1266 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1267 $p = $m[1];
1268 $lowerNs = strtolower( $p );
1269 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1270 # Canonical namespace
1271 $t = $m[2];
1272 $this->mNamespace = $ns;
1273 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1274 # Ordinary namespace
1275 $t = $m[2];
1276 $this->mNamespace = $ns;
1277 } elseif( $this->getInterwikiLink( $p ) ) {
1278 if( !$firstPass ) {
1279 # Can't make a local interwiki link to an interwiki link.
1280 # That's just crazy!
1281 wfProfileOut( $fname );
1282 return false;
1283 }
1284
1285 # Interwiki link
1286 $t = $m[2];
1287 $this->mInterwiki = strtolower( $p );
1288
1289 # Redundant interwiki prefix to the local wiki
1290 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1291 if( $t == '' ) {
1292 # Can't have an empty self-link
1293 wfProfileOut( $fname );
1294 return false;
1295 }
1296 $this->mInterwiki = '';
1297 $firstPass = false;
1298 # Do another namespace split...
1299 continue;
1300 }
1301 }
1302 # If there's no recognized interwiki or namespace,
1303 # then let the colon expression be part of the title.
1304 }
1305 break;
1306 } while( true );
1307 $r = $t;
1308
1309 # We already know that some pages won't be in the database!
1310 #
1311 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1312 $this->mArticleID = 0;
1313 }
1314 $f = strstr( $r, '#' );
1315 if ( false !== $f ) {
1316 $this->mFragment = substr( $f, 1 );
1317 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1318 # remove whitespace again: prevents "Foo_bar_#"
1319 # becoming "Foo_bar_"
1320 $r = preg_replace( '/_*$/', '', $r );
1321 }
1322
1323 # Reject illegal characters.
1324 #
1325 if( preg_match( $rxTc, $r ) ) {
1326 wfProfileOut( $fname );
1327 return false;
1328 }
1329
1330 /**
1331 * Pages with "/./" or "/../" appearing in the URLs will
1332 * often be unreachable due to the way web browsers deal
1333 * with 'relative' URLs. Forbid them explicitly.
1334 */
1335 if ( strpos( $r, '.' ) !== false &&
1336 ( $r === '.' || $r === '..' ||
1337 strpos( $r, './' ) === 0 ||
1338 strpos( $r, '../' ) === 0 ||
1339 strpos( $r, '/./' ) !== false ||
1340 strpos( $r, '/../' ) !== false ) )
1341 {
1342 wfProfileOut( $fname );
1343 return false;
1344 }
1345
1346 # We shouldn't need to query the DB for the size.
1347 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1348 if ( strlen( $r ) > 255 ) {
1349 wfProfileOut( $fname );
1350 return false;
1351 }
1352
1353 /**
1354 * Normally, all wiki links are forced to have
1355 * an initial capital letter so [[foo]] and [[Foo]]
1356 * point to the same place.
1357 *
1358 * Don't force it for interwikis, since the other
1359 * site might be case-sensitive.
1360 */
1361 if( $wgCapitalLinks && $this->mInterwiki == '') {
1362 $t = $wgContLang->ucfirst( $r );
1363 } else {
1364 $t = $r;
1365 }
1366
1367 /**
1368 * Can't make a link to a namespace alone...
1369 * "empty" local links can only be self-links
1370 * with a fragment identifier.
1371 */
1372 if( $t == '' &&
1373 $this->mInterwiki == '' &&
1374 $this->mNamespace != NS_MAIN ) {
1375 wfProfileOut( $fname );
1376 return false;
1377 }
1378
1379 # Fill fields
1380 $this->mDbkeyform = $t;
1381 $this->mUrlform = wfUrlencode( $t );
1382
1383 $this->mTextform = str_replace( '_', ' ', $t );
1384
1385 wfProfileOut( $fname );
1386 return true;
1387 }
1388
1389 /**
1390 * Get a Title object associated with the talk page of this article
1391 * @return Title the object for the talk page
1392 * @access public
1393 */
1394 function getTalkPage() {
1395 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1396 }
1397
1398 /**
1399 * Get a title object associated with the subject page of this
1400 * talk page
1401 *
1402 * @return Title the object for the subject page
1403 * @access public
1404 */
1405 function getSubjectPage() {
1406 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1407 }
1408
1409 /**
1410 * Get an array of Title objects linking to this Title
1411 * Also stores the IDs in the link cache.
1412 *
1413 * @param string $options may be FOR UPDATE
1414 * @return array the Title objects linking here
1415 * @access public
1416 */
1417 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1418 $linkCache =& LinkCache::singleton();
1419 $id = $this->getArticleID();
1420
1421 if ( $options ) {
1422 $db =& wfGetDB( DB_MASTER );
1423 } else {
1424 $db =& wfGetDB( DB_SLAVE );
1425 }
1426
1427 $res = $db->select( array( 'page', $table ),
1428 array( 'page_namespace', 'page_title', 'page_id' ),
1429 array(
1430 "{$prefix}_from=page_id",
1431 "{$prefix}_namespace" => $this->getNamespace(),
1432 "{$prefix}_title" => $this->getDbKey() ),
1433 'Title::getLinksTo',
1434 $options );
1435
1436 $retVal = array();
1437 if ( $db->numRows( $res ) ) {
1438 while ( $row = $db->fetchObject( $res ) ) {
1439 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1440 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1441 $retVal[] = $titleObj;
1442 }
1443 }
1444 }
1445 $db->freeResult( $res );
1446 return $retVal;
1447 }
1448
1449 /**
1450 * Get an array of Title objects using this Title as a template
1451 * Also stores the IDs in the link cache.
1452 *
1453 * @param string $options may be FOR UPDATE
1454 * @return array the Title objects linking here
1455 * @access public
1456 */
1457 function getTemplateLinksTo( $options = '' ) {
1458 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1459 }
1460
1461 /**
1462 * Get an array of Title objects referring to non-existent articles linked from this page
1463 *
1464 * @param string $options may be FOR UPDATE
1465 * @return array the Title objects
1466 * @access public
1467 */
1468 function getBrokenLinksFrom( $options = '' ) {
1469 if ( $options ) {
1470 $db =& wfGetDB( DB_MASTER );
1471 } else {
1472 $db =& wfGetDB( DB_SLAVE );
1473 }
1474
1475 $res = $db->safeQuery(
1476 "SELECT pl_namespace, pl_title
1477 FROM !
1478 LEFT JOIN !
1479 ON pl_namespace=page_namespace
1480 AND pl_title=page_title
1481 WHERE pl_from=?
1482 AND page_namespace IS NULL
1483 !",
1484 $db->tableName( 'pagelinks' ),
1485 $db->tableName( 'page' ),
1486 $this->getArticleId(),
1487 $options );
1488
1489 $retVal = array();
1490 if ( $db->numRows( $res ) ) {
1491 while ( $row = $db->fetchObject( $res ) ) {
1492 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1493 }
1494 }
1495 $db->freeResult( $res );
1496 return $retVal;
1497 }
1498
1499
1500 /**
1501 * Get a list of URLs to purge from the Squid cache when this
1502 * page changes
1503 *
1504 * @return array the URLs
1505 * @access public
1506 */
1507 function getSquidURLs() {
1508 return array(
1509 $this->getInternalURL(),
1510 $this->getInternalURL( 'action=history' )
1511 );
1512 }
1513
1514 /**
1515 * Move this page without authentication
1516 * @param Title &$nt the new page Title
1517 * @access public
1518 */
1519 function moveNoAuth( &$nt ) {
1520 return $this->moveTo( $nt, false );
1521 }
1522
1523 /**
1524 * Check whether a given move operation would be valid.
1525 * Returns true if ok, or a message key string for an error message
1526 * if invalid. (Scarrrrry ugly interface this.)
1527 * @param Title &$nt the new title
1528 * @param bool $auth indicates whether $wgUser's permissions
1529 * should be checked
1530 * @return mixed true on success, message name on failure
1531 * @access public
1532 */
1533 function isValidMoveOperation( &$nt, $auth = true ) {
1534 global $wgUser;
1535 if( !$this or !$nt ) {
1536 return 'badtitletext';
1537 }
1538 if( $this->equals( $nt ) ) {
1539 return 'selfmove';
1540 }
1541 if( !$this->isMovable() || !$nt->isMovable() ) {
1542 return 'immobile_namespace';
1543 }
1544
1545 $oldid = $this->getArticleID();
1546 $newid = $nt->getArticleID();
1547
1548 if ( strlen( $nt->getDBkey() ) < 1 ) {
1549 return 'articleexists';
1550 }
1551 if ( ( '' == $this->getDBkey() ) ||
1552 ( !$oldid ) ||
1553 ( '' == $nt->getDBkey() ) ) {
1554 return 'badarticleerror';
1555 }
1556
1557 if ( $auth && (
1558 !$this->userCanEdit() || !$nt->userCanEdit() ||
1559 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1560 return 'protectedpage';
1561 }
1562
1563 # The move is allowed only if (1) the target doesn't exist, or
1564 # (2) the target is a redirect to the source, and has no history
1565 # (so we can undo bad moves right after they're done).
1566
1567 if ( 0 != $newid ) { # Target exists; check for validity
1568 if ( ! $this->isValidMoveTarget( $nt ) ) {
1569 return 'articleexists';
1570 }
1571 }
1572 return true;
1573 }
1574
1575 /**
1576 * Move a title to a new location
1577 * @param Title &$nt the new title
1578 * @param bool $auth indicates whether $wgUser's permissions
1579 * should be checked
1580 * @return mixed true on success, message name on failure
1581 * @access public
1582 */
1583 function moveTo( &$nt, $auth = true, $reason = '' ) {
1584 $err = $this->isValidMoveOperation( $nt, $auth );
1585 if( is_string( $err ) ) {
1586 return $err;
1587 }
1588
1589 $pageid = $this->getArticleID();
1590 if( $nt->exists() ) {
1591 $this->moveOverExistingRedirect( $nt, $reason );
1592 $pageCountChange = 0;
1593 } else { # Target didn't exist, do normal move.
1594 $this->moveToNewTitle( $nt, $reason );
1595 $pageCountChange = 1;
1596 }
1597 $redirid = $this->getArticleID();
1598
1599 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1600 $dbw =& wfGetDB( DB_MASTER );
1601 $categorylinks = $dbw->tableName( 'categorylinks' );
1602 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1603 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1604 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1605 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1606
1607 # Update watchlists
1608
1609 $oldnamespace = $this->getNamespace() & ~1;
1610 $newnamespace = $nt->getNamespace() & ~1;
1611 $oldtitle = $this->getDBkey();
1612 $newtitle = $nt->getDBkey();
1613
1614 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1615 WatchedItem::duplicateEntries( $this, $nt );
1616 }
1617
1618 # Update search engine
1619 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1620 $u->doUpdate();
1621 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1622 $u->doUpdate();
1623
1624 # Update site_stats
1625 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1626 # Moved out of main namespace
1627 # not viewed, edited, removing
1628 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1629 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1630 # Moved into main namespace
1631 # not viewed, edited, adding
1632 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1633 } elseif ( $pageCountChange ) {
1634 # Added redirect
1635 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1636 } else{
1637 $u = false;
1638 }
1639 if ( $u ) {
1640 $u->doUpdate();
1641 }
1642
1643 global $wgUser;
1644 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1645 return true;
1646 }
1647
1648 /**
1649 * Move page to a title which is at present a redirect to the
1650 * source page
1651 *
1652 * @param Title &$nt the page to move to, which should currently
1653 * be a redirect
1654 * @access private
1655 */
1656 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1657 global $wgUser, $wgUseSquid, $wgMwRedir;
1658 $fname = 'Title::moveOverExistingRedirect';
1659 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1660
1661 if ( $reason ) {
1662 $comment .= ": $reason";
1663 }
1664
1665 $now = wfTimestampNow();
1666 $rand = wfRandom();
1667 $newid = $nt->getArticleID();
1668 $oldid = $this->getArticleID();
1669 $dbw =& wfGetDB( DB_MASTER );
1670 $linkCache =& LinkCache::singleton();
1671
1672 # Delete the old redirect. We don't save it to history since
1673 # by definition if we've got here it's rather uninteresting.
1674 # We have to remove it so that the next step doesn't trigger
1675 # a conflict on the unique namespace+title index...
1676 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1677
1678 # Save a null revision in the page's history notifying of the move
1679 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1680 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1681 true );
1682 $nullRevId = $nullRevision->insertOn( $dbw );
1683
1684 # Change the name of the target page:
1685 $dbw->update( 'page',
1686 /* SET */ array(
1687 'page_touched' => $dbw->timestamp($now),
1688 'page_namespace' => $nt->getNamespace(),
1689 'page_title' => $nt->getDBkey(),
1690 'page_latest' => $nullRevId,
1691 ),
1692 /* WHERE */ array( 'page_id' => $oldid ),
1693 $fname
1694 );
1695 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1696
1697 # Recreate the redirect, this time in the other direction.
1698 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1699 $redirectArticle = new Article( $this );
1700 $newid = $redirectArticle->insertOn( $dbw );
1701 $redirectRevision = new Revision( array(
1702 'page' => $newid,
1703 'comment' => $comment,
1704 'text' => $redirectText ) );
1705 $revid = $redirectRevision->insertOn( $dbw );
1706 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1707 $linkCache->clearLink( $this->getPrefixedDBkey() );
1708
1709 # Log the move
1710 $log = new LogPage( 'move' );
1711 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1712
1713 # Now, we record the link from the redirect to the new title.
1714 # It should have no other outgoing links...
1715 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1716 $dbw->insert( 'pagelinks',
1717 array(
1718 'pl_from' => $newid,
1719 'pl_namespace' => $nt->getNamespace(),
1720 'pl_title' => $nt->getDbKey() ),
1721 $fname );
1722
1723 # Purge squid
1724 if ( $wgUseSquid ) {
1725 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1726 $u = new SquidUpdate( $urls );
1727 $u->doUpdate();
1728 }
1729 }
1730
1731 /**
1732 * Move page to non-existing title.
1733 * @param Title &$nt the new Title
1734 * @access private
1735 */
1736 function moveToNewTitle( &$nt, $reason = '' ) {
1737 global $wgUser, $wgUseSquid;
1738 global $wgMwRedir;
1739 $fname = 'MovePageForm::moveToNewTitle';
1740 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1741 if ( $reason ) {
1742 $comment .= ": $reason";
1743 }
1744
1745 $newid = $nt->getArticleID();
1746 $oldid = $this->getArticleID();
1747 $dbw =& wfGetDB( DB_MASTER );
1748 $now = $dbw->timestamp();
1749 $rand = wfRandom();
1750 $linkCache =& LinkCache::singleton();
1751
1752 # Save a null revision in the page's history notifying of the move
1753 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1754 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1755 true );
1756 $nullRevId = $nullRevision->insertOn( $dbw );
1757
1758 # Rename cur entry
1759 $dbw->update( 'page',
1760 /* SET */ array(
1761 'page_touched' => $now,
1762 'page_namespace' => $nt->getNamespace(),
1763 'page_title' => $nt->getDBkey(),
1764 'page_latest' => $nullRevId,
1765 ),
1766 /* WHERE */ array( 'page_id' => $oldid ),
1767 $fname
1768 );
1769
1770 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1771
1772 # Insert redirect
1773 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1774 $redirectArticle = new Article( $this );
1775 $newid = $redirectArticle->insertOn( $dbw );
1776 $redirectRevision = new Revision( array(
1777 'page' => $newid,
1778 'comment' => $comment,
1779 'text' => $redirectText ) );
1780 $revid = $redirectRevision->insertOn( $dbw );
1781 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1782 $linkCache->clearLink( $this->getPrefixedDBkey() );
1783
1784 # Log the move
1785 $log = new LogPage( 'move' );
1786 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1787
1788 # Purge caches as per article creation
1789 Article::onArticleCreate( $nt );
1790
1791 # Record the just-created redirect's linking to the page
1792 $dbw->insert( 'pagelinks',
1793 array(
1794 'pl_from' => $newid,
1795 'pl_namespace' => $nt->getNamespace(),
1796 'pl_title' => $nt->getDBkey() ),
1797 $fname );
1798
1799 # Non-existent target may have had broken links to it; these must
1800 # now be touched to update link coloring.
1801 $nt->touchLinks();
1802
1803 # Purge old title from squid
1804 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1805 $titles = $nt->getLinksTo();
1806 if ( $wgUseSquid ) {
1807 $urls = $this->getSquidURLs();
1808 foreach ( $titles as $linkTitle ) {
1809 $urls[] = $linkTitle->getInternalURL();
1810 }
1811 $u = new SquidUpdate( $urls );
1812 $u->doUpdate();
1813 }
1814 }
1815
1816 /**
1817 * Checks if $this can be moved to a given Title
1818 * - Selects for update, so don't call it unless you mean business
1819 *
1820 * @param Title &$nt the new title to check
1821 * @access public
1822 */
1823 function isValidMoveTarget( $nt ) {
1824
1825 $fname = 'Title::isValidMoveTarget';
1826 $dbw =& wfGetDB( DB_MASTER );
1827
1828 # Is it a redirect?
1829 $id = $nt->getArticleID();
1830 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1831 array( 'page_is_redirect','old_text','old_flags' ),
1832 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1833 $fname, 'FOR UPDATE' );
1834
1835 if ( !$obj || 0 == $obj->page_is_redirect ) {
1836 # Not a redirect
1837 return false;
1838 }
1839 $text = Revision::getRevisionText( $obj );
1840
1841 # Does the redirect point to the source?
1842 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1843 $redirTitle = Title::newFromText( $m[1] );
1844 if( !is_object( $redirTitle ) ||
1845 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1846 return false;
1847 }
1848 } else {
1849 # Fail safe
1850 return false;
1851 }
1852
1853 # Does the article have a history?
1854 $row = $dbw->selectRow( array( 'page', 'revision'),
1855 array( 'rev_id' ),
1856 array( 'page_namespace' => $nt->getNamespace(),
1857 'page_title' => $nt->getDBkey(),
1858 'page_id=rev_page AND page_latest != rev_id'
1859 ), $fname, 'FOR UPDATE'
1860 );
1861
1862 # Return true if there was no history
1863 return $row === false;
1864 }
1865
1866 /**
1867 * Create a redirect; fails if the title already exists; does
1868 * not notify RC
1869 *
1870 * @param Title $dest the destination of the redirect
1871 * @param string $comment the comment string describing the move
1872 * @return bool true on success
1873 * @access public
1874 */
1875 function createRedirect( $dest, $comment ) {
1876 global $wgUser;
1877 if ( $this->getArticleID() ) {
1878 return false;
1879 }
1880
1881 $fname = 'Title::createRedirect';
1882 $dbw =& wfGetDB( DB_MASTER );
1883
1884 $article = new Article( $this );
1885 $newid = $article->insertOn( $dbw );
1886 $revision = new Revision( array(
1887 'page' => $newid,
1888 'comment' => $comment,
1889 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1890 ) );
1891 $revisionId = $revision->insertOn( $dbw );
1892 $article->updateRevisionOn( $dbw, $revision, 0 );
1893
1894 # Link table
1895 $dbw->insert( 'pagelinks',
1896 array(
1897 'pl_from' => $newid,
1898 'pl_namespace' => $dest->getNamespace(),
1899 'pl_title' => $dest->getDbKey()
1900 ), $fname
1901 );
1902
1903 Article::onArticleCreate( $this );
1904 return true;
1905 }
1906
1907 /**
1908 * Get categories to which this Title belongs and return an array of
1909 * categories' names.
1910 *
1911 * @return array an array of parents in the form:
1912 * $parent => $currentarticle
1913 * @access public
1914 */
1915 function getParentCategories() {
1916 global $wgContLang,$wgUser;
1917
1918 $titlekey = $this->getArticleId();
1919 $dbr =& wfGetDB( DB_SLAVE );
1920 $categorylinks = $dbr->tableName( 'categorylinks' );
1921
1922 # NEW SQL
1923 $sql = "SELECT * FROM $categorylinks"
1924 ." WHERE cl_from='$titlekey'"
1925 ." AND cl_from <> '0'"
1926 ." ORDER BY cl_sortkey";
1927
1928 $res = $dbr->query ( $sql ) ;
1929
1930 if($dbr->numRows($res) > 0) {
1931 while ( $x = $dbr->fetchObject ( $res ) )
1932 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1933 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1934 $dbr->freeResult ( $res ) ;
1935 } else {
1936 $data = '';
1937 }
1938 return $data;
1939 }
1940
1941 /**
1942 * Get a tree of parent categories
1943 * @param array $children an array with the children in the keys, to check for circular refs
1944 * @return array
1945 * @access public
1946 */
1947 function getParentCategoryTree( $children = array() ) {
1948 $parents = $this->getParentCategories();
1949
1950 if($parents != '') {
1951 foreach($parents as $parent => $current) {
1952 if ( array_key_exists( $parent, $children ) ) {
1953 # Circular reference
1954 $stack[$parent] = array();
1955 } else {
1956 $nt = Title::newFromText($parent);
1957 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1958 }
1959 }
1960 return $stack;
1961 } else {
1962 return array();
1963 }
1964 }
1965
1966
1967 /**
1968 * Get an associative array for selecting this title from
1969 * the "page" table
1970 *
1971 * @return array
1972 * @access public
1973 */
1974 function pageCond() {
1975 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
1976 }
1977
1978 /**
1979 * Get the revision ID of the previous revision
1980 *
1981 * @param integer $revision Revision ID. Get the revision that was before this one.
1982 * @return interger $oldrevision|false
1983 */
1984 function getPreviousRevisionID( $revision ) {
1985 $dbr =& wfGetDB( DB_SLAVE );
1986 return $dbr->selectField( 'revision', 'rev_id',
1987 'rev_page=' . intval( $this->getArticleId() ) .
1988 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
1989 }
1990
1991 /**
1992 * Get the revision ID of the next revision
1993 *
1994 * @param integer $revision Revision ID. Get the revision that was after this one.
1995 * @return interger $oldrevision|false
1996 */
1997 function getNextRevisionID( $revision ) {
1998 $dbr =& wfGetDB( DB_SLAVE );
1999 return $dbr->selectField( 'revision', 'rev_id',
2000 'rev_page=' . intval( $this->getArticleId() ) .
2001 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2002 }
2003
2004 /**
2005 * Compare with another title.
2006 *
2007 * @param Title $title
2008 * @return bool
2009 */
2010 function equals( $title ) {
2011 return $this->getInterwiki() == $title->getInterwiki()
2012 && $this->getNamespace() == $title->getNamespace()
2013 && $this->getDbkey() == $title->getDbkey();
2014 }
2015
2016 /**
2017 * Check if page exists
2018 * @return bool
2019 */
2020 function exists() {
2021 return $this->getArticleId() != 0;
2022 }
2023
2024 /**
2025 * Should a link should be displayed as a known link, just based on its title?
2026 *
2027 * Currently, a self-link with a fragment and special pages are in
2028 * this category. Special pages never exist in the database.
2029 */
2030 function isAlwaysKnown() {
2031 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2032 || NS_SPECIAL == $this->mNamespace;
2033 }
2034
2035 /**
2036 * Update page_touched timestamps on pages linking to this title.
2037 * In principal, this could be backgrounded and could also do squid
2038 * purging.
2039 */
2040 function touchLinks() {
2041 $fname = 'Title::touchLinks';
2042
2043 $dbw =& wfGetDB( DB_MASTER );
2044
2045 $res = $dbw->select( 'pagelinks',
2046 array( 'pl_from' ),
2047 array(
2048 'pl_namespace' => $this->getNamespace(),
2049 'pl_title' => $this->getDbKey() ),
2050 $fname );
2051
2052 $toucharr = array();
2053 while( $row = $dbw->fetchObject( $res ) ) {
2054 $toucharr[] = $row->pl_from;
2055 }
2056 $dbw->freeResult( $res );
2057
2058 if( $this->getNamespace() == NS_CATEGORY ) {
2059 // Categories show up in a separate set of links as well
2060 $res = $dbw->select( 'categorylinks',
2061 array( 'cl_from' ),
2062 array( 'cl_to' => $this->getDbKey() ),
2063 $fname );
2064 while( $row = $dbw->fetchObject( $res ) ) {
2065 $toucharr[] = $row->cl_from;
2066 }
2067 $dbw->freeResult( $res );
2068 }
2069
2070 if (!count($toucharr))
2071 return;
2072 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2073 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2074 }
2075
2076 function trackbackURL() {
2077 global $wgTitle, $wgScriptPath, $wgServer;
2078
2079 return "$wgServer$wgScriptPath/trackback.php?article="
2080 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2081 }
2082
2083 function trackbackRDF() {
2084 $url = htmlspecialchars($this->getFullURL());
2085 $title = htmlspecialchars($this->getText());
2086 $tburl = $this->trackbackURL();
2087
2088 return "
2089 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2090 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2091 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2092 <rdf:Description
2093 rdf:about=\"$url\"
2094 dc:identifier=\"$url\"
2095 dc:title=\"$title\"
2096 trackback:ping=\"$tburl\" />
2097 </rdf:RDF>";
2098 }
2099 }
2100 ?>