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