2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
8 include_once( "DatabaseFunctions.php" );
9 include_once( "UpdateClasses.php" );
10 include_once( "LogPage.php" );
13 * Compatibility functions
16 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
17 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
18 # such as the new autoglobals.
20 if( !function_exists('iconv') ) {
21 # iconv support is not in the default configuration and so may not be present.
22 # Assume will only ever use utf-8 and iso-8859-1.
23 # This will *not* work in all circumstances.
24 function iconv( $from, $to, $string ) {
25 if(strcasecmp( $from, $to ) == 0) return $string;
26 if(strcasecmp( $from, "utf-8" ) == 0) return utf8_decode( $string );
27 if(strcasecmp( $to, "utf-8" ) == 0) return utf8_encode( $string );
32 if( !function_exists('file_get_contents') ) {
33 # Exists in PHP 4.3.0+
34 function file_get_contents( $filename ) {
35 return implode( "", file( $filename ) );
39 $wgRandomSeeded = false;
41 function wfSeedRandom()
43 global $wgRandomSeeded;
45 if ( ! $wgRandomSeeded ) {
46 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
48 $wgRandomSeeded = true;
52 function wfLocalUrl( $a, $q = "" )
54 global $wgServer, $wgScript, $wgArticlePath;
56 $a = str_replace( " ", "_", $a );
57 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
63 $a = "{$wgScript}?{$q}";
65 } else if ( "" == $q ) {
66 $a = str_replace( "$1", $a, $wgArticlePath );
68 $a = "{$wgScript}?title={$a}&{$q}";
73 function wfLocalUrlE( $a, $q = "" )
75 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
78 function wfFullUrl( $a, $q = "" ) {
80 return $wgServer . wfLocalUrl( $a, $q );
83 function wfFullUrlE( $a, $q = "" ) {
84 return wfEscapeHTML( wfFullUrl( $a, $q ) );
87 function wfImageUrl( $img )
91 $nt = Title
::newFromText( $img );
94 $name = $nt->getDBkey();
97 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
98 substr( $hash, 0, 2 ) . "/{$name}";
99 return wfUrlencode( $url );
102 function wfImageArchiveUrl( $name )
104 global $wgUploadPath;
106 $hash = md5( substr( $name, 15) );
107 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
108 substr( $hash, 0, 2 ) . "/{$name}";
112 function wfUrlencode ( $s )
114 $ulink = urlencode( $s );
115 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
116 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
120 function wfUtf8Sequence($codepoint) {
121 if($codepoint < 0x80) return chr($codepoint);
122 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
123 chr($codepoint & 0x3f |
0x80);
124 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
125 chr($codepoint >> 6 & 0x3f |
0x80) .
126 chr($codepoint & 0x3f |
0x80);
127 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
128 chr($codepoint >> 12 & 0x3f |
0x80) .
129 chr($codepoint >> 6 & 0x3f |
0x80) .
130 chr($codepoint & 0x3f |
0x80);
131 # Doesn't yet handle outside the BMP
132 return "&#$codepoint;";
135 function wfMungeToUtf8($string) {
136 global $wgInputEncoding; # This is debatable
137 #$string = iconv($wgInputEncoding, "UTF-8", $string);
138 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
139 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
140 # Should also do named entities here
144 function wfDebug( $text, $logonly = false )
146 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
148 if ( $wgDebugComments && !$logonly ) {
149 $wgOut->debug( $text );
151 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
152 error_log( $text, 3, $wgDebugLogFile );
156 function logProfilingData()
158 global $wgRequestTime, $wgDebugLogFile;
159 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
160 list( $usec, $sec ) = explode( " ", microtime() );
161 $now = (float)$sec +
(float)$usec;
163 list( $usec, $sec ) = explode( " ", $wgRequestTime );
164 $start = (float)$sec +
(float)$usec;
165 $elapsed = $now - $start;
166 if ( "" != $wgDebugLogFile ) {
167 $prof = wfGetProfilingOutput( $start, $elapsed );
168 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
169 $forward = " forwarded for " . $_SERVER['HTTP_X_FORWARDED_FOR'];
170 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
171 $forward .= " client IP " . $_SERVER['HTTP_CLIENT_IP'];
172 if( !empty( $_SERVER['HTTP_FROM'] ) )
173 $forward .= " from " . $_SERVER['HTTP_FROM'];
175 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
176 if($wgUser->getId() == 0)
178 $log = sprintf( "%s\t%04.3f\t%s\n",
179 gmdate( "YmdHis" ), $elapsed,
180 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
181 error_log( $log . $prof, 3, $wgDebugLogFile );
186 function wfReadOnly()
188 global $wgReadOnlyFile;
190 if ( "" == $wgReadOnlyFile ) { return false; }
191 return is_file( $wgReadOnlyFile );
194 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
196 # Get a message from anywhere
197 function wfMsg( $key ) {
198 $args = func_get_args();
199 if ( count( $args ) ) {
200 array_shift( $args );
202 return wfMsgReal( $key, $args, true );
205 # Get a message from the language file
206 function wfMsgNoDB( $key ) {
207 $args = func_get_args();
208 if ( count( $args ) ) {
209 array_shift( $args );
211 return wfMsgReal( $key, $args, false );
214 # Really get a message
215 function wfMsgReal( $key, $args, $useDB ) {
216 global $wgReplacementKeys, $wgMessageCache, $wgLang;
219 wfProfileIn( $fname );
220 if ( $wgMessageCache ) {
221 $message = $wgMessageCache->get( $key, $useDB );
222 } elseif ( $wgLang ) {
223 $message = $wgLang->getMessage( $key );
225 wfDebug( "No language object when getting $key\n" );
226 $message = "<$key>";
230 if( count( $args ) ) {
231 $message = str_replace( $wgReplacementKeys, $args, $message );
233 wfProfileOut( $fname );
237 function wfCleanFormFields( $fields )
239 global $HTTP_POST_VARS;
240 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
242 if ( get_magic_quotes_gpc() ) {
243 foreach ( $fields as $fname ) {
244 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
245 $HTTP_POST_VARS[$fname] = stripslashes(
246 $HTTP_POST_VARS[$fname] );
249 if ( isset( $
{$fname} ) ) {
250 $
{$fname} = stripslashes( $
{$fname} );
254 $enc = $wgOutputEncoding;
255 if( $wgEditEncoding != "") $enc = $wgEditEncoding;
256 if ( $enc != $wgInputEncoding ) {
257 foreach ( $fields as $fname ) {
258 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
259 $HTTP_POST_VARS[$fname] = $wgLang->iconv(
260 $wgOutputEncoding, $wgInputEncoding,
261 $HTTP_POST_VARS[$fname] );
264 if ( isset( $
{$fname} ) ) {
265 $
{$fname} = $wgLang->iconv(
266 $enc, $wgInputEncoding, $
{$fname} );
272 function wfMungeQuotes( $in )
274 $out = str_replace( "%", "%25", $in );
275 $out = str_replace( "'", "%27", $out );
276 $out = str_replace( "\"", "%22", $out );
280 function wfDemungeQuotes( $in )
282 $out = str_replace( "%22", "\"", $in );
283 $out = str_replace( "%27", "'", $out );
284 $out = str_replace( "%25", "%", $out );
288 function wfCleanQueryVar( $var )
291 if ( get_magic_quotes_gpc() ) {
292 $var = stripslashes( $var );
294 return $wgLang->recodeInput( $var );
297 function wfSpecialPage()
299 global $wgUser, $wgOut, $wgTitle, $wgLang;
301 /* FIXME: this list probably shouldn't be language-specific, per se */
302 $validSP = $wgLang->getValidSpecialPages();
303 $sysopSP = $wgLang->getSysopSpecialPages();
304 $devSP = $wgLang->getDeveloperSpecialPages();
306 $wgOut->setArticleFlag( false );
307 $wgOut->setRobotpolicy( "noindex,follow" );
310 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
312 if ( array_key_exists( $t, $validSP ) ||
313 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
314 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
316 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
318 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
320 $inc = "Special" . $t . ".php";
321 include_once( $inc );
322 $call = "wfSpecial" . $t;
324 } else if ( array_key_exists( $t, $sysopSP ) ) {
325 $wgOut->sysopRequired();
326 } else if ( array_key_exists( $t, $devSP ) ) {
327 $wgOut->developerRequired();
329 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
333 function wfSearch( $s )
335 $se = new SearchEngine( wfCleanQueryVar( $s ) );
340 { # pick the nearest match
341 $se = new SearchEngine( wfCleanQueryVar( $s ) );
345 /* private */ $wgAbruptExitCalled = false;
347 # Just like exit() but makes a note of it.
348 function wfAbruptExit(){
349 // Safety to avoid infinite recursion in case of (unlikely) bugs somewhere
350 global $wgAbruptExitCalled;
351 if ( $wgAbruptExitCalled ){
354 $wgAbruptExitCalled = true;
356 $bt = debug_backtrace();
357 for($i = 0; $i < count($bt) ; $i++
){
358 $file = $bt[$i]["file"];
359 $line = $bt[$i]["line"];
360 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
365 function wfNumberOfArticles()
367 global $wgNumberOfArticles;
370 return $wgNumberOfArticles;
373 /* private */ function wfLoadSiteStats()
375 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
376 if ( -1 != $wgNumberOfArticles ) return;
378 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
379 "FROM site_stats WHERE ss_row_id=1";
380 $res = wfQuery( $sql, DB_READ
, "wfLoadSiteStats" );
382 if ( 0 == wfNumRows( $res ) ) { return; }
384 $s = wfFetchObject( $res );
385 $wgTotalViews = $s->ss_total_views
;
386 $wgTotalEdits = $s->ss_total_edits
;
387 $wgNumberOfArticles = $s->ss_good_articles
;
391 function wfEscapeHTML( $in )
394 array( "&", "\"", ">", "<" ),
395 array( "&", """, ">", "<" ),
399 function wfEscapeHTMLTagsOnly( $in ) {
401 array( "\"", ">", "<" ),
402 array( """, ">", "<" ),
406 function wfUnescapeHTML( $in )
408 $in = str_replace( "<", "<", $in );
409 $in = str_replace( ">", ">", $in );
410 $in = str_replace( """, "\"", $in );
411 $in = str_replace( "&", "&", $in );
415 function wfImageDir( $fname )
417 global $wgUploadDirectory;
419 $hash = md5( $fname );
420 $oldumask = umask(0);
421 $dest = $wgUploadDirectory . "/" . $hash{0};
422 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
423 $dest .= "/" . substr( $hash, 0, 2 );
424 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
430 function wfImageArchiveDir( $fname )
432 global $wgUploadDirectory;
434 $hash = md5( $fname );
435 $oldumask = umask(0);
436 $archive = "{$wgUploadDirectory}/archive";
437 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
438 $archive .= "/" . $hash{0};
439 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
440 $archive .= "/" . substr( $hash, 0, 2 );
441 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
447 function wfRecordUpload( $name, $oldver, $size, $desc )
449 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
450 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
452 $fname = "wfRecordUpload";
454 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
455 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
456 $res = wfQuery( $sql, DB_READ
, $fname );
458 $now = wfTimestampNow();
459 $won = wfInvertTimestamp( $now );
460 $size = IntVal( $size );
462 if ( $wgUseCopyrightUpload )
464 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
465 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
466 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
468 else $textdesc = $desc ;
470 $now = wfTimestampNow();
471 $won = wfInvertTimestamp( $now );
473 if ( 0 == wfNumRows( $res ) ) {
474 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
475 "img_description,img_user,img_user_text) VALUES ('" .
476 wfStrencode( $name ) . "',$size,'{$now}','" .
477 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
478 "', '" . wfStrencode( $wgUser->getName() ) . "')";
479 wfQuery( $sql, DB_WRITE
, $fname );
481 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
482 Namespace::getImage() . " AND cur_title='" .
483 wfStrencode( $name ) . "'";
484 $res = wfQuery( $sql, DB_READ
, $fname );
485 if ( 0 == wfNumRows( $res ) ) {
487 Namespace::getImage() . ",'" .
488 wfStrencode( $name ) . "','" .
489 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
490 wfStrencode( $wgUser->getName() ) . "','" . $now .
492 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
493 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
494 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
496 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
497 wfQuery( $sql, DB_WRITE
, $fname );
498 $id = wfInsertId() or 0; # We should throw an error instead
499 $sql = "INSERT INTO recentchanges (rc_namespace,rc_title,
500 rc_comment,rc_user,rc_user_text,rc_timestamp,rc_new,
501 rc_cur_id,rc_cur_time) VALUES ({$common},{$id},'{$now}')";
502 wfQuery( $sql, DB_WRITE
, $fname );
503 $u = new SearchUpdate( $id, $name, $desc );
507 $s = wfFetchObject( $res );
509 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
510 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
511 wfStrencode( $s->img_name
) . "','" .
512 wfStrencode( $oldver ) .
513 "',{$s->img_size},'{$s->img_timestamp}','" .
514 wfStrencode( $s->img_description
) . "','" .
515 wfStrencode( $s->img_user
) . "','" .
516 wfStrencode( $s->img_user_text
) . "')";
517 wfQuery( $sql, DB_WRITE
, $fname );
519 $sql = "UPDATE image SET img_size={$size}," .
520 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
521 $wgUser->getID() . "',img_user_text='" .
522 wfStrencode( $wgUser->getName() ) . "', img_description='" .
523 wfStrencode( $desc ) . "' WHERE img_name='" .
524 wfStrencode( $name ) . "'";
525 wfQuery( $sql, DB_WRITE
, $fname );
527 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
528 Namespace::getImage() . " AND cur_title='" .
529 wfStrencode( $name ) . "'";
530 wfQuery( $sql, DB_WRITE
, $fname );
533 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
534 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
535 Namespace::getImage() ) . ":{$name}|{$name}]]" );
536 $ta = wfMsg( "uploadedimage", $name );
537 $log->addEntry( $da, $desc, $ta );
541 /* Some generic result counters, pulled out of SearchEngine */
543 function wfShowingResults( $offset, $limit )
545 return wfMsg( "showingresults", $limit, $offset+
1 );
548 function wfShowingResultsNum( $offset, $limit, $num )
550 return wfMsg( "showingresultsnum", $limit, $offset+
1, $num );
553 function wfViewPrevNext( $offset, $limit, $link, $query = "" )
556 $prev = wfMsg( "prevn", $limit );
557 $next = wfMsg( "nextn", $limit );
559 $sk = $wgUser->getSkin();
560 if ( 0 != $offset ) {
561 $po = $offset - $limit;
562 if ( $po < 0 ) { $po = 0; }
563 $q = "limit={$limit}&offset={$po}";
564 if ( "" != $query ) { $q .= "&{$query}"; }
565 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
566 } else { $plink = $prev; }
568 $no = $offset +
$limit;
569 $q = "limit={$limit}&offset={$no}";
570 if ( "" != $query ) { $q .= "&{$query}"; }
572 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
573 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
574 wfNumLink( $offset, 50, $link, $query ) . " | " .
575 wfNumLink( $offset, 100, $link, $query ) . " | " .
576 wfNumLink( $offset, 250, $link, $query ) . " | " .
577 wfNumLink( $offset, 500, $link, $query );
579 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
582 function wfNumLink( $offset, $limit, $link, $query = "" )
585 if ( "" == $query ) { $q = ""; }
586 else { $q = "{$query}&"; }
587 $q .= "limit={$limit}&offset={$offset}";
589 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
593 function wfClientAcceptsGzip() {
596 # FIXME: we may want to blacklist some broken browsers
598 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
599 $_SERVER["HTTP_ACCEPT_ENCODING"],
601 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
602 wfDebug( " accepts gzip\n" );
609 # Yay, more global functions!
610 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
613 $limit = (int)$_REQUEST['limit'];
614 if( $limit < 0 ) $limit = 0;
615 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
616 $limit = (int)$wgUser->getOption( $optionname );
618 if( $limit <= 0 ) $limit = $deflimit;
619 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
621 $offset = (int)$_REQUEST['offset'];
622 $offset = (int)$offset;
623 if( $offset < 0 ) $offset = 0;
624 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
626 return array( $limit, $offset );
629 # Escapes the given text so that it may be output using addWikiText()
630 # without any linking, formatting, etc. making its way through. This
631 # is achieved by substituting certain characters with HTML entities.
632 # As required by the callers, <nowiki> is not used. It currently does
633 # not filter out characters which have special meaning only at the
634 # start of a line, such as "*".
635 function wfEscapeWikiText( $text )
638 array( '[', "'", 'ISBN ' , '://' , "\n=" ),
639 array( '[', ''', 'ISBN ', '://' , "\n=" ),
640 htmlspecialchars($text) );
644 function wfQuotedPrintable( $string, $charset = "" )
646 # Probably incomplete; see RFC 2045
647 if( empty( $charset ) ) {
648 global $wgInputEncoding;
649 $charset = $wgInputEncoding;
651 $charset = strtoupper( $charset );
652 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
654 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
655 $replace = $illegal . '\t ?_';
656 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
657 $out = "=?$charset?Q?";
658 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );