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