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