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