commit early, commit often!
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?php
2
3 /**
4 * Global functions used everywhere
5 * @package MediaWiki
6 */
7
8 /**
9 * Some globals and requires needed
10 */
11
12 /**
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
15 */
16 $wgNumberOfArticles = -1; # Unset
17 /**
18 * Total number of views
19 * @global integer $wgTotalViews
20 */
21 $wgTotalViews = -1;
22 /**
23 * Total number of edits
24 * @global integer $wgTotalEdits
25 */
26 $wgTotalEdits = -1;
27
28
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'LogPage.php' );
31 require_once( 'normal/UtfNormalUtil.php' );
32 require_once( 'XmlFunctions.php' );
33
34 /**
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
39 */
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
48 return $string;
49 }
50 }
51
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
56 }
57 }
58
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
62 return
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
65 }
66 }
67
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
72
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
76 } else {
77 return join( '', array_slice( $ar[0], $start ) );
78 }
79 }
80 }
81
82 if( !function_exists( 'floatval' ) ) {
83 /**
84 * First defined in PHP 4.2.0
85 * @param mixed $var;
86 * @return float
87 */
88 function floatval( $var ) {
89 return (float)$var;
90 }
91 }
92
93 if ( !function_exists( 'array_diff_key' ) ) {
94 /**
95 * Exists in PHP 5.1.0+
96 * Not quite compatible, two-argument version only
97 * Null values will cause problems due to this use of isset()
98 */
99 function array_diff_key( $left, $right ) {
100 $result = $left;
101 foreach ( $left as $key => $value ) {
102 if ( isset( $right[$key] ) ) {
103 unset( $result[$key] );
104 }
105 }
106 return $result;
107 }
108 }
109
110
111 /**
112 * Wrapper for clone() for PHP 4, for the moment.
113 * PHP 5 won't let you declare a 'clone' function, even conditionally,
114 * so it has to be a wrapper with a different name.
115 */
116 function wfClone( $object ) {
117 // WARNING: clone() is not a function in PHP 5, so function_exists fails.
118 if( version_compare( PHP_VERSION, '5.0' ) < 0 ) {
119 return $object;
120 } else {
121 return clone( $object );
122 }
123 }
124
125 /**
126 * Where as we got a random seed
127 * @var bool $wgTotalViews
128 */
129 $wgRandomSeeded = false;
130
131 /**
132 * Seed Mersenne Twister
133 * Only necessary in PHP < 4.2.0
134 *
135 * @return bool
136 */
137 function wfSeedRandom() {
138 global $wgRandomSeeded;
139
140 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
141 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
142 mt_srand( $seed );
143 $wgRandomSeeded = true;
144 }
145 }
146
147 /**
148 * Get a random decimal value between 0 and 1, in a way
149 * not likely to give duplicate values for any realistic
150 * number of articles.
151 *
152 * @return string
153 */
154 function wfRandom() {
155 # The maximum random value is "only" 2^31-1, so get two random
156 # values to reduce the chance of dupes
157 $max = mt_getrandmax();
158 $rand = number_format( (mt_rand() * $max + mt_rand())
159 / $max / $max, 12, '.', '' );
160 return $rand;
161 }
162
163 /**
164 * We want / and : to be included as literal characters in our title URLs.
165 * %2F in the page titles seems to fatally break for some reason.
166 *
167 * @param $s String:
168 * @return string
169 */
170 function wfUrlencode ( $s ) {
171 $s = urlencode( $s );
172 $s = preg_replace( '/%3[Aa]/', ':', $s );
173 $s = preg_replace( '/%2[Ff]/', '/', $s );
174
175 return $s;
176 }
177
178 /**
179 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
180 * In normal operation this is a NOP.
181 *
182 * Controlling globals:
183 * $wgDebugLogFile - points to the log file
184 * $wgProfileOnly - if set, normal debug messages will not be recorded.
185 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
186 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
187 *
188 * @param $text String
189 * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
190 */
191 function wfDebug( $text, $logonly = false ) {
192 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
193
194 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
195 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
196 return;
197 }
198
199 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
200 $wgOut->debug( $text );
201 }
202 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
203 # Strip unprintables; they can switch terminal modes when binary data
204 # gets dumped, which is pretty annoying.
205 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
206 @error_log( $text, 3, $wgDebugLogFile );
207 }
208 }
209
210 /**
211 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
212 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
213 *
214 * @param $logGroup String
215 * @param $text String
216 * @param $public Bool: whether to log the event in the public log if no private
217 * log file is specified, (default true)
218 */
219 function wfDebugLog( $logGroup, $text, $public = true ) {
220 global $wgDebugLogGroups, $wgDBname;
221 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
222 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
223 $time = wfTimestamp( TS_DB );
224 @error_log( "$time $wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
225 } else if ( $public === true ) {
226 wfDebug( $text, true );
227 }
228 }
229
230 /**
231 * Log for database errors
232 * @param $text String: database error message.
233 */
234 function wfLogDBError( $text ) {
235 global $wgDBerrorLog;
236 if ( $wgDBerrorLog ) {
237 $host = trim(`hostname`);
238 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
239 error_log( $text, 3, $wgDBerrorLog );
240 }
241 }
242
243 /**
244 * @todo document
245 */
246 function wfLogProfilingData() {
247 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
248 global $wgProfiling, $wgUser;
249 if ( $wgProfiling ) {
250 $now = wfTime();
251 $elapsed = $now - $wgRequestTime;
252 $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
253 $forward = '';
254 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
255 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
256 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
257 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
258 if( !empty( $_SERVER['HTTP_FROM'] ) )
259 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
260 if( $forward )
261 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
262 // Don't unstub $wgUser at this late stage just for statistics purposes
263 if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
264 $forward .= ' anon';
265 $log = sprintf( "%s\t%04.3f\t%s\n",
266 gmdate( 'YmdHis' ), $elapsed,
267 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
268 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
269 error_log( $log . $prof, 3, $wgDebugLogFile );
270 }
271 }
272 }
273
274 /**
275 * Check if the wiki read-only lock file is present. This can be used to lock
276 * off editing functions, but doesn't guarantee that the database will not be
277 * modified.
278 * @return bool
279 */
280 function wfReadOnly() {
281 global $wgReadOnlyFile, $wgReadOnly;
282
283 if ( !is_null( $wgReadOnly ) ) {
284 return (bool)$wgReadOnly;
285 }
286 if ( '' == $wgReadOnlyFile ) {
287 return false;
288 }
289 // Set $wgReadOnly for faster access next time
290 if ( is_file( $wgReadOnlyFile ) ) {
291 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
292 } else {
293 $wgReadOnly = false;
294 }
295 return (bool)$wgReadOnly;
296 }
297
298
299 /**
300 * Get a message from anywhere, for the current user language.
301 *
302 * Use wfMsgForContent() instead if the message should NOT
303 * change depending on the user preferences.
304 *
305 * Note that the message may contain HTML, and is therefore
306 * not safe for insertion anywhere. Some functions such as
307 * addWikiText will do the escaping for you. Use wfMsgHtml()
308 * if you need an escaped message.
309 *
310 * @param $key String: lookup key for the message, usually
311 * defined in languages/Language.php
312 */
313 function wfMsg( $key ) {
314 $args = func_get_args();
315 array_shift( $args );
316 return wfMsgReal( $key, $args, true );
317 }
318
319 /**
320 * Same as above except doesn't transform the message
321 */
322 function wfMsgNoTrans( $key ) {
323 $args = func_get_args();
324 array_shift( $args );
325 return wfMsgReal( $key, $args, true, false );
326 }
327
328 /**
329 * Get a message from anywhere, for the current global language
330 * set with $wgLanguageCode.
331 *
332 * Use this if the message should NOT change dependent on the
333 * language set in the user's preferences. This is the case for
334 * most text written into logs, as well as link targets (such as
335 * the name of the copyright policy page). Link titles, on the
336 * other hand, should be shown in the UI language.
337 *
338 * Note that MediaWiki allows users to change the user interface
339 * language in their preferences, but a single installation
340 * typically only contains content in one language.
341 *
342 * Be wary of this distinction: If you use wfMsg() where you should
343 * use wfMsgForContent(), a user of the software may have to
344 * customize over 70 messages in order to, e.g., fix a link in every
345 * possible language.
346 *
347 * @param $key String: lookup key for the message, usually
348 * defined in languages/Language.php
349 */
350 function wfMsgForContent( $key ) {
351 global $wgForceUIMsgAsContentMsg;
352 $args = func_get_args();
353 array_shift( $args );
354 $forcontent = true;
355 if( is_array( $wgForceUIMsgAsContentMsg ) &&
356 in_array( $key, $wgForceUIMsgAsContentMsg ) )
357 $forcontent = false;
358 return wfMsgReal( $key, $args, true, $forcontent );
359 }
360
361 /**
362 * Same as above except doesn't transform the message
363 */
364 function wfMsgForContentNoTrans( $key ) {
365 global $wgForceUIMsgAsContentMsg;
366 $args = func_get_args();
367 array_shift( $args );
368 $forcontent = true;
369 if( is_array( $wgForceUIMsgAsContentMsg ) &&
370 in_array( $key, $wgForceUIMsgAsContentMsg ) )
371 $forcontent = false;
372 return wfMsgReal( $key, $args, true, $forcontent, false );
373 }
374
375 /**
376 * Get a message from the language file, for the UI elements
377 */
378 function wfMsgNoDB( $key ) {
379 $args = func_get_args();
380 array_shift( $args );
381 return wfMsgReal( $key, $args, false );
382 }
383
384 /**
385 * Get a message from the language file, for the content
386 */
387 function wfMsgNoDBForContent( $key ) {
388 global $wgForceUIMsgAsContentMsg;
389 $args = func_get_args();
390 array_shift( $args );
391 $forcontent = true;
392 if( is_array( $wgForceUIMsgAsContentMsg ) &&
393 in_array( $key, $wgForceUIMsgAsContentMsg ) )
394 $forcontent = false;
395 return wfMsgReal( $key, $args, false, $forcontent );
396 }
397
398
399 /**
400 * Really get a message
401 * @return $key String: key to get.
402 * @return $args
403 * @return $useDB Boolean
404 * @return String: the requested message.
405 */
406 function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
407 $fname = 'wfMsgReal';
408
409 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
410 $message = wfMsgReplaceArgs( $message, $args );
411 return $message;
412 }
413
414 /**
415 * This function provides the message source for messages to be edited which are *not* stored in the database.
416 * @param $key String:
417 */
418 function wfMsgWeirdKey ( $key ) {
419 $subsource = str_replace ( ' ' , '_' , $key ) ;
420 $source = wfMsgForContentNoTrans( $subsource ) ;
421 if ( $source == "&lt;{$subsource}&gt;" ) {
422 # Try again with first char lower case
423 $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
424 $source = wfMsgForContentNoTrans( $subsource ) ;
425 }
426 if ( $source == "&lt;{$subsource}&gt;" ) {
427 # Didn't work either, return blank text
428 $source = "" ;
429 }
430 return $source ;
431 }
432
433 /**
434 * Fetch a message string value, but don't replace any keys yet.
435 * @param string $key
436 * @param bool $useDB
437 * @param bool $forContent
438 * @return string
439 * @private
440 */
441 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
442 global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
443
444 if ( is_object( $wgMessageCache ) )
445 $transstat = $wgMessageCache->getTransform();
446
447 if( is_object( $wgMessageCache ) ) {
448 if ( ! $transform )
449 $wgMessageCache->disableTransform();
450 $message = $wgMessageCache->get( $key, $useDB, $forContent );
451 } else {
452 if( $forContent ) {
453 $lang = &$wgContLang;
454 } else {
455 $lang = &$wgLang;
456 }
457
458 wfSuppressWarnings();
459
460 if( is_object( $lang ) ) {
461 $message = $lang->getMessage( $key );
462 } else {
463 $message = false;
464 }
465 wfRestoreWarnings();
466 if($message === false)
467 $message = Language::getMessage($key);
468 if ( $transform && strstr( $message, '{{' ) !== false ) {
469 $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
470 }
471 }
472
473 if ( is_object( $wgMessageCache ) && ! $transform )
474 $wgMessageCache->setTransform( $transstat );
475
476 return $message;
477 }
478
479 /**
480 * Replace message parameter keys on the given formatted output.
481 *
482 * @param string $message
483 * @param array $args
484 * @return string
485 * @private
486 */
487 function wfMsgReplaceArgs( $message, $args ) {
488 # Fix windows line-endings
489 # Some messages are split with explode("\n", $msg)
490 $message = str_replace( "\r", '', $message );
491
492 // Replace arguments
493 if ( count( $args ) ) {
494 if ( is_array( $args[0] ) ) {
495 foreach ( $args[0] as $key => $val ) {
496 $message = str_replace( '$' . $key, $val, $message );
497 }
498 } else {
499 foreach( $args as $n => $param ) {
500 $replacementKeys['$' . ($n + 1)] = $param;
501 }
502 $message = strtr( $message, $replacementKeys );
503 }
504 }
505
506 return $message;
507 }
508
509 /**
510 * Return an HTML-escaped version of a message.
511 * Parameter replacements, if any, are done *after* the HTML-escaping,
512 * so parameters may contain HTML (eg links or form controls). Be sure
513 * to pre-escape them if you really do want plaintext, or just wrap
514 * the whole thing in htmlspecialchars().
515 *
516 * @param string $key
517 * @param string ... parameters
518 * @return string
519 */
520 function wfMsgHtml( $key ) {
521 $args = func_get_args();
522 array_shift( $args );
523 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
524 }
525
526 /**
527 * Return an HTML version of message
528 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
529 * so parameters may contain HTML (eg links or form controls). Be sure
530 * to pre-escape them if you really do want plaintext, or just wrap
531 * the whole thing in htmlspecialchars().
532 *
533 * @param string $key
534 * @param string ... parameters
535 * @return string
536 */
537 function wfMsgWikiHtml( $key ) {
538 global $wgOut;
539 $args = func_get_args();
540 array_shift( $args );
541 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
542 }
543
544 /**
545 * Returns message in the requested format
546 * @param string $key Key of the message
547 * @param array $options Processing rules:
548 * <i>parse<i>: parses wikitext to html
549 * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
550 * <i>escape<i>: filters message trough htmlspecialchars
551 * <i>replaceafter<i>: parameters are substituted after parsing or escaping
552 */
553 function wfMsgExt( $key, $options ) {
554 global $wgOut, $wgMsgParserOptions, $wgParser;
555
556 $args = func_get_args();
557 array_shift( $args );
558 array_shift( $args );
559
560 if( !is_array($options) ) {
561 $options = array($options);
562 }
563
564 $string = wfMsgGetKey( $key, true, false, false );
565
566 if( !in_array('replaceafter', $options) ) {
567 $string = wfMsgReplaceArgs( $string, $args );
568 }
569
570 if( in_array('parse', $options) ) {
571 $string = $wgOut->parse( $string, true, true );
572 } elseif ( in_array('parseinline', $options) ) {
573 $string = $wgOut->parse( $string, true, true );
574 $m = array();
575 if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
576 $string = $m[1];
577 }
578 } elseif ( in_array('parsemag', $options) ) {
579 global $wgTitle;
580 $parser = new Parser();
581 $parserOptions = new ParserOptions();
582 $parserOptions->setInterfaceMessage( true );
583 $parser->startExternalParse( $wgTitle, $parserOptions, OT_MSG );
584 $string = $parser->transformMsg( $string, $parserOptions );
585 }
586
587 if ( in_array('escape', $options) ) {
588 $string = htmlspecialchars ( $string );
589 }
590
591 if( in_array('replaceafter', $options) ) {
592 $string = wfMsgReplaceArgs( $string, $args );
593 }
594
595 return $string;
596 }
597
598
599 /**
600 * Just like exit() but makes a note of it.
601 * Commits open transactions except if the error parameter is set
602 *
603 * @obsolete Please return control to the caller or throw an exception
604 */
605 function wfAbruptExit( $error = false ){
606 global $wgLoadBalancer;
607 static $called = false;
608 if ( $called ){
609 exit( -1 );
610 }
611 $called = true;
612
613 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
614 $bt = debug_backtrace();
615 for($i = 0; $i < count($bt) ; $i++){
616 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
617 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
618 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
619 }
620 } else {
621 wfDebug('WARNING: Abrupt exit\n');
622 }
623
624 wfLogProfilingData();
625
626 if ( !$error ) {
627 $wgLoadBalancer->closeAll();
628 }
629 exit( -1 );
630 }
631
632 /**
633 * @obsolete Please return control the caller or throw an exception
634 */
635 function wfErrorExit() {
636 wfAbruptExit( true );
637 }
638
639 /**
640 * Print a simple message and die, returning nonzero to the shell if any.
641 * Plain die() fails to return nonzero to the shell if you pass a string.
642 * @param string $msg
643 */
644 function wfDie( $msg='' ) {
645 echo $msg;
646 die( 1 );
647 }
648
649 /**
650 * Throw a debugging exception. This function previously once exited the process,
651 * but now throws an exception instead, with similar results.
652 *
653 * @param string $msg Message shown when dieing.
654 */
655 function wfDebugDieBacktrace( $msg = '' ) {
656 throw new MWException( $msg );
657 }
658
659 /**
660 * Fetch server name for use in error reporting etc.
661 * Use real server name if available, so we know which machine
662 * in a server farm generated the current page.
663 * @return string
664 */
665 function wfHostname() {
666 if ( function_exists( 'posix_uname' ) ) {
667 // This function not present on Windows
668 $uname = @posix_uname();
669 } else {
670 $uname = false;
671 }
672 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
673 return $uname['nodename'];
674 } else {
675 # This may be a virtual server.
676 return $_SERVER['SERVER_NAME'];
677 }
678 }
679
680 /**
681 * Returns a HTML comment with the elapsed time since request.
682 * This method has no side effects.
683 * @return string
684 */
685 function wfReportTime() {
686 global $wgRequestTime;
687
688 $now = wfTime();
689 $elapsed = $now - $wgRequestTime;
690
691 $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
692 wfHostname(), $elapsed );
693 return $com;
694 }
695
696 function wfBacktrace() {
697 global $wgCommandLineMode;
698 if ( !function_exists( 'debug_backtrace' ) ) {
699 return false;
700 }
701
702 if ( $wgCommandLineMode ) {
703 $msg = '';
704 } else {
705 $msg = "<ul>\n";
706 }
707 $backtrace = debug_backtrace();
708 foreach( $backtrace as $call ) {
709 if( isset( $call['file'] ) ) {
710 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
711 $file = $f[count($f)-1];
712 } else {
713 $file = '-';
714 }
715 if( isset( $call['line'] ) ) {
716 $line = $call['line'];
717 } else {
718 $line = '-';
719 }
720 if ( $wgCommandLineMode ) {
721 $msg .= "$file line $line calls ";
722 } else {
723 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
724 }
725 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
726 $msg .= $call['function'] . '()';
727
728 if ( $wgCommandLineMode ) {
729 $msg .= "\n";
730 } else {
731 $msg .= "</li>\n";
732 }
733 }
734 if ( $wgCommandLineMode ) {
735 $msg .= "\n";
736 } else {
737 $msg .= "</ul>\n";
738 }
739
740 return $msg;
741 }
742
743
744 /* Some generic result counters, pulled out of SearchEngine */
745
746
747 /**
748 * @todo document
749 */
750 function wfShowingResults( $offset, $limit ) {
751 global $wgLang;
752 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
753 }
754
755 /**
756 * @todo document
757 */
758 function wfShowingResultsNum( $offset, $limit, $num ) {
759 global $wgLang;
760 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
761 }
762
763 /**
764 * @todo document
765 */
766 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
767 global $wgLang;
768 $fmtLimit = $wgLang->formatNum( $limit );
769 $prev = wfMsg( 'prevn', $fmtLimit );
770 $next = wfMsg( 'nextn', $fmtLimit );
771
772 if( is_object( $link ) ) {
773 $title =& $link;
774 } else {
775 $title = Title::newFromText( $link );
776 if( is_null( $title ) ) {
777 return false;
778 }
779 }
780
781 if ( 0 != $offset ) {
782 $po = $offset - $limit;
783 if ( $po < 0 ) { $po = 0; }
784 $q = "limit={$limit}&offset={$po}";
785 if ( '' != $query ) { $q .= '&'.$query; }
786 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
787 } else { $plink = $prev; }
788
789 $no = $offset + $limit;
790 $q = 'limit='.$limit.'&offset='.$no;
791 if ( '' != $query ) { $q .= '&'.$query; }
792
793 if ( $atend ) {
794 $nlink = $next;
795 } else {
796 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
797 }
798 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
799 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
800 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
801 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
802 wfNumLink( $offset, 500, $title, $query );
803
804 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
805 }
806
807 /**
808 * @todo document
809 */
810 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
811 global $wgLang;
812 if ( '' == $query ) { $q = ''; }
813 else { $q = $query.'&'; }
814 $q .= 'limit='.$limit.'&offset='.$offset;
815
816 $fmtLimit = $wgLang->formatNum( $limit );
817 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
818 return $s;
819 }
820
821 /**
822 * @todo document
823 * @todo FIXME: we may want to blacklist some broken browsers
824 *
825 * @return bool Whereas client accept gzip compression
826 */
827 function wfClientAcceptsGzip() {
828 global $wgUseGzip;
829 if( $wgUseGzip ) {
830 # FIXME: we may want to blacklist some broken browsers
831 if( preg_match(
832 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
833 $_SERVER['HTTP_ACCEPT_ENCODING'],
834 $m ) ) {
835 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
836 wfDebug( " accepts gzip\n" );
837 return true;
838 }
839 }
840 return false;
841 }
842
843 /**
844 * Obtain the offset and limit values from the request string;
845 * used in special pages
846 *
847 * @param $deflimit Default limit if none supplied
848 * @param $optionname Name of a user preference to check against
849 * @return array
850 *
851 */
852 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
853 global $wgRequest;
854 return $wgRequest->getLimitOffset( $deflimit, $optionname );
855 }
856
857 /**
858 * Escapes the given text so that it may be output using addWikiText()
859 * without any linking, formatting, etc. making its way through. This
860 * is achieved by substituting certain characters with HTML entities.
861 * As required by the callers, <nowiki> is not used. It currently does
862 * not filter out characters which have special meaning only at the
863 * start of a line, such as "*".
864 *
865 * @param string $text Text to be escaped
866 */
867 function wfEscapeWikiText( $text ) {
868 $text = str_replace(
869 array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
870 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
871 htmlspecialchars($text) );
872 return $text;
873 }
874
875 /**
876 * @todo document
877 */
878 function wfQuotedPrintable( $string, $charset = '' ) {
879 # Probably incomplete; see RFC 2045
880 if( empty( $charset ) ) {
881 global $wgInputEncoding;
882 $charset = $wgInputEncoding;
883 }
884 $charset = strtoupper( $charset );
885 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
886
887 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
888 $replace = $illegal . '\t ?_';
889 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
890 $out = "=?$charset?Q?";
891 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
892 $out .= '?=';
893 return $out;
894 }
895
896
897 /**
898 * @todo document
899 * @return float
900 */
901 function wfTime() {
902 return microtime(true);
903 }
904
905 /**
906 * Sets dest to source and returns the original value of dest
907 * If source is NULL, it just returns the value, it doesn't set the variable
908 */
909 function wfSetVar( &$dest, $source ) {
910 $temp = $dest;
911 if ( !is_null( $source ) ) {
912 $dest = $source;
913 }
914 return $temp;
915 }
916
917 /**
918 * As for wfSetVar except setting a bit
919 */
920 function wfSetBit( &$dest, $bit, $state = true ) {
921 $temp = (bool)($dest & $bit );
922 if ( !is_null( $state ) ) {
923 if ( $state ) {
924 $dest |= $bit;
925 } else {
926 $dest &= ~$bit;
927 }
928 }
929 return $temp;
930 }
931
932 /**
933 * This function takes two arrays as input, and returns a CGI-style string, e.g.
934 * "days=7&limit=100". Options in the first array override options in the second.
935 * Options set to "" will not be output.
936 */
937 function wfArrayToCGI( $array1, $array2 = NULL )
938 {
939 if ( !is_null( $array2 ) ) {
940 $array1 = $array1 + $array2;
941 }
942
943 $cgi = '';
944 foreach ( $array1 as $key => $value ) {
945 if ( '' !== $value ) {
946 if ( '' != $cgi ) {
947 $cgi .= '&';
948 }
949 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
950 }
951 }
952 return $cgi;
953 }
954
955 /**
956 * This is obsolete, use SquidUpdate::purge()
957 * @deprecated
958 */
959 function wfPurgeSquidServers ($urlArr) {
960 SquidUpdate::purge( $urlArr );
961 }
962
963 /**
964 * Windows-compatible version of escapeshellarg()
965 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
966 * function puts single quotes in regardless of OS
967 */
968 function wfEscapeShellArg( ) {
969 $args = func_get_args();
970 $first = true;
971 $retVal = '';
972 foreach ( $args as $arg ) {
973 if ( !$first ) {
974 $retVal .= ' ';
975 } else {
976 $first = false;
977 }
978
979 if ( wfIsWindows() ) {
980 // Escaping for an MSVC-style command line parser
981 // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
982 // Double the backslashes before any double quotes. Escape the double quotes.
983 $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
984 $arg = '';
985 $delim = false;
986 foreach ( $tokens as $token ) {
987 if ( $delim ) {
988 $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
989 } else {
990 $arg .= $token;
991 }
992 $delim = !$delim;
993 }
994 // Double the backslashes before the end of the string, because
995 // we will soon add a quote
996 if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
997 $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
998 }
999
1000 // Add surrounding quotes
1001 $retVal .= '"' . $arg . '"';
1002 } else {
1003 $retVal .= escapeshellarg( $arg );
1004 }
1005 }
1006 return $retVal;
1007 }
1008
1009 /**
1010 * wfMerge attempts to merge differences between three texts.
1011 * Returns true for a clean merge and false for failure or a conflict.
1012 */
1013 function wfMerge( $old, $mine, $yours, &$result ){
1014 global $wgDiff3;
1015
1016 # This check may also protect against code injection in
1017 # case of broken installations.
1018 if(! file_exists( $wgDiff3 ) ){
1019 wfDebug( "diff3 not found\n" );
1020 return false;
1021 }
1022
1023 # Make temporary files
1024 $td = wfTempDir();
1025 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
1026 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
1027 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
1028
1029 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
1030 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
1031 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
1032
1033 # Check for a conflict
1034 $cmd = $wgDiff3 . ' -a --overlap-only ' .
1035 wfEscapeShellArg( $mytextName ) . ' ' .
1036 wfEscapeShellArg( $oldtextName ) . ' ' .
1037 wfEscapeShellArg( $yourtextName );
1038 $handle = popen( $cmd, 'r' );
1039
1040 if( fgets( $handle, 1024 ) ){
1041 $conflict = true;
1042 } else {
1043 $conflict = false;
1044 }
1045 pclose( $handle );
1046
1047 # Merge differences
1048 $cmd = $wgDiff3 . ' -a -e --merge ' .
1049 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
1050 $handle = popen( $cmd, 'r' );
1051 $result = '';
1052 do {
1053 $data = fread( $handle, 8192 );
1054 if ( strlen( $data ) == 0 ) {
1055 break;
1056 }
1057 $result .= $data;
1058 } while ( true );
1059 pclose( $handle );
1060 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
1061
1062 if ( $result === '' && $old !== '' && $conflict == false ) {
1063 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
1064 $conflict = true;
1065 }
1066 return ! $conflict;
1067 }
1068
1069 /**
1070 * @todo document
1071 */
1072 function wfVarDump( $var ) {
1073 global $wgOut;
1074 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
1075 if ( headers_sent() || !@is_object( $wgOut ) ) {
1076 print $s;
1077 } else {
1078 $wgOut->addHTML( $s );
1079 }
1080 }
1081
1082 /**
1083 * Provide a simple HTTP error.
1084 */
1085 function wfHttpError( $code, $label, $desc ) {
1086 global $wgOut;
1087 $wgOut->disable();
1088 header( "HTTP/1.0 $code $label" );
1089 header( "Status: $code $label" );
1090 $wgOut->sendCacheControl();
1091
1092 header( 'Content-type: text/html' );
1093 print "<html><head><title>" .
1094 htmlspecialchars( $label ) .
1095 "</title></head><body><h1>" .
1096 htmlspecialchars( $label ) .
1097 "</h1><p>" .
1098 htmlspecialchars( $desc ) .
1099 "</p></body></html>\n";
1100 }
1101
1102 /**
1103 * Converts an Accept-* header into an array mapping string values to quality
1104 * factors
1105 */
1106 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
1107 # No arg means accept anything (per HTTP spec)
1108 if( !$accept ) {
1109 return array( $def => 1 );
1110 }
1111
1112 $prefs = array();
1113
1114 $parts = explode( ',', $accept );
1115
1116 foreach( $parts as $part ) {
1117 # FIXME: doesn't deal with params like 'text/html; level=1'
1118 @list( $value, $qpart ) = explode( ';', $part );
1119 if( !isset( $qpart ) ) {
1120 $prefs[$value] = 1;
1121 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1122 $prefs[$value] = $match[1];
1123 }
1124 }
1125
1126 return $prefs;
1127 }
1128
1129 /**
1130 * Checks if a given MIME type matches any of the keys in the given
1131 * array. Basic wildcards are accepted in the array keys.
1132 *
1133 * Returns the matching MIME type (or wildcard) if a match, otherwise
1134 * NULL if no match.
1135 *
1136 * @param string $type
1137 * @param array $avail
1138 * @return string
1139 * @private
1140 */
1141 function mimeTypeMatch( $type, $avail ) {
1142 if( array_key_exists($type, $avail) ) {
1143 return $type;
1144 } else {
1145 $parts = explode( '/', $type );
1146 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1147 return $parts[0] . '/*';
1148 } elseif( array_key_exists( '*/*', $avail ) ) {
1149 return '*/*';
1150 } else {
1151 return NULL;
1152 }
1153 }
1154 }
1155
1156 /**
1157 * Returns the 'best' match between a client's requested internet media types
1158 * and the server's list of available types. Each list should be an associative
1159 * array of type to preference (preference is a float between 0.0 and 1.0).
1160 * Wildcards in the types are acceptable.
1161 *
1162 * @param array $cprefs Client's acceptable type list
1163 * @param array $sprefs Server's offered types
1164 * @return string
1165 *
1166 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1167 * XXX: generalize to negotiate other stuff
1168 */
1169 function wfNegotiateType( $cprefs, $sprefs ) {
1170 $combine = array();
1171
1172 foreach( array_keys($sprefs) as $type ) {
1173 $parts = explode( '/', $type );
1174 if( $parts[1] != '*' ) {
1175 $ckey = mimeTypeMatch( $type, $cprefs );
1176 if( $ckey ) {
1177 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1178 }
1179 }
1180 }
1181
1182 foreach( array_keys( $cprefs ) as $type ) {
1183 $parts = explode( '/', $type );
1184 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1185 $skey = mimeTypeMatch( $type, $sprefs );
1186 if( $skey ) {
1187 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1188 }
1189 }
1190 }
1191
1192 $bestq = 0;
1193 $besttype = NULL;
1194
1195 foreach( array_keys( $combine ) as $type ) {
1196 if( $combine[$type] > $bestq ) {
1197 $besttype = $type;
1198 $bestq = $combine[$type];
1199 }
1200 }
1201
1202 return $besttype;
1203 }
1204
1205 /**
1206 * Array lookup
1207 * Returns an array where the values in the first array are replaced by the
1208 * values in the second array with the corresponding keys
1209 *
1210 * @return array
1211 */
1212 function wfArrayLookup( $a, $b ) {
1213 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1214 }
1215
1216 /**
1217 * Convenience function; returns MediaWiki timestamp for the present time.
1218 * @return string
1219 */
1220 function wfTimestampNow() {
1221 # return NOW
1222 return wfTimestamp( TS_MW, time() );
1223 }
1224
1225 /**
1226 * Reference-counted warning suppression
1227 */
1228 function wfSuppressWarnings( $end = false ) {
1229 static $suppressCount = 0;
1230 static $originalLevel = false;
1231
1232 if ( $end ) {
1233 if ( $suppressCount ) {
1234 --$suppressCount;
1235 if ( !$suppressCount ) {
1236 error_reporting( $originalLevel );
1237 }
1238 }
1239 } else {
1240 if ( !$suppressCount ) {
1241 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1242 }
1243 ++$suppressCount;
1244 }
1245 }
1246
1247 /**
1248 * Restore error level to previous value
1249 */
1250 function wfRestoreWarnings() {
1251 wfSuppressWarnings( true );
1252 }
1253
1254 # Autodetect, convert and provide timestamps of various types
1255
1256 /**
1257 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1258 */
1259 define('TS_UNIX', 0);
1260
1261 /**
1262 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1263 */
1264 define('TS_MW', 1);
1265
1266 /**
1267 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1268 */
1269 define('TS_DB', 2);
1270
1271 /**
1272 * RFC 2822 format, for E-mail and HTTP headers
1273 */
1274 define('TS_RFC2822', 3);
1275
1276 /**
1277 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1278 *
1279 * This is used by Special:Export
1280 */
1281 define('TS_ISO_8601', 4);
1282
1283 /**
1284 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1285 *
1286 * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1287 * DateTime tag and page 36 for the DateTimeOriginal and
1288 * DateTimeDigitized tags.
1289 */
1290 define('TS_EXIF', 5);
1291
1292 /**
1293 * Oracle format time.
1294 */
1295 define('TS_ORACLE', 6);
1296
1297 /**
1298 * Postgres format time.
1299 */
1300 define('TS_POSTGRES', 7);
1301
1302 /**
1303 * @param mixed $outputtype A timestamp in one of the supported formats, the
1304 * function will autodetect which format is supplied
1305 * and act accordingly.
1306 * @return string Time in the format specified in $outputtype
1307 */
1308 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1309 $uts = 0;
1310 $da = array();
1311 if ($ts==0) {
1312 $uts=time();
1313 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1314 # TS_DB
1315 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1316 (int)$da[2],(int)$da[3],(int)$da[1]);
1317 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D",$ts,$da)) {
1318 # TS_EXIF
1319 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1320 (int)$da[2],(int)$da[3],(int)$da[1]);
1321 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D",$ts,$da)) {
1322 # TS_MW
1323 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1324 (int)$da[2],(int)$da[3],(int)$da[1]);
1325 } elseif (preg_match("/^(\d{1,13})$/D",$ts,$datearray)) {
1326 # TS_UNIX
1327 $uts = $ts;
1328 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1329 # TS_ORACLE
1330 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1331 str_replace("+00:00", "UTC", $ts)));
1332 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1333 # TS_ISO_8601
1334 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1335 (int)$da[2],(int)$da[3],(int)$da[1]);
1336 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/",$ts,$da)) {
1337 # TS_POSTGRES
1338 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1339 (int)$da[2],(int)$da[3],(int)$da[1]);
1340 } else {
1341 # Bogus value; fall back to the epoch...
1342 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1343 $uts = 0;
1344 }
1345
1346
1347 switch($outputtype) {
1348 case TS_UNIX:
1349 return $uts;
1350 case TS_MW:
1351 return gmdate( 'YmdHis', $uts );
1352 case TS_DB:
1353 return gmdate( 'Y-m-d H:i:s', $uts );
1354 case TS_ISO_8601:
1355 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1356 // This shouldn't ever be used, but is included for completeness
1357 case TS_EXIF:
1358 return gmdate( 'Y:m:d H:i:s', $uts );
1359 case TS_RFC2822:
1360 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1361 case TS_ORACLE:
1362 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1363 case TS_POSTGRES:
1364 return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
1365 default:
1366 throw new MWException( 'wfTimestamp() called with illegal output type.');
1367 }
1368 }
1369
1370 /**
1371 * Return a formatted timestamp, or null if input is null.
1372 * For dealing with nullable timestamp columns in the database.
1373 * @param int $outputtype
1374 * @param string $ts
1375 * @return string
1376 */
1377 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1378 if( is_null( $ts ) ) {
1379 return null;
1380 } else {
1381 return wfTimestamp( $outputtype, $ts );
1382 }
1383 }
1384
1385 /**
1386 * Check if the operating system is Windows
1387 *
1388 * @return bool True if it's Windows, False otherwise.
1389 */
1390 function wfIsWindows() {
1391 if (substr(php_uname(), 0, 7) == 'Windows') {
1392 return true;
1393 } else {
1394 return false;
1395 }
1396 }
1397
1398 /**
1399 * Swap two variables
1400 */
1401 function swap( &$x, &$y ) {
1402 $z = $x;
1403 $x = $y;
1404 $y = $z;
1405 }
1406
1407 function wfGetCachedNotice( $name ) {
1408 global $wgOut, $parserMemc, $wgDBname;
1409 $fname = 'wfGetCachedNotice';
1410 wfProfileIn( $fname );
1411
1412 $needParse = false;
1413 $notice = wfMsgForContent( $name );
1414 if( $notice == '&lt;'. $name . ';&gt' || $notice == '-' ) {
1415 wfProfileOut( $fname );
1416 return( false );
1417 }
1418
1419 $cachedNotice = $parserMemc->get( $wgDBname . ':' . $name );
1420 if( is_array( $cachedNotice ) ) {
1421 if( md5( $notice ) == $cachedNotice['hash'] ) {
1422 $notice = $cachedNotice['html'];
1423 } else {
1424 $needParse = true;
1425 }
1426 } else {
1427 $needParse = true;
1428 }
1429
1430 if( $needParse ) {
1431 if( is_object( $wgOut ) ) {
1432 $parsed = $wgOut->parse( $notice );
1433 $parserMemc->set( $wgDBname . ':' . $name, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
1434 $notice = $parsed;
1435 } else {
1436 wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
1437 $notice = '';
1438 }
1439 }
1440
1441 wfProfileOut( $fname );
1442 return $notice;
1443 }
1444
1445 function wfGetNamespaceNotice() {
1446 global $wgTitle;
1447
1448 # Paranoia
1449 if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
1450 return "";
1451
1452 $fname = 'wfGetNamespaceNotice';
1453 wfProfileIn( $fname );
1454
1455 $key = "namespacenotice-" . $wgTitle->getNsText();
1456 $namespaceNotice = wfGetCachedNotice( $key );
1457 if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
1458 $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
1459 } else {
1460 $namespaceNotice = "";
1461 }
1462
1463 wfProfileOut( $fname );
1464 return $namespaceNotice;
1465 }
1466
1467 function wfGetSiteNotice() {
1468 global $wgUser, $wgSiteNotice;
1469 $fname = 'wfGetSiteNotice';
1470 wfProfileIn( $fname );
1471 $siteNotice = '';
1472
1473 if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
1474 if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
1475 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1476 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1477 } else {
1478 $anonNotice = wfGetCachedNotice( 'anonnotice' );
1479 if( !$anonNotice ) {
1480 $siteNotice = wfGetCachedNotice( 'sitenotice' );
1481 $siteNotice = !$siteNotice ? $wgSiteNotice : $siteNotice;
1482 } else {
1483 $siteNotice = $anonNotice;
1484 }
1485 }
1486 }
1487
1488 wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
1489 wfProfileOut( $fname );
1490 return $siteNotice;
1491 }
1492
1493 /** Global singleton instance of MimeMagic. This is initialized on demand,
1494 * please always use the wfGetMimeMagic() function to get the instance.
1495 *
1496 * @private
1497 */
1498 $wgMimeMagic= NULL;
1499
1500 /** Factory functions for the global MimeMagic object.
1501 * This function always returns the same singleton instance of MimeMagic.
1502 * That objects will be instantiated on the first call to this function.
1503 * If needed, the MimeMagic.php file is automatically included by this function.
1504 * @return MimeMagic the global MimeMagic objects.
1505 */
1506 function &wfGetMimeMagic() {
1507 global $wgMimeMagic;
1508
1509 if (!is_null($wgMimeMagic)) {
1510 return $wgMimeMagic;
1511 }
1512
1513 if (!class_exists("MimeMagic")) {
1514 #include on demand
1515 require_once("MimeMagic.php");
1516 }
1517
1518 $wgMimeMagic= new MimeMagic();
1519
1520 return $wgMimeMagic;
1521 }
1522
1523
1524 /**
1525 * Tries to get the system directory for temporary files.
1526 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1527 * and if none are set /tmp is returned as the generic Unix default.
1528 *
1529 * NOTE: When possible, use the tempfile() function to create temporary
1530 * files to avoid race conditions on file creation, etc.
1531 *
1532 * @return string
1533 */
1534 function wfTempDir() {
1535 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1536 $tmp = getenv( $var );
1537 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1538 return $tmp;
1539 }
1540 }
1541 # Hope this is Unix of some kind!
1542 return '/tmp';
1543 }
1544
1545 /**
1546 * Make directory, and make all parent directories if they don't exist
1547 */
1548 function wfMkdirParents( $fullDir, $mode = 0777 ) {
1549 if ( strval( $fullDir ) === '' ) {
1550 return true;
1551 }
1552
1553 # Go back through the paths to find the first directory that exists
1554 $currentDir = $fullDir;
1555 $createList = array();
1556 while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
1557 # Strip trailing slashes
1558 $currentDir = rtrim( $currentDir, '/\\' );
1559
1560 # Add to create list
1561 $createList[] = $currentDir;
1562
1563 # Find next delimiter searching from the end
1564 $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
1565 if ( $p === false ) {
1566 $currentDir = false;
1567 } else {
1568 $currentDir = substr( $currentDir, 0, $p );
1569 }
1570 }
1571
1572 if ( count( $createList ) == 0 ) {
1573 # Directory specified already exists
1574 return true;
1575 } elseif ( $currentDir === false ) {
1576 # Went all the way back to root and it apparently doesn't exist
1577 return false;
1578 }
1579
1580 # Now go forward creating directories
1581 $createList = array_reverse( $createList );
1582 foreach ( $createList as $dir ) {
1583 # use chmod to override the umask, as suggested by the PHP manual
1584 if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
1585 return false;
1586 }
1587 }
1588 return true;
1589 }
1590
1591 /**
1592 * Increment a statistics counter
1593 */
1594 function wfIncrStats( $key ) {
1595 global $wgDBname, $wgMemc;
1596 $key = "$wgDBname:stats:$key";
1597 if ( is_null( $wgMemc->incr( $key ) ) ) {
1598 $wgMemc->add( $key, 1 );
1599 }
1600 }
1601
1602 /**
1603 * @param mixed $nr The number to format
1604 * @param int $acc The number of digits after the decimal point, default 2
1605 * @param bool $round Whether or not to round the value, default true
1606 * @return float
1607 */
1608 function wfPercent( $nr, $acc = 2, $round = true ) {
1609 $ret = sprintf( "%.${acc}f", $nr );
1610 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1611 }
1612
1613 /**
1614 * Encrypt a username/password.
1615 *
1616 * @param string $userid ID of the user
1617 * @param string $password Password of the user
1618 * @return string Hashed password
1619 */
1620 function wfEncryptPassword( $userid, $password ) {
1621 global $wgPasswordSalt;
1622 $p = md5( $password);
1623
1624 if($wgPasswordSalt)
1625 return md5( "{$userid}-{$p}" );
1626 else
1627 return $p;
1628 }
1629
1630 /**
1631 * Appends to second array if $value differs from that in $default
1632 */
1633 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1634 if ( is_null( $changed ) ) {
1635 throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1636 }
1637 if ( $default[$key] !== $value ) {
1638 $changed[$key] = $value;
1639 }
1640 }
1641
1642 /**
1643 * Since wfMsg() and co suck, they don't return false if the message key they
1644 * looked up didn't exist but a XHTML string, this function checks for the
1645 * nonexistance of messages by looking at wfMsg() output
1646 *
1647 * @param $msg The message key looked up
1648 * @param $wfMsgOut The output of wfMsg*()
1649 * @return bool
1650 */
1651 function wfEmptyMsg( $msg, $wfMsgOut ) {
1652 return $wfMsgOut === "&lt;$msg&gt;";
1653 }
1654
1655 /**
1656 * Find out whether or not a mixed variable exists in a string
1657 *
1658 * @param mixed needle
1659 * @param string haystack
1660 * @return bool
1661 */
1662 function in_string( $needle, $str ) {
1663 return strpos( $str, $needle ) !== false;
1664 }
1665
1666 function wfSpecialList( $page, $details ) {
1667 global $wgContLang;
1668 $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
1669 return $page . $details;
1670 }
1671
1672 /**
1673 * Returns a regular expression of url protocols
1674 *
1675 * @return string
1676 */
1677 function wfUrlProtocols() {
1678 global $wgUrlProtocols;
1679
1680 // Support old-style $wgUrlProtocols strings, for backwards compatibility
1681 // with LocalSettings files from 1.5
1682 if ( is_array( $wgUrlProtocols ) ) {
1683 $protocols = array();
1684 foreach ($wgUrlProtocols as $protocol)
1685 $protocols[] = preg_quote( $protocol, '/' );
1686
1687 return implode( '|', $protocols );
1688 } else {
1689 return $wgUrlProtocols;
1690 }
1691 }
1692
1693 /**
1694 * Execute a shell command, with time and memory limits mirrored from the PHP
1695 * configuration if supported.
1696 * @param $cmd Command line, properly escaped for shell.
1697 * @param &$retval optional, will receive the program's exit code.
1698 * (non-zero is usually failure)
1699 * @return collected stdout as a string (trailing newlines stripped)
1700 */
1701 function wfShellExec( $cmd, &$retval=null ) {
1702 global $IP, $wgMaxShellMemory;
1703
1704 if( ini_get( 'safe_mode' ) ) {
1705 wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
1706 $retval = 1;
1707 return "Unable to run external programs in safe mode.";
1708 }
1709
1710 if ( php_uname( 's' ) == 'Linux' ) {
1711 $time = ini_get( 'max_execution_time' );
1712 $mem = intval( $wgMaxShellMemory );
1713
1714 if ( $time > 0 && $mem > 0 ) {
1715 $script = "$IP/bin/ulimit.sh";
1716 if ( is_executable( $script ) ) {
1717 $cmd = escapeshellarg( $script ) . " $time $mem $cmd";
1718 }
1719 }
1720 } elseif ( php_uname( 's' ) == 'Windows NT' ) {
1721 # This is a hack to work around PHP's flawed invocation of cmd.exe
1722 # http://news.php.net/php.internals/21796
1723 $cmd = '"' . $cmd . '"';
1724 }
1725 wfDebug( "wfShellExec: $cmd\n" );
1726
1727 $output = array();
1728 $retval = 1; // error by default?
1729 $lastline = exec( $cmd, $output, $retval );
1730 return implode( "\n", $output );
1731
1732 }
1733
1734 /**
1735 * This function works like "use VERSION" in Perl, the program will die with a
1736 * backtrace if the current version of PHP is less than the version provided
1737 *
1738 * This is useful for extensions which due to their nature are not kept in sync
1739 * with releases, and might depend on other versions of PHP than the main code
1740 *
1741 * Note: PHP might die due to parsing errors in some cases before it ever
1742 * manages to call this function, such is life
1743 *
1744 * @see perldoc -f use
1745 *
1746 * @param mixed $version The version to check, can be a string, an integer, or
1747 * a float
1748 */
1749 function wfUsePHP( $req_ver ) {
1750 $php_ver = PHP_VERSION;
1751
1752 if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
1753 throw new MWException( "PHP $req_ver required--this is only $php_ver" );
1754 }
1755
1756 /**
1757 * This function works like "use VERSION" in Perl except it checks the version
1758 * of MediaWiki, the program will die with a backtrace if the current version
1759 * of MediaWiki is less than the version provided.
1760 *
1761 * This is useful for extensions which due to their nature are not kept in sync
1762 * with releases
1763 *
1764 * @see perldoc -f use
1765 *
1766 * @param mixed $version The version to check, can be a string, an integer, or
1767 * a float
1768 */
1769 function wfUseMW( $req_ver ) {
1770 global $wgVersion;
1771
1772 if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
1773 throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
1774 }
1775
1776 /**
1777 * Escape a string to make it suitable for inclusion in a preg_replace()
1778 * replacement parameter.
1779 *
1780 * @param string $string
1781 * @return string
1782 */
1783 function wfRegexReplacement( $string ) {
1784 $string = str_replace( '\\', '\\\\', $string );
1785 $string = str_replace( '$', '\\$', $string );
1786 return $string;
1787 }
1788
1789 /**
1790 * Return the final portion of a pathname.
1791 * Reimplemented because PHP5's basename() is buggy with multibyte text.
1792 * http://bugs.php.net/bug.php?id=33898
1793 *
1794 * PHP's basename() only considers '\' a pathchar on Windows and Netware.
1795 * We'll consider it so always, as we don't want \s in our Unix paths either.
1796 *
1797 * @param string $path
1798 * @return string
1799 */
1800 function wfBaseName( $path ) {
1801 if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
1802 return $matches[1];
1803 } else {
1804 return '';
1805 }
1806 }
1807
1808 /**
1809 * Make a URL index, appropriate for the el_index field of externallinks.
1810 */
1811 function wfMakeUrlIndex( $url ) {
1812 wfSuppressWarnings();
1813 $bits = parse_url( $url );
1814 wfRestoreWarnings();
1815 if ( !$bits || $bits['scheme'] !== 'http' ) {
1816 return false;
1817 }
1818 // Reverse the labels in the hostname, convert to lower case
1819 $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
1820 // Add an extra dot to the end
1821 if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
1822 $reversedHost .= '.';
1823 }
1824 // Reconstruct the pseudo-URL
1825 $index = "http://$reversedHost";
1826 // Leave out user and password. Add the port, path, query and fragment
1827 if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
1828 if ( isset( $bits['path'] ) ) {
1829 $index .= $bits['path'];
1830 } else {
1831 $index .= '/';
1832 }
1833 if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
1834 if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
1835 return $index;
1836 }
1837
1838 /**
1839 * Do any deferred updates and clear the list
1840 * TODO: This could be in Wiki.php if that class made any sense at all
1841 */
1842 function wfDoUpdates()
1843 {
1844 global $wgPostCommitUpdateList, $wgDeferredUpdateList;
1845 foreach ( $wgDeferredUpdateList as $update ) {
1846 $update->doUpdate();
1847 }
1848 foreach ( $wgPostCommitUpdateList as $update ) {
1849 $update->doUpdate();
1850 }
1851 $wgDeferredUpdateList = array();
1852 $wgPostCommitUpdateList = array();
1853 }
1854
1855 /**
1856 * More or less "markup-safe" explode()
1857 * Ignores any instances of the separator inside <...>
1858 * @param string $separator
1859 * @param string $text
1860 * @return array
1861 */
1862 function wfExplodeMarkup( $separator, $text ) {
1863 $placeholder = "\x00";
1864
1865 // Just in case...
1866 $text = str_replace( $placeholder, '', $text );
1867
1868 // Trim stuff
1869 $replacer = new ReplacerCallback( $separator, $placeholder );
1870 $cleaned = preg_replace_callback( '/(<.*?>)/', array( $replacer, 'go' ), $text );
1871
1872 $items = explode( $separator, $cleaned );
1873 foreach( $items as $i => $str ) {
1874 $items[$i] = str_replace( $placeholder, $separator, $str );
1875 }
1876
1877 return $items;
1878 }
1879
1880 class ReplacerCallback {
1881 function ReplacerCallback( $from, $to ) {
1882 $this->from = $from;
1883 $this->to = $to;
1884 }
1885
1886 function go( $matches ) {
1887 return str_replace( $this->from, $this->to, $matches[1] );
1888 }
1889 }
1890
1891
1892 /**
1893 * Convert an arbitrarily-long digit string from one numeric base
1894 * to another, optionally zero-padding to a minimum column width.
1895 *
1896 * Supports base 2 through 36; digit values 10-36 are represented
1897 * as lowercase letters a-z. Input is case-insensitive.
1898 *
1899 * @param $input string of digits
1900 * @param $sourceBase int 2-36
1901 * @param $destBase int 2-36
1902 * @param $pad int 1 or greater
1903 * @return string or false on invalid input
1904 */
1905 function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
1906 if( $sourceBase < 2 ||
1907 $sourceBase > 36 ||
1908 $destBase < 2 ||
1909 $destBase > 36 ||
1910 $pad < 1 ||
1911 $sourceBase != intval( $sourceBase ) ||
1912 $destBase != intval( $destBase ) ||
1913 $pad != intval( $pad ) ||
1914 !is_string( $input ) ||
1915 $input == '' ) {
1916 return false;
1917 }
1918
1919 $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
1920 $inDigits = array();
1921 $outChars = '';
1922
1923 // Decode and validate input string
1924 $input = strtolower( $input );
1925 for( $i = 0; $i < strlen( $input ); $i++ ) {
1926 $n = strpos( $digitChars, $input{$i} );
1927 if( $n === false || $n > $sourceBase ) {
1928 return false;
1929 }
1930 $inDigits[] = $n;
1931 }
1932
1933 // Iterate over the input, modulo-ing out an output digit
1934 // at a time until input is gone.
1935 while( count( $inDigits ) ) {
1936 $work = 0;
1937 $workDigits = array();
1938
1939 // Long division...
1940 foreach( $inDigits as $digit ) {
1941 $work *= $sourceBase;
1942 $work += $digit;
1943
1944 if( $work < $destBase ) {
1945 // Gonna need to pull another digit.
1946 if( count( $workDigits ) ) {
1947 // Avoid zero-padding; this lets us find
1948 // the end of the input very easily when
1949 // length drops to zero.
1950 $workDigits[] = 0;
1951 }
1952 } else {
1953 // Finally! Actual division!
1954 $workDigits[] = intval( $work / $destBase );
1955
1956 // Isn't it annoying that most programming languages
1957 // don't have a single divide-and-remainder operator,
1958 // even though the CPU implements it that way?
1959 $work = $work % $destBase;
1960 }
1961 }
1962
1963 // All that division leaves us with a remainder,
1964 // which is conveniently our next output digit.
1965 $outChars .= $digitChars[$work];
1966
1967 // And we continue!
1968 $inDigits = $workDigits;
1969 }
1970
1971 while( strlen( $outChars ) < $pad ) {
1972 $outChars .= '0';
1973 }
1974
1975 return strrev( $outChars );
1976 }
1977
1978 /**
1979 * Create an object with a given name and an array of construct parameters
1980 * @param string $name
1981 * @param array $p parameters
1982 */
1983 function wfCreateObject( $name, $p ){
1984 $p = array_values( $p );
1985 switch ( count( $p ) ) {
1986 case 0:
1987 return new $name;
1988 case 1:
1989 return new $name( $p[0] );
1990 case 2:
1991 return new $name( $p[0], $p[1] );
1992 case 3:
1993 return new $name( $p[0], $p[1], $p[2] );
1994 case 4:
1995 return new $name( $p[0], $p[1], $p[2], $p[3] );
1996 case 5:
1997 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
1998 case 6:
1999 return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
2000 default:
2001 throw new MWException( "Too many arguments to construtor in wfCreateObject" );
2002 }
2003 }
2004
2005 /**
2006 * Aliases for modularized functions
2007 */
2008 function wfGetHTTP( $url, $timeout = 'default' ) {
2009 return Http::get( $url, $timeout );
2010 }
2011 function wfIsLocalURL( $url ) {
2012 return Http::isLocalURL( $url );
2013 }
2014
2015 /**
2016 * Initialise php session
2017 */
2018 function wfSetupSession() {
2019 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
2020 if( $wgSessionsInMemcached ) {
2021 require_once( 'MemcachedSessions.php' );
2022 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
2023 # If it's left on 'user' or another setting from another
2024 # application, it will end up failing. Try to recover.
2025 ini_set ( 'session.save_handler', 'files' );
2026 }
2027 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
2028 session_cache_limiter( 'private, must-revalidate' );
2029 @session_start();
2030 }
2031
2032 /**
2033 * Get an object from the precompiled serialized directory
2034 *
2035 * @return mixed The variable on success, false on failure
2036 */
2037 function wfGetPrecompiledData( $name ) {
2038 global $IP;
2039
2040 $file = "$IP/serialized/$name";
2041 if ( file_exists( $file ) ) {
2042 $blob = file_get_contents( $file );
2043 if ( $blob ) {
2044 return unserialize( $blob );
2045 }
2046 }
2047 return false;
2048 }
2049
2050 function wfGetCaller( $level = 2 ) {
2051 $backtrace = debug_backtrace();
2052 if ( isset( $backtrace[$level] ) ) {
2053 if ( isset( $backtrace[$level]['class'] ) ) {
2054 $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
2055 } else {
2056 $caller = $backtrace[$level]['function'];
2057 }
2058 } else {
2059 $caller = 'unknown';
2060 }
2061 return $caller;
2062 }
2063
2064 ?>