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