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