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