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