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