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