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