Hooks! Hoooooks!
[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( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.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 /**
94 * Where as we got a random seed
95 * @var bool $wgTotalViews
96 */
97 $wgRandomSeeded = false;
98
99 /**
100 * Seed Mersenne Twister
101 * Only necessary in PHP < 4.2.0
102 *
103 * @return bool
104 */
105 function wfSeedRandom() {
106 global $wgRandomSeeded;
107
108 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
109 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
110 mt_srand( $seed );
111 $wgRandomSeeded = true;
112 }
113 }
114
115 /**
116 * Get a random decimal value between 0 and 1, in a way
117 * not likely to give duplicate values for any realistic
118 * number of articles.
119 *
120 * @return string
121 */
122 function wfRandom() {
123 # The maximum random value is "only" 2^31-1, so get two random
124 # values to reduce the chance of dupes
125 $max = mt_getrandmax();
126 $rand = number_format( (mt_rand() * $max + mt_rand())
127 / $max / $max, 12, '.', '' );
128 return $rand;
129 }
130
131 /**
132 * We want / and : to be included as literal characters in our title URLs.
133 * %2F in the page titles seems to fatally break for some reason.
134 *
135 * @param string $s
136 * @return string
137 */
138 function wfUrlencode ( $s ) {
139 $s = urlencode( $s );
140 $s = preg_replace( '/%3[Aa]/', ':', $s );
141 $s = preg_replace( '/%2[Ff]/', '/', $s );
142
143 return $s;
144 }
145
146 /**
147 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
148 * In normal operation this is a NOP.
149 *
150 * Controlling globals:
151 * $wgDebugLogFile - points to the log file
152 * $wgProfileOnly - if set, normal debug messages will not be recorded.
153 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
154 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
155 *
156 * @param string $text
157 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
158 */
159 function wfDebug( $text, $logonly = false ) {
160 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
161
162 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
163 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
164 return;
165 }
166
167 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
168 $wgOut->debug( $text );
169 }
170 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
171 # Strip unprintables; they can switch terminal modes when binary data
172 # gets dumped, which is pretty annoying.
173 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
174 @error_log( $text, 3, $wgDebugLogFile );
175 }
176 }
177
178 /**
179 * Send a line to a supplementary debug log file, if configured, or main debug log if not.
180 * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
181 *
182 * @param string $logGroup
183 * @param string $text
184 * @param bool $public Whether to log the event in the public log if no private
185 * log file is specified, (default true)
186 */
187 function wfDebugLog( $logGroup, $text, $public = true ) {
188 global $wgDebugLogGroups, $wgDBname;
189 if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
190 if( isset( $wgDebugLogGroups[$logGroup] ) ) {
191 @error_log( "$wgDBname: $text", 3, $wgDebugLogGroups[$logGroup] );
192 } else if ( $public === true ) {
193 wfDebug( $text, true );
194 }
195 }
196
197 /**
198 * Log for database errors
199 * @param string $text Database error message.
200 */
201 function wfLogDBError( $text ) {
202 global $wgDBerrorLog;
203 if ( $wgDBerrorLog ) {
204 $host = trim(`hostname`);
205 $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
206 error_log( $text, 3, $wgDBerrorLog );
207 }
208 }
209
210 /**
211 * @todo document
212 */
213 function logProfilingData() {
214 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
215 global $wgProfiling, $wgUser;
216 $now = wfTime();
217
218 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
219 $start = (float)$sec + (float)$usec;
220 $elapsed = $now - $start;
221 if ( $wgProfiling ) {
222 $prof = wfGetProfilingOutput( $start, $elapsed );
223 $forward = '';
224 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
225 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
226 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
227 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
228 if( !empty( $_SERVER['HTTP_FROM'] ) )
229 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
230 if( $forward )
231 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
232 if( $wgUser->isAnon() )
233 $forward .= ' anon';
234 $log = sprintf( "%s\t%04.3f\t%s\n",
235 gmdate( 'YmdHis' ), $elapsed,
236 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
237 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
238 error_log( $log . $prof, 3, $wgDebugLogFile );
239 }
240 }
241 }
242
243 /**
244 * Check if the wiki read-only lock file is present. This can be used to lock
245 * off editing functions, but doesn't guarantee that the database will not be
246 * modified.
247 * @return bool
248 */
249 function wfReadOnly() {
250 global $wgReadOnlyFile, $wgReadOnly;
251
252 if ( $wgReadOnly ) {
253 return true;
254 }
255 if ( '' == $wgReadOnlyFile ) {
256 return false;
257 }
258
259 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
260 if ( is_file( $wgReadOnlyFile ) ) {
261 $wgReadOnly = file_get_contents( $wgReadOnlyFile );
262 } else {
263 $wgReadOnly = false;
264 }
265 $wgReadOnlyFile = '';
266 return $wgReadOnly;
267 }
268
269
270 /**
271 * Get a message from anywhere, for the current user language.
272 *
273 * Use wfMsgForContent() instead if the message should NOT
274 * change depending on the user preferences.
275 *
276 * Note that the message may contain HTML, and is therefore
277 * not safe for insertion anywhere. Some functions such as
278 * addWikiText will do the escaping for you. Use wfMsgHtml()
279 * if you need an escaped message.
280 *
281 * @param string lookup key for the message, usually
282 * defined in languages/Language.php
283 */
284 function wfMsg( $key ) {
285 $args = func_get_args();
286 array_shift( $args );
287 return wfMsgReal( $key, $args, true );
288 }
289
290 /**
291 * Same as above except doesn't transform the message
292 */
293 function wfMsgNoTrans( $key ) {
294 $args = func_get_args();
295 array_shift( $args );
296 return wfMsgReal( $key, $args, true, false );
297 }
298
299 /**
300 * Get a message from anywhere, for the current global language
301 * set with $wgLanguageCode.
302 *
303 * Use this if the message should NOT change dependent on the
304 * language set in the user's preferences. This is the case for
305 * most text written into logs, as well as link targets (such as
306 * the name of the copyright policy page). Link titles, on the
307 * other hand, should be shown in the UI language.
308 *
309 * Note that MediaWiki allows users to change the user interface
310 * language in their preferences, but a single installation
311 * typically only contains content in one language.
312 *
313 * Be wary of this distinction: If you use wfMsg() where you should
314 * use wfMsgForContent(), a user of the software may have to
315 * customize over 70 messages in order to, e.g., fix a link in every
316 * possible language.
317 *
318 * @param string lookup key for the message, usually
319 * defined in languages/Language.php
320 */
321 function wfMsgForContent( $key ) {
322 global $wgForceUIMsgAsContentMsg;
323 $args = func_get_args();
324 array_shift( $args );
325 $forcontent = true;
326 if( is_array( $wgForceUIMsgAsContentMsg ) &&
327 in_array( $key, $wgForceUIMsgAsContentMsg ) )
328 $forcontent = false;
329 return wfMsgReal( $key, $args, true, $forcontent );
330 }
331
332 /**
333 * Same as above except doesn't transform the message
334 */
335 function wfMsgForContentNoTrans( $key ) {
336 global $wgForceUIMsgAsContentMsg;
337 $args = func_get_args();
338 array_shift( $args );
339 $forcontent = true;
340 if( is_array( $wgForceUIMsgAsContentMsg ) &&
341 in_array( $key, $wgForceUIMsgAsContentMsg ) )
342 $forcontent = false;
343 return wfMsgReal( $key, $args, true, $forcontent, false );
344 }
345
346 /**
347 * Get a message from the language file, for the UI elements
348 */
349 function wfMsgNoDB( $key ) {
350 $args = func_get_args();
351 array_shift( $args );
352 return wfMsgReal( $key, $args, false );
353 }
354
355 /**
356 * Get a message from the language file, for the content
357 */
358 function wfMsgNoDBForContent( $key ) {
359 global $wgForceUIMsgAsContentMsg;
360 $args = func_get_args();
361 array_shift( $args );
362 $forcontent = true;
363 if( is_array( $wgForceUIMsgAsContentMsg ) &&
364 in_array( $key, $wgForceUIMsgAsContentMsg ) )
365 $forcontent = false;
366 return wfMsgReal( $key, $args, false, $forcontent );
367 }
368
369
370 /**
371 * Really get a message
372 */
373 function wfMsgReal( $key, $args, $useDB, $forContent=false, $transform = true ) {
374 $fname = 'wfMsgReal';
375 wfProfileIn( $fname );
376
377 $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
378 $message = wfMsgReplaceArgs( $message, $args );
379 wfProfileOut( $fname );
380 return $message;
381 }
382
383 /**
384 * Fetch a message string value, but don't replace any keys yet.
385 * @param string $key
386 * @param bool $useDB
387 * @param bool $forContent
388 * @return string
389 * @access private
390 */
391 function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
392 global $wgParser, $wgMsgParserOptions, $wgContLang, $wgMessageCache, $wgLang;
393
394 if ( is_object( $wgMessageCache ) )
395 $transstat = $wgMessageCache->getTransform();
396
397 if( is_object( $wgMessageCache ) ) {
398 if ( ! $transform )
399 $wgMessageCache->disableTransform();
400 $message = $wgMessageCache->get( $key, $useDB, $forContent );
401 } else {
402 if( $forContent ) {
403 $lang = &$wgContLang;
404 } else {
405 $lang = &$wgLang;
406 }
407
408 wfSuppressWarnings();
409
410 if( is_object( $lang ) ) {
411 $message = $lang->getMessage( $key );
412 } else {
413 $message = false;
414 }
415 wfRestoreWarnings();
416 if($message === false)
417 $message = Language::getMessage($key);
418 if ( $transform && strstr( $message, '{{' ) !== false ) {
419 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
420 }
421 }
422
423 if ( is_object( $wgMessageCache ) && ! $transform )
424 $wgMessageCache->setTransform( $transstat );
425
426 return $message;
427 }
428
429 /**
430 * Replace message parameter keys on the given formatted output.
431 *
432 * @param string $message
433 * @param array $args
434 * @return string
435 * @access private
436 */
437 function wfMsgReplaceArgs( $message, $args ) {
438 # Fix windows line-endings
439 # Some messages are split with explode("\n", $msg)
440 $message = str_replace( "\r", '', $message );
441
442 // Replace arguments
443 if ( count( $args ) )
444 if ( is_array( $args[0] ) )
445 foreach ( $args[0] as $key => $val )
446 $message = str_replace( '$' . $key, $val, $message );
447 else {
448 foreach( $args as $n => $param )
449 $replacementKeys['$' . ($n + 1)] = $param;
450 $message = strtr( $message, $replacementKeys );
451 }
452
453 return $message;
454 }
455
456 /**
457 * Return an HTML-escaped version of a message.
458 * Parameter replacements, if any, are done *after* the HTML-escaping,
459 * so parameters may contain HTML (eg links or form controls). Be sure
460 * to pre-escape them if you really do want plaintext, or just wrap
461 * the whole thing in htmlspecialchars().
462 *
463 * @param string $key
464 * @param string ... parameters
465 * @return string
466 */
467 function wfMsgHtml( $key ) {
468 $args = func_get_args();
469 array_shift( $args );
470 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
471 }
472
473 /**
474 * Return an HTML version of message
475 * Parameter replacements, if any, are done *after* parsing the wiki-text message,
476 * so parameters may contain HTML (eg links or form controls). Be sure
477 * to pre-escape them if you really do want plaintext, or just wrap
478 * the whole thing in htmlspecialchars().
479 *
480 * @param string $key
481 * @param string ... parameters
482 * @return string
483 */
484 function wfMsgWikiHtml( $key ) {
485 global $wgOut;
486 $args = func_get_args();
487 array_shift( $args );
488 return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
489 }
490
491 /**
492 * Just like exit() but makes a note of it.
493 * Commits open transactions except if the error parameter is set
494 */
495 function wfAbruptExit( $error = false ){
496 global $wgLoadBalancer;
497 static $called = false;
498 if ( $called ){
499 exit();
500 }
501 $called = true;
502
503 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
504 $bt = debug_backtrace();
505 for($i = 0; $i < count($bt) ; $i++){
506 $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
507 $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
508 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
509 }
510 } else {
511 wfDebug('WARNING: Abrupt exit\n');
512 }
513 if ( !$error ) {
514 $wgLoadBalancer->closeAll();
515 }
516 exit();
517 }
518
519 /**
520 * @todo document
521 */
522 function wfErrorExit() {
523 wfAbruptExit( true );
524 }
525
526 /**
527 * Die with a backtrace
528 * This is meant as a debugging aid to track down where bad data comes from.
529 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
530 *
531 * @param string $msg Message shown when dieing.
532 */
533 function wfDebugDieBacktrace( $msg = '' ) {
534 global $wgCommandLineMode;
535
536 $backtrace = wfBacktrace();
537 if ( $backtrace !== false ) {
538 if ( $wgCommandLineMode ) {
539 $msg .= "\nBacktrace:\n$backtrace";
540 } else {
541 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
542 }
543 }
544 echo $msg;
545 echo wfReportTime()."\n";
546 die( -1 );
547 }
548
549 /**
550 * Returns a HTML comment with the elapsed time since request.
551 * This method has no side effects.
552 * @return string
553 */
554 function wfReportTime() {
555 global $wgRequestTime;
556
557 $now = wfTime();
558 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
559 $start = (float)$sec + (float)$usec;
560 $elapsed = $now - $start;
561
562 # Use real server name if available, so we know which machine
563 # in a server farm generated the current page.
564 if ( function_exists( 'posix_uname' ) ) {
565 $uname = @posix_uname();
566 } else {
567 $uname = false;
568 }
569 if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
570 $hostname = $uname['nodename'];
571 } else {
572 # This may be a virtual server.
573 $hostname = $_SERVER['SERVER_NAME'];
574 }
575 $com = sprintf( "<!-- Served by %s in %01.2f secs. -->",
576 $hostname, $elapsed );
577 return $com;
578 }
579
580 function wfBacktrace() {
581 global $wgCommandLineMode;
582 if ( !function_exists( 'debug_backtrace' ) ) {
583 return false;
584 }
585
586 if ( $wgCommandLineMode ) {
587 $msg = '';
588 } else {
589 $msg = "<ul>\n";
590 }
591 $backtrace = debug_backtrace();
592 foreach( $backtrace as $call ) {
593 if( isset( $call['file'] ) ) {
594 $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
595 $file = $f[count($f)-1];
596 } else {
597 $file = '-';
598 }
599 if( isset( $call['line'] ) ) {
600 $line = $call['line'];
601 } else {
602 $line = '-';
603 }
604 if ( $wgCommandLineMode ) {
605 $msg .= "$file line $line calls ";
606 } else {
607 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
608 }
609 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
610 $msg .= $call['function'] . '()';
611
612 if ( $wgCommandLineMode ) {
613 $msg .= "\n";
614 } else {
615 $msg .= "</li>\n";
616 }
617 }
618 if ( $wgCommandLineMode ) {
619 $msg .= "\n";
620 } else {
621 $msg .= "</ul>\n";
622 }
623
624 return $msg;
625 }
626
627
628 /* Some generic result counters, pulled out of SearchEngine */
629
630
631 /**
632 * @todo document
633 */
634 function wfShowingResults( $offset, $limit ) {
635 global $wgLang;
636 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
637 }
638
639 /**
640 * @todo document
641 */
642 function wfShowingResultsNum( $offset, $limit, $num ) {
643 global $wgLang;
644 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
645 }
646
647 /**
648 * @todo document
649 */
650 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
651 global $wgUser, $wgLang;
652 $fmtLimit = $wgLang->formatNum( $limit );
653 $prev = wfMsg( 'prevn', $fmtLimit );
654 $next = wfMsg( 'nextn', $fmtLimit );
655
656 if( is_object( $link ) ) {
657 $title =& $link;
658 } else {
659 $title = Title::newFromText( $link );
660 if( is_null( $title ) ) {
661 return false;
662 }
663 }
664
665 $sk = $wgUser->getSkin();
666 if ( 0 != $offset ) {
667 $po = $offset - $limit;
668 if ( $po < 0 ) { $po = 0; }
669 $q = "limit={$limit}&offset={$po}";
670 if ( '' != $query ) { $q .= '&'.$query; }
671 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
672 } else { $plink = $prev; }
673
674 $no = $offset + $limit;
675 $q = 'limit='.$limit.'&offset='.$no;
676 if ( '' != $query ) { $q .= '&'.$query; }
677
678 if ( $atend ) {
679 $nlink = $next;
680 } else {
681 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
682 }
683 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
684 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
685 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
686 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
687 wfNumLink( $offset, 500, $title, $query );
688
689 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
690 }
691
692 /**
693 * @todo document
694 */
695 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
696 global $wgUser, $wgLang;
697 if ( '' == $query ) { $q = ''; }
698 else { $q = $query.'&'; }
699 $q .= 'limit='.$limit.'&offset='.$offset;
700
701 $fmtLimit = $wgLang->formatNum( $limit );
702 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
703 return $s;
704 }
705
706 /**
707 * @todo document
708 * @todo FIXME: we may want to blacklist some broken browsers
709 *
710 * @return bool Whereas client accept gzip compression
711 */
712 function wfClientAcceptsGzip() {
713 global $wgUseGzip;
714 if( $wgUseGzip ) {
715 # FIXME: we may want to blacklist some broken browsers
716 if( preg_match(
717 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
718 $_SERVER['HTTP_ACCEPT_ENCODING'],
719 $m ) ) {
720 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
721 wfDebug( " accepts gzip\n" );
722 return true;
723 }
724 }
725 return false;
726 }
727
728 /**
729 * Yay, more global functions!
730 */
731 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
732 global $wgRequest;
733 return $wgRequest->getLimitOffset( $deflimit, $optionname );
734 }
735
736 /**
737 * Escapes the given text so that it may be output using addWikiText()
738 * without any linking, formatting, etc. making its way through. This
739 * is achieved by substituting certain characters with HTML entities.
740 * As required by the callers, <nowiki> is not used. It currently does
741 * not filter out characters which have special meaning only at the
742 * start of a line, such as "*".
743 *
744 * @param string $text Text to be escaped
745 */
746 function wfEscapeWikiText( $text ) {
747 $text = str_replace(
748 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
749 array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', '&#58;//' , "\n&#61;", '&#123;&#123;' ),
750 htmlspecialchars($text) );
751 return $text;
752 }
753
754 /**
755 * @todo document
756 */
757 function wfQuotedPrintable( $string, $charset = '' ) {
758 # Probably incomplete; see RFC 2045
759 if( empty( $charset ) ) {
760 global $wgInputEncoding;
761 $charset = $wgInputEncoding;
762 }
763 $charset = strtoupper( $charset );
764 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
765
766 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
767 $replace = $illegal . '\t ?_';
768 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
769 $out = "=?$charset?Q?";
770 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
771 $out .= '?=';
772 return $out;
773 }
774
775 /**
776 * Returns an escaped string suitable for inclusion in a string literal
777 * for JavaScript source code.
778 * Illegal control characters are assumed not to be present.
779 *
780 * @param string $string
781 * @return string
782 */
783 function wfEscapeJsString( $string ) {
784 // See ECMA 262 section 7.8.4 for string literal format
785 $pairs = array(
786 "\\" => "\\\\",
787 "\"" => "\\\"",
788 '\'' => '\\\'',
789 "\n" => "\\n",
790 "\r" => "\\r",
791
792 # To avoid closing the element or CDATA section
793 "<" => "\\x3c",
794 ">" => "\\x3e",
795 );
796 return strtr( $string, $pairs );
797 }
798
799 /**
800 * @todo document
801 * @return float
802 */
803 function wfTime() {
804 $st = explode( ' ', microtime() );
805 return (float)$st[0] + (float)$st[1];
806 }
807
808 /**
809 * Changes the first character to an HTML entity
810 */
811 function wfHtmlEscapeFirst( $text ) {
812 $ord = ord($text);
813 $newText = substr($text, 1);
814 return "&#$ord;$newText";
815 }
816
817 /**
818 * Sets dest to source and returns the original value of dest
819 * If source is NULL, it just returns the value, it doesn't set the variable
820 */
821 function wfSetVar( &$dest, $source ) {
822 $temp = $dest;
823 if ( !is_null( $source ) ) {
824 $dest = $source;
825 }
826 return $temp;
827 }
828
829 /**
830 * As for wfSetVar except setting a bit
831 */
832 function wfSetBit( &$dest, $bit, $state = true ) {
833 $temp = (bool)($dest & $bit );
834 if ( !is_null( $state ) ) {
835 if ( $state ) {
836 $dest |= $bit;
837 } else {
838 $dest &= ~$bit;
839 }
840 }
841 return $temp;
842 }
843
844 /**
845 * This function takes two arrays as input, and returns a CGI-style string, e.g.
846 * "days=7&limit=100". Options in the first array override options in the second.
847 * Options set to "" will not be output.
848 */
849 function wfArrayToCGI( $array1, $array2 = NULL )
850 {
851 if ( !is_null( $array2 ) ) {
852 $array1 = $array1 + $array2;
853 }
854
855 $cgi = '';
856 foreach ( $array1 as $key => $value ) {
857 if ( '' !== $value ) {
858 if ( '' != $cgi ) {
859 $cgi .= '&';
860 }
861 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
862 }
863 }
864 return $cgi;
865 }
866
867 /**
868 * This is obsolete, use SquidUpdate::purge()
869 * @deprecated
870 */
871 function wfPurgeSquidServers ($urlArr) {
872 SquidUpdate::purge( $urlArr );
873 }
874
875 /**
876 * Windows-compatible version of escapeshellarg()
877 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
878 * function puts single quotes in regardless of OS
879 */
880 function wfEscapeShellArg( ) {
881 $args = func_get_args();
882 $first = true;
883 $retVal = '';
884 foreach ( $args as $arg ) {
885 if ( !$first ) {
886 $retVal .= ' ';
887 } else {
888 $first = false;
889 }
890
891 if ( wfIsWindows() ) {
892 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
893 } else {
894 $retVal .= escapeshellarg( $arg );
895 }
896 }
897 return $retVal;
898 }
899
900 /**
901 * wfMerge attempts to merge differences between three texts.
902 * Returns true for a clean merge and false for failure or a conflict.
903 */
904 function wfMerge( $old, $mine, $yours, &$result ){
905 global $wgDiff3;
906
907 # This check may also protect against code injection in
908 # case of broken installations.
909 if(! file_exists( $wgDiff3 ) ){
910 wfDebug( "diff3 not found\n" );
911 return false;
912 }
913
914 # Make temporary files
915 $td = wfTempDir();
916 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
917 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
918 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
919
920 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
921 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
922 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
923
924 # Check for a conflict
925 $cmd = $wgDiff3 . ' -a --overlap-only ' .
926 wfEscapeShellArg( $mytextName ) . ' ' .
927 wfEscapeShellArg( $oldtextName ) . ' ' .
928 wfEscapeShellArg( $yourtextName );
929 $handle = popen( $cmd, 'r' );
930
931 if( fgets( $handle, 1024 ) ){
932 $conflict = true;
933 } else {
934 $conflict = false;
935 }
936 pclose( $handle );
937
938 # Merge differences
939 $cmd = $wgDiff3 . ' -a -e --merge ' .
940 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
941 $handle = popen( $cmd, 'r' );
942 $result = '';
943 do {
944 $data = fread( $handle, 8192 );
945 if ( strlen( $data ) == 0 ) {
946 break;
947 }
948 $result .= $data;
949 } while ( true );
950 pclose( $handle );
951 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
952
953 if ( $result === '' && $old !== '' && $conflict == false ) {
954 wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
955 $conflict = true;
956 }
957 return ! $conflict;
958 }
959
960 /**
961 * @todo document
962 */
963 function wfVarDump( $var ) {
964 global $wgOut;
965 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
966 if ( headers_sent() || !@is_object( $wgOut ) ) {
967 print $s;
968 } else {
969 $wgOut->addHTML( $s );
970 }
971 }
972
973 /**
974 * Provide a simple HTTP error.
975 */
976 function wfHttpError( $code, $label, $desc ) {
977 global $wgOut;
978 $wgOut->disable();
979 header( "HTTP/1.0 $code $label" );
980 header( "Status: $code $label" );
981 $wgOut->sendCacheControl();
982
983 header( 'Content-type: text/html' );
984 print "<html><head><title>" .
985 htmlspecialchars( $label ) .
986 "</title></head><body><h1>" .
987 htmlspecialchars( $label ) .
988 "</h1><p>" .
989 htmlspecialchars( $desc ) .
990 "</p></body></html>\n";
991 }
992
993 /**
994 * Converts an Accept-* header into an array mapping string values to quality
995 * factors
996 */
997 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
998 # No arg means accept anything (per HTTP spec)
999 if( !$accept ) {
1000 return array( $def => 1 );
1001 }
1002
1003 $prefs = array();
1004
1005 $parts = explode( ',', $accept );
1006
1007 foreach( $parts as $part ) {
1008 # FIXME: doesn't deal with params like 'text/html; level=1'
1009 @list( $value, $qpart ) = explode( ';', $part );
1010 if( !isset( $qpart ) ) {
1011 $prefs[$value] = 1;
1012 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
1013 $prefs[$value] = $match[1];
1014 }
1015 }
1016
1017 return $prefs;
1018 }
1019
1020 /**
1021 * Checks if a given MIME type matches any of the keys in the given
1022 * array. Basic wildcards are accepted in the array keys.
1023 *
1024 * Returns the matching MIME type (or wildcard) if a match, otherwise
1025 * NULL if no match.
1026 *
1027 * @param string $type
1028 * @param array $avail
1029 * @return string
1030 * @access private
1031 */
1032 function mimeTypeMatch( $type, $avail ) {
1033 if( array_key_exists($type, $avail) ) {
1034 return $type;
1035 } else {
1036 $parts = explode( '/', $type );
1037 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
1038 return $parts[0] . '/*';
1039 } elseif( array_key_exists( '*/*', $avail ) ) {
1040 return '*/*';
1041 } else {
1042 return NULL;
1043 }
1044 }
1045 }
1046
1047 /**
1048 * Returns the 'best' match between a client's requested internet media types
1049 * and the server's list of available types. Each list should be an associative
1050 * array of type to preference (preference is a float between 0.0 and 1.0).
1051 * Wildcards in the types are acceptable.
1052 *
1053 * @param array $cprefs Client's acceptable type list
1054 * @param array $sprefs Server's offered types
1055 * @return string
1056 *
1057 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
1058 * XXX: generalize to negotiate other stuff
1059 */
1060 function wfNegotiateType( $cprefs, $sprefs ) {
1061 $combine = array();
1062
1063 foreach( array_keys($sprefs) as $type ) {
1064 $parts = explode( '/', $type );
1065 if( $parts[1] != '*' ) {
1066 $ckey = mimeTypeMatch( $type, $cprefs );
1067 if( $ckey ) {
1068 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1069 }
1070 }
1071 }
1072
1073 foreach( array_keys( $cprefs ) as $type ) {
1074 $parts = explode( '/', $type );
1075 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
1076 $skey = mimeTypeMatch( $type, $sprefs );
1077 if( $skey ) {
1078 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1079 }
1080 }
1081 }
1082
1083 $bestq = 0;
1084 $besttype = NULL;
1085
1086 foreach( array_keys( $combine ) as $type ) {
1087 if( $combine[$type] > $bestq ) {
1088 $besttype = $type;
1089 $bestq = $combine[$type];
1090 }
1091 }
1092
1093 return $besttype;
1094 }
1095
1096 /**
1097 * Array lookup
1098 * Returns an array where the values in the first array are replaced by the
1099 * values in the second array with the corresponding keys
1100 *
1101 * @return array
1102 */
1103 function wfArrayLookup( $a, $b ) {
1104 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
1105 }
1106
1107 /**
1108 * Convenience function; returns MediaWiki timestamp for the present time.
1109 * @return string
1110 */
1111 function wfTimestampNow() {
1112 # return NOW
1113 return wfTimestamp( TS_MW, time() );
1114 }
1115
1116 /**
1117 * Reference-counted warning suppression
1118 */
1119 function wfSuppressWarnings( $end = false ) {
1120 static $suppressCount = 0;
1121 static $originalLevel = false;
1122
1123 if ( $end ) {
1124 if ( $suppressCount ) {
1125 --$suppressCount;
1126 if ( !$suppressCount ) {
1127 error_reporting( $originalLevel );
1128 }
1129 }
1130 } else {
1131 if ( !$suppressCount ) {
1132 $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
1133 }
1134 ++$suppressCount;
1135 }
1136 }
1137
1138 /**
1139 * Restore error level to previous value
1140 */
1141 function wfRestoreWarnings() {
1142 wfSuppressWarnings( true );
1143 }
1144
1145 # Autodetect, convert and provide timestamps of various types
1146
1147 /**
1148 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1149 */
1150 define('TS_UNIX', 0);
1151
1152 /**
1153 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1154 */
1155 define('TS_MW', 1);
1156
1157 /**
1158 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1159 */
1160 define('TS_DB', 2);
1161
1162 /**
1163 * RFC 2822 format, for E-mail and HTTP headers
1164 */
1165 define('TS_RFC2822', 3);
1166
1167 /**
1168 * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
1169 *
1170 * This is used by Special:Export
1171 */
1172 define('TS_ISO_8601', 4);
1173
1174 /**
1175 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1176 *
1177 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1178 * DateTime tag and page 36 for the DateTimeOriginal and
1179 * DateTimeDigitized tags.
1180 */
1181 define('TS_EXIF', 5);
1182
1183 /**
1184 * Oracle format time.
1185 */
1186 define('TS_ORACLE', 6);
1187
1188 /**
1189 * @param mixed $outputtype A timestamp in one of the supported formats, the
1190 * function will autodetect which format is supplied
1191 and act accordingly.
1192 * @return string Time in the format specified in $outputtype
1193 */
1194 function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
1195 $uts = 0;
1196 if ($ts==0) {
1197 $uts=time();
1198 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1199 # TS_DB
1200 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1201 (int)$da[2],(int)$da[3],(int)$da[1]);
1202 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1203 # TS_EXIF
1204 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1205 (int)$da[2],(int)$da[3],(int)$da[1]);
1206 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1207 # TS_MW
1208 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1209 (int)$da[2],(int)$da[3],(int)$da[1]);
1210 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1211 # TS_UNIX
1212 $uts=$ts;
1213 } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
1214 # TS_ORACLE
1215 $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
1216 str_replace("+00:00", "UTC", $ts)));
1217 } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
1218 # TS_ISO_8601
1219 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1220 (int)$da[2],(int)$da[3],(int)$da[1]);
1221 } else {
1222 # Bogus value; fall back to the epoch...
1223 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1224 $uts = 0;
1225 }
1226
1227
1228 switch($outputtype) {
1229 case TS_UNIX:
1230 return $uts;
1231 case TS_MW:
1232 return gmdate( 'YmdHis', $uts );
1233 case TS_DB:
1234 return gmdate( 'Y-m-d H:i:s', $uts );
1235 case TS_ISO_8601:
1236 return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
1237 // This shouldn't ever be used, but is included for completeness
1238 case TS_EXIF:
1239 return gmdate( 'Y:m:d H:i:s', $uts );
1240 case TS_RFC2822:
1241 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1242 case TS_ORACLE:
1243 return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
1244 default:
1245 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1246 }
1247 }
1248
1249 /**
1250 * Return a formatted timestamp, or null if input is null.
1251 * For dealing with nullable timestamp columns in the database.
1252 * @param int $outputtype
1253 * @param string $ts
1254 * @return string
1255 */
1256 function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
1257 if( is_null( $ts ) ) {
1258 return null;
1259 } else {
1260 return wfTimestamp( $outputtype, $ts );
1261 }
1262 }
1263
1264 /**
1265 * Check if the operating system is Windows
1266 *
1267 * @return bool True if it's Windows, False otherwise.
1268 */
1269 function wfIsWindows() {
1270 if (substr(php_uname(), 0, 7) == 'Windows') {
1271 return true;
1272 } else {
1273 return false;
1274 }
1275 }
1276
1277 /**
1278 * Swap two variables
1279 */
1280 function swap( &$x, &$y ) {
1281 $z = $x;
1282 $x = $y;
1283 $y = $z;
1284 }
1285
1286 function wfGetSiteNotice() {
1287 global $wgSiteNotice, $wgTitle, $wgOut;
1288 $fname = 'wfGetSiteNotice';
1289 wfProfileIn( $fname );
1290
1291 $notice = wfMsgForContent( 'sitenotice' );
1292 if( $notice == '&lt;sitenotice&gt;' || $notice == '-' ) {
1293 $notice = '';
1294 }
1295 if( $notice == '' ) {
1296 # We may also need to override a message with eg downtime info
1297 # FIXME: make this work!
1298 $notice = $wgSiteNotice;
1299 }
1300 if($notice != '-' && $notice != '') {
1301 $specialparser = new Parser();
1302 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions, false );
1303 $notice = $parserOutput->getText();
1304 }
1305 wfProfileOut( $fname );
1306 return $notice;
1307 }
1308
1309 /**
1310 * Format an XML element with given attributes and, optionally, text content.
1311 * Element and attribute names are assumed to be ready for literal inclusion.
1312 * Strings are assumed to not contain XML-illegal characters; special
1313 * characters (<, >, &) are escaped but illegals are not touched.
1314 *
1315 * @param string $element
1316 * @param array $attribs Name=>value pairs. Values will be escaped.
1317 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1318 * @return string
1319 */
1320 function wfElement( $element, $attribs = null, $contents = '') {
1321 $out = '<' . $element;
1322 if( !is_null( $attribs ) ) {
1323 foreach( $attribs as $name => $val ) {
1324 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1325 }
1326 }
1327 if( is_null( $contents ) ) {
1328 $out .= '>';
1329 } else {
1330 if( $contents == '' ) {
1331 $out .= ' />';
1332 } else {
1333 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
1334 }
1335 }
1336 return $out;
1337 }
1338
1339 /**
1340 * Format an XML element as with wfElement(), but run text through the
1341 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1342 * is passed.
1343 *
1344 * @param string $element
1345 * @param array $attribs Name=>value pairs. Values will be escaped.
1346 * @param string $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1347 * @return string
1348 */
1349 function wfElementClean( $element, $attribs = array(), $contents = '') {
1350 if( $attribs ) {
1351 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1352 }
1353 if( $contents ) {
1354 $contents = UtfNormal::cleanUp( $contents );
1355 }
1356 return wfElement( $element, $attribs, $contents );
1357 }
1358
1359 // Shortcuts
1360 function wfOpenElement( $element, $attribs = null ) { return wfElement( $element, $attribs, null ); }
1361 function wfCloseElement( $element ) { return "</$element>"; }
1362
1363 /**
1364 * Create a namespace selector
1365 *
1366 * @param mixed $selected The namespace which should be selected, default ''
1367 * @param string $allnamespaces Value of a special item denoting all namespaces. Null to not include (default)
1368 * @return Html string containing the namespace selector
1369 */
1370 function &HTMLnamespaceselector($selected = '', $allnamespaces = null) {
1371 global $wgContLang;
1372 if( $selected !== '' ) {
1373 if( is_null( $selected ) ) {
1374 // No namespace selected; let exact match work without hitting Main
1375 $selected = '';
1376 } else {
1377 // Let input be numeric strings without breaking the empty match.
1378 $selected = intval( $selected );
1379 }
1380 }
1381 $s = "<select name='namespace' class='namespaceselector'>\n\t";
1382 $arr = $wgContLang->getFormattedNamespaces();
1383 if( !is_null($allnamespaces) ) {
1384 $arr = array($allnamespaces => wfMsgHtml('namespacesall')) + $arr;
1385 }
1386 foreach ($arr as $index => $name) {
1387 if ($index < NS_MAIN) continue;
1388
1389 $name = $index !== 0 ? $name : wfMsgHtml('blanknamespace');
1390
1391 if ($index === $selected) {
1392 $s .= wfElement("option",
1393 array("value" => $index, "selected" => "selected"),
1394 $name);
1395 } else {
1396 $s .= wfElement("option", array("value" => $index), $name);
1397 }
1398 }
1399 $s .= "\n</select>\n";
1400 return $s;
1401 }
1402
1403 /** Global singleton instance of MimeMagic. This is initialized on demand,
1404 * please always use the wfGetMimeMagic() function to get the instance.
1405 *
1406 * @private
1407 */
1408 $wgMimeMagic= NULL;
1409
1410 /** Factory functions for the global MimeMagic object.
1411 * This function always returns the same singleton instance of MimeMagic.
1412 * That objects will be instantiated on the first call to this function.
1413 * If needed, the MimeMagic.php file is automatically included by this function.
1414 * @return MimeMagic the global MimeMagic objects.
1415 */
1416 function &wfGetMimeMagic() {
1417 global $wgMimeMagic;
1418
1419 if (!is_null($wgMimeMagic)) {
1420 return $wgMimeMagic;
1421 }
1422
1423 if (!class_exists("MimeMagic")) {
1424 #include on demand
1425 require_once("MimeMagic.php");
1426 }
1427
1428 $wgMimeMagic= new MimeMagic();
1429
1430 return $wgMimeMagic;
1431 }
1432
1433
1434 /**
1435 * Tries to get the system directory for temporary files.
1436 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1437 * and if none are set /tmp is returned as the generic Unix default.
1438 *
1439 * NOTE: When possible, use the tempfile() function to create temporary
1440 * files to avoid race conditions on file creation, etc.
1441 *
1442 * @return string
1443 */
1444 function wfTempDir() {
1445 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1446 $tmp = getenv( $var );
1447 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1448 return $tmp;
1449 }
1450 }
1451 # Hope this is Unix of some kind!
1452 return '/tmp';
1453 }
1454
1455 /**
1456 * Make directory, and make all parent directories if they don't exist
1457 */
1458 function wfMkdirParents( $fullDir, $mode ) {
1459 $parts = explode( '/', $fullDir );
1460 $path = '';
1461
1462 foreach ( $parts as $dir ) {
1463 $path .= $dir . '/';
1464 if ( !is_dir( $path ) ) {
1465 if ( !mkdir( $path, $mode ) ) {
1466 return false;
1467 }
1468 }
1469 }
1470 return true;
1471 }
1472
1473 /**
1474 * Increment a statistics counter
1475 */
1476 function wfIncrStats( $key ) {
1477 global $wgDBname, $wgMemc;
1478 $key = "$wgDBname:stats:$key";
1479 if ( is_null( $wgMemc->incr( $key ) ) ) {
1480 $wgMemc->add( $key, 1 );
1481 }
1482 }
1483
1484 /**
1485 * @param mixed $nr The number to format
1486 * @param int $acc The number of digits after the decimal point, default 2
1487 * @param bool $round Whether or not to round the value, default true
1488 * @return float
1489 */
1490 function wfPercent( $nr, $acc = 2, $round = true ) {
1491 $ret = sprintf( "%.${acc}f", $nr );
1492 return $round ? round( $ret, $acc ) . '%' : "$ret%";
1493 }
1494
1495 /**
1496 * Encrypt a username/password.
1497 *
1498 * @param string $userid ID of the user
1499 * @param string $password Password of the user
1500 * @return string Hashed password
1501 */
1502 function wfEncryptPassword( $userid, $password ) {
1503 global $wgPasswordSalt;
1504 $p = md5( $password);
1505
1506 if($wgPasswordSalt)
1507 return md5( "{$userid}-{$p}" );
1508 else
1509 return $p;
1510 }
1511
1512 /**
1513 * Appends to second array if $value differs from that in $default
1514 */
1515 function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
1516 if ( is_null( $changed ) ) {
1517 wfDebugDieBacktrace('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
1518 }
1519 if ( $default[$key] !== $value ) {
1520 $changed[$key] = $value;
1521 }
1522 }
1523
1524 /**
1525 * Since wfMsg() and co suck, they don't return false if the message key they
1526 * looked up didn't exist but a XHTML string, this function checks for the
1527 * nonexistance of messages by looking at wfMsg() output
1528 *
1529 * @param $msg The message key looked up
1530 * @param $wfMsgOut The output of wfMsg*()
1531 * @return bool
1532 */
1533 function wfEmptyMsg( $msg, $wfMsgOut ) {
1534 return $wfMsgOut === "&lt;$msg&gt;";
1535 }
1536
1537 /**
1538 * Find out whether or not a mixed variable exists in a string
1539 *
1540 * @param mixed needle
1541 * @param string haystack
1542 * @return bool
1543 */
1544 function in_string( $needle, $str ) {
1545 return strpos( $str, $needle ) !== false;
1546 }
1547
1548 /**
1549 * Returns a regular expression of url protocols
1550 *
1551 * @return string
1552 */
1553 function wfUrlProtocols() {
1554 global $wgUrlProtocols;
1555
1556 $protocols = array();
1557 foreach ($wgUrlProtocols as $protocol)
1558 $protocols[] = preg_quote( $protocol, '/' );
1559
1560 return implode( '|', $protocols );
1561 }
1562
1563 /**
1564 * Check if a string is well-formed XML.
1565 * Must include the surrounding tag.
1566 *
1567 * @param string $text
1568 * @return bool
1569 *
1570 * @todo Error position reporting return
1571 */
1572 function wfIsWellFormedXml( $text ) {
1573 $parser = xml_parser_create( "UTF-8" );
1574
1575 # case folding violates XML standard, turn it off
1576 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1577
1578 if( !xml_parse( $parser, $text, true ) ) {
1579 $err = xml_error_string( xml_get_error_code( $parser ) );
1580 $position = xml_get_current_byte_index( $parser );
1581 //$fragment = $this->extractFragment( $html, $position );
1582 //$this->mXmlError = "$err at byte $position:\n$fragment";
1583 xml_parser_free( $parser );
1584 return false;
1585 }
1586 xml_parser_free( $parser );
1587 return true;
1588 }
1589
1590 /**
1591 * Check if a string is a well-formed XML fragment.
1592 * Wraps fragment in an <html> bit and doctype, so it can be a fragment
1593 * and can use HTML named entities.
1594 *
1595 * @param string $text
1596 * @return bool
1597 */
1598 function wfIsWellFormedXmlFragment( $text ) {
1599 $html =
1600 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ' .
1601 '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' .
1602 '<html>' .
1603 $text .
1604 '</html>';
1605 return wfIsWellFormedXml( $html );
1606 }
1607
1608 /**
1609 * shell_exec() with time and memory limits mirrored from the PHP configuration,
1610 * if supported.
1611 */
1612 function wfShellExec( $cmd )
1613 {
1614 global $IP;
1615
1616 if ( php_uname( 's' ) == 'Linux' ) {
1617 $time = ini_get( 'max_execution_time' );
1618 $mem = ini_get( 'memory_limit' );
1619 if( preg_match( '/^([0-9]+)[Mm]$/', trim( $mem ), $m ) ) {
1620 $mem = intval( $m[1] * (1024*1024) );
1621 }
1622 if ( $time > 0 && $mem > 0 ) {
1623 $script = "$IP/bin/ulimit.sh";
1624 if ( is_executable( $script ) ) {
1625 $memKB = intval( $mem / 1024 );
1626 $cmd = escapeshellarg( $script ) . " $time $memKB $cmd";
1627 }
1628 }
1629 }
1630 return shell_exec( $cmd );
1631 }
1632
1633 ?>