Tweak to use local random, don't trust mysql's; new seed
[lhc/web/wiklou.git] / includes / GlobalFunctions.php
1 <?
2 # Global functions used everywhere
3
4 $wgNumberOfArticles = -1; # Unset
5 $wgTotalViews = -1;
6 $wgTotalEdits = -1;
7
8 global $IP;
9 include_once( "$IP/DatabaseFunctions.php" );
10 include_once( "$IP/UpdateClasses.php" );
11 include_once( "$IP/LogPage.php" );
12
13 # PHP 4.1+ has array_key_exists, PHP 4.0.6 has key_exists instead, and earlier
14 # versions of PHP have neither. So we roll our own. Note that this
15 # function will return false even for keys that exist but whose associated
16 # value is NULL.
17 #
18 if ( phpversion() == "4.0.6" ) {
19 function array_key_exists( $k, $a ) {
20 return key_exists( $k, $a );
21 }
22 } else if (phpversion() < "4.1") {
23 function array_key_exists( $k, $a ) {
24 return isset($a[$k]);
25 }
26 }
27
28 $wgRandomSeeded = false;
29
30 function wfSeedRandom()
31 {
32 global $wgRandomSeeded;
33
34 if ( ! $wgRandomSeeded ) {
35 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
36 mt_srand( $seed );
37 $wgRandomSeeded = true;
38 }
39 }
40
41 function wfLocalUrl( $a, $q = "" )
42 {
43 global $wgServer, $wgScript, $wgArticlePath;
44
45 $a = str_replace( " ", "_", $a );
46 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
47
48 if ( "" == $a ) {
49 if( "" == $q ) {
50 $a = $wgScript;
51 } else {
52 $a = "{$wgScript}?{$q}";
53 }
54 } else if ( "" == $q ) {
55 $a = str_replace( "$1", $a, $wgArticlePath );
56 } else {
57 $a = "{$wgScript}?title={$a}&{$q}";
58 }
59 return $a;
60 }
61
62 function wfLocalUrlE( $a, $q = "" )
63 {
64 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
65 }
66
67 function wfImageUrl( $img )
68 {
69 global $wgUploadPath;
70
71 $nt = Title::newFromText( $img );
72 $name = $nt->getDBkey();
73 $hash = md5( $name );
74
75 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
76 substr( $hash, 0, 2 ) . "/{$name}";
77 return wfUrlencode( $url );
78 }
79
80 function wfImageArchiveUrl( $name )
81 {
82 global $wgUploadPath;
83
84 $hash = md5( substr( $name, 15) );
85 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
86 substr( $hash, 0, 2 ) . "/{$name}";
87 return $url;
88 }
89
90 function wfUrlencode ( $s )
91 {
92 $ulink = urlencode( $s );
93 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
94 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
95 return $ulink;
96 }
97
98 function wfUtf8Sequence($codepoint) {
99 if($codepoint < 0x80) return chr($codepoint);
100 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
101 chr($codepoint & 0x3f | 0x80);
102 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
103 chr($codepoint >> 6 & 0x3f | 0x80) .
104 chr($codepoint & 0x3f | 0x80);
105 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
106 chr($codepoint >> 12 & 0x3f | 0x80) .
107 chr($codepoint >> 6 & 0x3f | 0x80) .
108 chr($codepoint & 0x3f | 0x80);
109 # Doesn't yet handle outside the BMP
110 return "&#$codepoint;";
111 }
112
113 function wfMungeToUtf8($string) {
114 global $wgInputEncoding; # This is debatable
115 #$string = iconv($wgInputEncoding, "UTF-8", $string);
116 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
117 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
118 # Should also do named entities here
119 return $string;
120 }
121
122 function wfDebug( $text, $logonly = false )
123 {
124 global $wgOut, $wgDebugLogFile;
125
126 if ( ! $logonly ) {
127 $wgOut->debug( $text );
128 }
129 if ( "" != $wgDebugLogFile ) {
130 error_log( $text, 3, $wgDebugLogFile );
131 }
132 }
133
134 if( !isset( $wgProfiling ) )
135 $wgProfiling = false;
136 $wgProfileStack = array();
137 $wgProfileWorkStack = array();
138
139 if( $wgProfiling ) {
140 function wfProfileIn( $functionname )
141 {
142 global $wgProfileStack, $wgProfileWorkStack;
143 array_push( $wgProfileWorkStack, "$functionname " .
144 count( $wgProfileWorkStack ) . " " . microtime() );
145 }
146
147 function wfProfileOut() {
148 global $wgProfileStack, $wgProfileWorkStack;
149 $bit = array_pop( $wgProfileWorkStack );
150 $bit .= " " . microtime();
151 array_push( $wgProfileStack, $bit );
152 }
153 } else {
154 function wfProfileIn( $functionname ) { }
155 function wfProfileOut( ) { }
156 }
157
158 function wfReadOnly()
159 {
160 global $wgReadOnlyFile;
161
162 if ( "" == $wgReadOnlyFile ) { return false; }
163 return is_file( $wgReadOnlyFile );
164 }
165
166 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
167 function wfMsg( $key )
168 {
169 global $wgLang, $wgReplacementKeys;
170 $ret = $wgLang->getMessage( $key );
171
172 if( func_num_args() > 1 ) {
173 $reps = func_get_args();
174 array_shift( $reps );
175 $ret = str_replace( $wgReplacementKeys, $reps, $ret );
176 }
177
178 if ( "" == $ret ) {
179 user_error( "Couldn't find text for message \"{$key}\"." );
180 }
181 return $ret;
182 }
183
184 function wfCleanFormFields( $fields )
185 {
186 global $HTTP_POST_VARS;
187 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
188
189 if ( get_magic_quotes_gpc() ) {
190 foreach ( $fields as $fname ) {
191 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
192 $HTTP_POST_VARS[$fname] = stripslashes(
193 $HTTP_POST_VARS[$fname] );
194 }
195 global ${$fname};
196 if ( isset( ${$fname} ) ) {
197 ${$fname} = stripslashes( ${$fname} );
198 }
199 }
200 }
201 $enc = $wgOutputEncoding;
202 if( $wgEditEncoding != "") $enc = $wgEditEncoding;
203 if ( $enc != $wgInputEncoding ) {
204 foreach ( $fields as $fname ) {
205 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
206 $HTTP_POST_VARS[$fname] = $wgLang->iconv(
207 $wgOutputEncoding, $wgInputEncoding,
208 $HTTP_POST_VARS[$fname] );
209 }
210 global ${$fname};
211 if ( isset( ${$fname} ) ) {
212 ${$fname} = $wgLang->iconv(
213 $enc, $wgInputEncoding, ${$fname} );
214 }
215 }
216 }
217 }
218
219 function wfMungeQuotes( $in )
220 {
221 $out = str_replace( "%", "%25", $in );
222 $out = str_replace( "'", "%27", $out );
223 $out = str_replace( "\"", "%22", $out );
224 return $out;
225 }
226
227 function wfDemungeQuotes( $in )
228 {
229 $out = str_replace( "%22", "\"", $in );
230 $out = str_replace( "%27", "'", $out );
231 $out = str_replace( "%25", "%", $out );
232 return $out;
233 }
234
235 function wfCleanQueryVar( $var )
236 {
237 global $wgLang;
238 if ( get_magic_quotes_gpc() ) {
239 $var = stripslashes( $var );
240 }
241 return $wgLang->recodeInput( $var );
242 }
243
244 function wfSpecialPage()
245 {
246 global $wgUser, $wgOut, $wgTitle, $wgLang;
247
248 $validSP = $wgLang->getValidSpecialPages();
249 $sysopSP = $wgLang->getSysopSpecialPages();
250 $devSP = $wgLang->getDeveloperSpecialPages();
251
252 $wgOut->setArticleFlag( false );
253 $wgOut->setRobotpolicy( "noindex,follow" );
254
255 $t = $wgTitle->getDBkey();
256 if ( array_key_exists( $t, $validSP ) ||
257 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
258 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
259 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
260
261 $inc = "Special" . $t . ".php";
262 include_once( $inc );
263 $call = "wfSpecial" . $t;
264 $call();
265 } else if ( array_key_exists( $t, $sysopSP ) ) {
266 $wgOut->sysopRequired();
267 } else if ( array_key_exists( $t, $devSP ) ) {
268 $wgOut->developerRequired();
269 } else {
270 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
271 }
272 }
273
274 function wfSearch( $s )
275 {
276 $se = new SearchEngine( wfCleanQueryVar( $s ) );
277 $se->showResults();
278 }
279
280 function wfGo( $s )
281 { # pick the nearest match
282 $se = new SearchEngine( wfCleanQueryVar( $s ) );
283 $se->goResult();
284 }
285
286 function wfNumberOfArticles()
287 {
288 global $wgNumberOfArticles;
289
290 wfLoadSiteStats();
291 return $wgNumberOfArticles;
292 }
293
294 /* private */ function wfLoadSiteStats()
295 {
296 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
297 if ( -1 != $wgNumberOfArticles ) return;
298
299 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
300 "FROM site_stats WHERE ss_row_id=1";
301 $res = wfQuery( $sql, "wfLoadSiteStats" );
302
303 if ( 0 == wfNumRows( $res ) ) { return; }
304 else {
305 $s = wfFetchObject( $res );
306 $wgTotalViews = $s->ss_total_views;
307 $wgTotalEdits = $s->ss_total_edits;
308 $wgNumberOfArticles = $s->ss_good_articles;
309 }
310 }
311
312 function wfEscapeHTML( $in )
313 {
314 return str_replace(
315 array( "&", "\"", ">", "<" ),
316 array( "&amp;", "&quot;", "&gt;", "&lt;" ),
317 $in );
318 }
319
320 function wfEscapeHTMLTagsOnly( $in ) {
321 return str_replace(
322 array( "\"", ">", "<" ),
323 array( "&quot;", "&gt;", "&lt;" ),
324 $in );
325 }
326
327 function wfUnescapeHTML( $in )
328 {
329 $in = str_replace( "&lt;", "<", $in );
330 $in = str_replace( "&gt;", ">", $in );
331 $in = str_replace( "&quot;", "\"", $in );
332 $in = str_replace( "&amp;", "&", $in );
333 return $in;
334 }
335
336 function wfImageDir( $fname )
337 {
338 global $wgUploadDirectory;
339
340 $hash = md5( $fname );
341 $oldumask = umask(0);
342 $dest = $wgUploadDirectory . "/" . $hash{0};
343 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
344 $dest .= "/" . substr( $hash, 0, 2 );
345 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
346
347 umask( $oldumask );
348 return $dest;
349 }
350
351 function wfImageArchiveDir( $fname )
352 {
353 global $wgUploadDirectory;
354
355 $hash = md5( $fname );
356 $oldumask = umask(0);
357 $archive = "{$wgUploadDirectory}/archive";
358 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
359 $archive .= "/" . $hash{0};
360 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
361 $archive .= "/" . substr( $hash, 0, 2 );
362 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
363
364 umask( $oldumask );
365 return $archive;
366 }
367
368 function wfRecordUpload( $name, $oldver, $size, $desc )
369 {
370 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
371 $fname = "wfRecordUpload";
372
373 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
374 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
375 $res = wfQuery( $sql, $fname );
376
377 if ( 0 == wfNumRows( $res ) ) {
378 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
379 "img_description,img_user,img_user_text) VALUES ('" .
380 wfStrencode( $name ) . "',{$size},'" . date( "YmdHis" ) . "','" .
381 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
382 "', '" . wfStrencode( $wgUser->getName() ) . "')";
383 wfQuery( $sql, $fname );
384
385 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
386 Namespace::getImage() . " AND cur_title='" .
387 wfStrencode( $name ) . "'";
388 $res = wfQuery( $sql, $fname );
389 if ( 0 == wfNumRows( $res ) ) {
390 $now = wfTimestampNow();
391 $won = wfInvertTimestamp( $now );
392 $common =
393 Namespace::getImage() . ",'" .
394 wfStrencode( $name ) . "','" .
395 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
396 wfStrencode( $wgUser->getName() ) . "','" . $now .
397 "',1";
398 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
399 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
400 "cur_text,inverse_timestamp) VALUES (" .
401 $common .
402 ",'" . wfStrencode( $desc ) . "','{$won}')";
403 wfQuery( $sql, $fname );
404 $id = wfInsertId() or 0; # We should throw an error instead
405 $sql = "INSERT INTO recentchanges (rc_namespace,rc_title,
406 rc_comment,rc_user,rc_user_text,rc_timestamp,rc_new,
407 rc_cur_id,rc_cur_time) VALUES ({$common},{$id},'{$now}')";
408 wfQuery( $sql, $fname );
409 $u = new SearchUpdate( $id, $name, $desc );
410 $u->doUpdate();
411 }
412 } else {
413 $s = wfFetchObject( $res );
414
415 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
416 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
417 wfStrencode( $s->img_name ) . "','" .
418 wfStrencode( $oldver ) .
419 "',{$s->img_size},'{$s->img_timestamp}','" .
420 wfStrencode( $s->img_description ) . "','" .
421 wfStrencode( $s->img_user ) . "','" .
422 wfStrencode( $s->img_user_text) . "')";
423 wfQuery( $sql, $fname );
424
425 $sql = "UPDATE image SET img_size={$size}," .
426 "img_timestamp='" . date( "YmdHis" ) . "',img_user='" .
427 $wgUser->getID() . "',img_user_text='" .
428 wfStrencode( $wgUser->getName() ) . "', img_description='" .
429 wfStrencode( $desc ) . "' WHERE img_name='" .
430 wfStrencode( $name ) . "'";
431 wfQuery( $sql, $fname );
432 }
433
434 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
435 $da = str_replace( "$1", "[[:" . $wgLang->getNsText(
436 Namespace::getImage() ) . ":{$name}|{$name}]]",
437 wfMsg( "uploadedimage" ) );
438 $ta = str_replace( "$1", $name, wfMsg( "uploadedimage" ) );
439 $log->addEntry( $da, $desc, $ta );
440 }
441
442
443 /* Some generic result counters, pulled out of SearchEngine */
444
445 function wfShowingResults( $offset, $limit )
446 {
447 $top = str_replace( "$1", $limit, wfMsg( "showingresults" ) );
448 $top = str_replace( "$2", $offset+1, $top );
449 return $top;
450 }
451
452 function wfShowingResultsNum( $offset, $limit, $num )
453 {
454 $top = str_replace( "$1", $limit, wfMsg( "showingresultsnum" ) );
455 $top = str_replace( "$2", $offset+1, $top );
456 $top = str_replace( "$3", $num, $top );
457 return $top;
458 }
459
460 function wfViewPrevNext( $offset, $limit, $link, $query = "" )
461 {
462 global $wgUser;
463 $prev = str_replace( "$1", $limit, wfMsg( "prevn" ) );
464 $next = str_replace( "$1", $limit, wfMsg( "nextn" ) );
465
466 $sk = $wgUser->getSkin();
467 if ( 0 != $offset ) {
468 $po = $offset - $limit;
469 if ( $po < 0 ) { $po = 0; }
470 $q = "limit={$limit}&offset={$po}";
471 if ( "" != $query ) { $q .= "&{$query}"; }
472 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
473 } else { $plink = $prev; }
474
475 $no = $offset + $limit;
476 $q = "limit={$limit}&offset={$no}";
477 if ( "" != $query ) { $q .= "&{$query}"; }
478
479 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
480 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
481 wfNumLink( $offset, 50, $link, $query ) . " | " .
482 wfNumLink( $offset, 100, $link, $query ) . " | " .
483 wfNumLink( $offset, 250, $link, $query ) . " | " .
484 wfNumLink( $offset, 500, $link, $query );
485
486 $sl = str_replace( "$1", $plink, wfMsg( "viewprevnext" ) );
487 $sl = str_replace( "$2", $nlink, $sl );
488 $sl = str_replace( "$3", $nums, $sl );
489 return $sl;
490 }
491
492 function wfNumLink( $offset, $limit, $link, $query = "" )
493 {
494 global $wgUser;
495 if ( "" == $query ) { $q = ""; }
496 else { $q = "{$query}&"; }
497 $q .= "limit={$limit}&offset={$offset}";
498
499 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
500 return $s;
501 }
502
503 function wfClientAcceptsGzip() {
504 global $wgUseGzip;
505 if( $wgUseGzip ) {
506 # FIXME: we may want to blacklist some broken browsers
507 if( preg_match(
508 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
509 $_SERVER["HTTP_ACCEPT_ENCODING"],
510 $m ) ) {
511 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
512 wfDebug( " accepts gzip\n" );
513 return true;
514 }
515 }
516 return false;
517 }
518
519 # Yay, more global functions!
520 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
521 global $wgUser;
522
523 $limit = (int)$_REQUEST['limit'];
524 if( $limit < 0 ) $limit = 0;
525 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
526 $limit = (int)$wgUser->getOption( $optionname );
527 }
528 if( $limit <= 0 ) $limit = $deflimit;
529 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
530
531 $offset = (int)$_REQUEST['offset'];
532 $offset = (int)$offset;
533 if( $offset < 0 ) $offset = 0;
534 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
535
536 return array( $limit, $offset );
537 }
538
539 ?>