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