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