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