block/unblock log; split off profiling into Profiling.php and broke it (turn it off...
[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, $wgDebugComments;
134
135 if ( $wgDebugComments && !$logonly ) {
136 $wgOut->debug( $text );
137 }
138 if ( "" != $wgDebugLogFile ) {
139 error_log( $text, 3, $wgDebugLogFile );
140 }
141 }
142
143 function wfReadOnly()
144 {
145 global $wgReadOnlyFile;
146
147 if ( "" == $wgReadOnlyFile ) { return false; }
148 return is_file( $wgReadOnlyFile );
149 }
150
151 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
152
153 function wfMsg( $key ) {
154 $args = func_get_args();
155 if ( count( $args ) ) {
156 array_shift( $args );
157 }
158 return wfMsgReal( $key, $args, true );
159 }
160
161 function wfMsgNoDB( $key ) {
162 $args = func_get_args();
163 if ( count( $args ) ) {
164 array_shift( $args );
165 }
166 return wfMsgReal( $key, $args, false );
167 }
168
169 function wfMsgReal( $key, $args, $useDB ) {
170 global $wgLang, $wgReplacementKeys, $wgMemc, $wgDBname;
171 global $wgUseDatabaseMessages;
172
173 static $l1cache = array();
174 $fname = "wfMsg";
175 $message = false;
176 $l1hit = false;
177
178 # Check for DB suppression
179 if ( !$wgUseDatabaseMessages || !$useDB ) {
180 $message = $wgLang->getMessage( $key );
181 }
182
183 # Try L1 cache
184 if ( $message === false && array_key_exists( $key, $l1cache ) ) {
185 $message = $l1cache[$key];
186 if ( $message === false ) {
187 $message = $wgLang->getMessage( $key );
188 }
189 $l1hit = true;
190 }
191
192 # Try memcached
193 if ( $message === false ) {
194 $titleObj = Title::newFromText( $key );
195 $title = $titleObj->getDBkey();
196 $mcKey = "$wgDBname:MediaWiki:title:$title";
197 $message = $wgMemc->get( $mcKey );
198 }
199
200 # Try database
201 if ( $message === false) {
202 if ( $useDB ) {
203 $sql = "SELECT cur_text FROM cur WHERE cur_namespace=" . NS_MEDIAWIKI .
204 " AND cur_title='$title'";
205 $res = wfQuery( $sql, DB_READ, $fname );
206
207 if ( wfNumRows( $res ) ) {
208 # Got it from the database, now store in MemCached
209 $obj = wfFetchObject( $res );
210 $message = $obj->cur_text;
211 wfFreeResult( $res );
212 $wgMemc->set( $key, $message, time() + 1800 );
213 }
214 }
215 }
216
217 # Finally, try the array in $wgLang
218 if ( $message === false ) {
219 $message = $wgLang->getMessage( $key );
220 $l1cache[$key] = false;
221 } elseif ( !$l1hit && $wgUseDatabaseMessages) {
222 $l1cache[$key] = $message;
223 }
224
225 # Replace arguments
226 if( count( $args ) ) {
227 $message = str_replace( $wgReplacementKeys, $args, $message );
228 }
229
230 if ( "" == $message ) {
231 # Let's at least _try_ to be graceful about this.
232 return "&lt;$key&gt;";
233 }
234 return $message;
235 }
236
237 function wfCleanFormFields( $fields )
238 {
239 global $HTTP_POST_VARS;
240 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
241
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] );
247 }
248 global ${$fname};
249 if ( isset( ${$fname} ) ) {
250 ${$fname} = stripslashes( ${$fname} );
251 }
252 }
253 }
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] );
262 }
263 global ${$fname};
264 if ( isset( ${$fname} ) ) {
265 ${$fname} = $wgLang->iconv(
266 $enc, $wgInputEncoding, ${$fname} );
267 }
268 }
269 }
270 }
271
272 function wfMungeQuotes( $in )
273 {
274 $out = str_replace( "%", "%25", $in );
275 $out = str_replace( "'", "%27", $out );
276 $out = str_replace( "\"", "%22", $out );
277 return $out;
278 }
279
280 function wfDemungeQuotes( $in )
281 {
282 $out = str_replace( "%22", "\"", $in );
283 $out = str_replace( "%27", "'", $out );
284 $out = str_replace( "%25", "%", $out );
285 return $out;
286 }
287
288 function wfCleanQueryVar( $var )
289 {
290 global $wgLang;
291 if ( get_magic_quotes_gpc() ) {
292 $var = stripslashes( $var );
293 }
294 return $wgLang->recodeInput( $var );
295 }
296
297 function wfSpecialPage()
298 {
299 global $wgUser, $wgOut, $wgTitle, $wgLang;
300
301 /* FIXME: this list probably shouldn't be language-specific, per se */
302 $validSP = $wgLang->getValidSpecialPages();
303 $sysopSP = $wgLang->getSysopSpecialPages();
304 $devSP = $wgLang->getDeveloperSpecialPages();
305
306 $wgOut->setArticleFlag( false );
307 $wgOut->setRobotpolicy( "noindex,follow" );
308
309 $par = NULL;
310 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
311
312 if ( array_key_exists( $t, $validSP ) ||
313 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
314 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
315 if($par !== NULL)
316 $wgTitle = Title::makeTitle( Namespace::getSpecial(), $t );
317
318 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
319
320 $inc = "Special" . $t . ".php";
321 include_once( $inc );
322 $call = "wfSpecial" . $t;
323 $call( $par );
324 } else if ( array_key_exists( $t, $sysopSP ) ) {
325 $wgOut->sysopRequired();
326 } else if ( array_key_exists( $t, $devSP ) ) {
327 $wgOut->developerRequired();
328 } else {
329 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
330 }
331 }
332
333 function wfSearch( $s )
334 {
335 $se = new SearchEngine( wfCleanQueryVar( $s ) );
336 $se->showResults();
337 }
338
339 function wfGo( $s )
340 { # pick the nearest match
341 $se = new SearchEngine( wfCleanQueryVar( $s ) );
342 $se->goResult();
343 }
344
345 function wfNumberOfArticles()
346 {
347 global $wgNumberOfArticles;
348
349 wfLoadSiteStats();
350 return $wgNumberOfArticles;
351 }
352
353 /* private */ function wfLoadSiteStats()
354 {
355 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
356 if ( -1 != $wgNumberOfArticles ) return;
357
358 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
359 "FROM site_stats WHERE ss_row_id=1";
360 $res = wfQuery( $sql, DB_READ, "wfLoadSiteStats" );
361
362 if ( 0 == wfNumRows( $res ) ) { return; }
363 else {
364 $s = wfFetchObject( $res );
365 $wgTotalViews = $s->ss_total_views;
366 $wgTotalEdits = $s->ss_total_edits;
367 $wgNumberOfArticles = $s->ss_good_articles;
368 }
369 }
370
371 function wfEscapeHTML( $in )
372 {
373 return str_replace(
374 array( "&", "\"", ">", "<" ),
375 array( "&amp;", "&quot;", "&gt;", "&lt;" ),
376 $in );
377 }
378
379 function wfEscapeHTMLTagsOnly( $in ) {
380 return str_replace(
381 array( "\"", ">", "<" ),
382 array( "&quot;", "&gt;", "&lt;" ),
383 $in );
384 }
385
386 function wfUnescapeHTML( $in )
387 {
388 $in = str_replace( "&lt;", "<", $in );
389 $in = str_replace( "&gt;", ">", $in );
390 $in = str_replace( "&quot;", "\"", $in );
391 $in = str_replace( "&amp;", "&", $in );
392 return $in;
393 }
394
395 function wfImageDir( $fname )
396 {
397 global $wgUploadDirectory;
398
399 $hash = md5( $fname );
400 $oldumask = umask(0);
401 $dest = $wgUploadDirectory . "/" . $hash{0};
402 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
403 $dest .= "/" . substr( $hash, 0, 2 );
404 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
405
406 umask( $oldumask );
407 return $dest;
408 }
409
410 function wfImageArchiveDir( $fname )
411 {
412 global $wgUploadDirectory;
413
414 $hash = md5( $fname );
415 $oldumask = umask(0);
416 $archive = "{$wgUploadDirectory}/archive";
417 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
418 $archive .= "/" . $hash{0};
419 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
420 $archive .= "/" . substr( $hash, 0, 2 );
421 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
422
423 umask( $oldumask );
424 return $archive;
425 }
426
427 function wfRecordUpload( $name, $oldver, $size, $desc )
428 {
429 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
430 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
431
432 $fname = "wfRecordUpload";
433
434 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
435 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
436 $res = wfQuery( $sql, DB_READ, $fname );
437
438 $now = wfTimestampNow();
439 $won = wfInvertTimestamp( $now );
440
441 if ( $wgUseCopyrightUpload )
442 {
443 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
444 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
445 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
446 }
447 else $textdesc = $desc ;
448
449 if ( 0 == wfNumRows( $res ) ) {
450 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
451 "img_description,img_user,img_user_text) VALUES ('" .
452 wfStrencode( $name ) . "',{$size},'{$now}','" .
453 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
454 "', '" . wfStrencode( $wgUser->getName() ) . "')";
455 wfQuery( $sql, DB_WRITE, $fname );
456
457 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
458 Namespace::getImage() . " AND cur_title='" .
459 wfStrencode( $name ) . "'";
460 $res = wfQuery( $sql, DB_READ, $fname );
461 if ( 0 == wfNumRows( $res ) ) {
462 $common =
463 Namespace::getImage() . ",'" .
464 wfStrencode( $name ) . "','" .
465 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
466 wfStrencode( $wgUser->getName() ) . "','" . $now .
467 "',1";
468 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
469 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
470 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
471 $common .
472 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
473 wfQuery( $sql, DB_WRITE, $fname );
474 $id = wfInsertId() or 0; # We should throw an error instead
475 $sql = "INSERT INTO recentchanges (rc_namespace,rc_title,
476 rc_comment,rc_user,rc_user_text,rc_timestamp,rc_new,
477 rc_cur_id,rc_cur_time) VALUES ({$common},{$id},'{$now}')";
478 wfQuery( $sql, DB_WRITE, $fname );
479 $u = new SearchUpdate( $id, $name, $desc );
480 $u->doUpdate();
481 }
482 } else {
483 $s = wfFetchObject( $res );
484
485 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
486 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
487 wfStrencode( $s->img_name ) . "','" .
488 wfStrencode( $oldver ) .
489 "',{$s->img_size},'{$s->img_timestamp}','" .
490 wfStrencode( $s->img_description ) . "','" .
491 wfStrencode( $s->img_user ) . "','" .
492 wfStrencode( $s->img_user_text) . "')";
493 wfQuery( $sql, DB_WRITE, $fname );
494
495 $sql = "UPDATE image SET img_size={$size}," .
496 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
497 $wgUser->getID() . "',img_user_text='" .
498 wfStrencode( $wgUser->getName() ) . "', img_description='" .
499 wfStrencode( $desc ) . "' WHERE img_name='" .
500 wfStrencode( $name ) . "'";
501 wfQuery( $sql, DB_WRITE, $fname );
502
503 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
504 Namespace::getImage() . " AND cur_title='" .
505 wfStrencode( $name ) . "'";
506 wfQuery( $sql, DB_WRITE, $fname );
507 }
508
509 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
510 $da = str_replace( "$1", "[[:" . $wgLang->getNsText(
511 Namespace::getImage() ) . ":{$name}|{$name}]]",
512 wfMsg( "uploadedimage" ) );
513 $ta = str_replace( "$1", $name, wfMsg( "uploadedimage" ) );
514 $log->addEntry( $da, $desc, $ta );
515 }
516
517
518 /* Some generic result counters, pulled out of SearchEngine */
519
520 function wfShowingResults( $offset, $limit )
521 {
522 $top = str_replace( "$1", $limit, wfMsg( "showingresults" ) );
523 $top = str_replace( "$2", $offset+1, $top );
524 return $top;
525 }
526
527 function wfShowingResultsNum( $offset, $limit, $num )
528 {
529 $top = str_replace( "$1", $limit, wfMsg( "showingresultsnum" ) );
530 $top = str_replace( "$2", $offset+1, $top );
531 $top = str_replace( "$3", $num, $top );
532 return $top;
533 }
534
535 function wfViewPrevNext( $offset, $limit, $link, $query = "" )
536 {
537 global $wgUser;
538 $prev = str_replace( "$1", $limit, wfMsg( "prevn" ) );
539 $next = str_replace( "$1", $limit, wfMsg( "nextn" ) );
540
541 $sk = $wgUser->getSkin();
542 if ( 0 != $offset ) {
543 $po = $offset - $limit;
544 if ( $po < 0 ) { $po = 0; }
545 $q = "limit={$limit}&offset={$po}";
546 if ( "" != $query ) { $q .= "&{$query}"; }
547 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
548 } else { $plink = $prev; }
549
550 $no = $offset + $limit;
551 $q = "limit={$limit}&offset={$no}";
552 if ( "" != $query ) { $q .= "&{$query}"; }
553
554 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
555 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
556 wfNumLink( $offset, 50, $link, $query ) . " | " .
557 wfNumLink( $offset, 100, $link, $query ) . " | " .
558 wfNumLink( $offset, 250, $link, $query ) . " | " .
559 wfNumLink( $offset, 500, $link, $query );
560
561 $sl = str_replace( "$1", $plink, wfMsg( "viewprevnext" ) );
562 $sl = str_replace( "$2", $nlink, $sl );
563 $sl = str_replace( "$3", $nums, $sl );
564 return $sl;
565 }
566
567 function wfNumLink( $offset, $limit, $link, $query = "" )
568 {
569 global $wgUser;
570 if ( "" == $query ) { $q = ""; }
571 else { $q = "{$query}&"; }
572 $q .= "limit={$limit}&offset={$offset}";
573
574 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
575 return $s;
576 }
577
578 function wfClientAcceptsGzip() {
579 global $wgUseGzip;
580 if( $wgUseGzip ) {
581 # FIXME: we may want to blacklist some broken browsers
582 if( preg_match(
583 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
584 $_SERVER["HTTP_ACCEPT_ENCODING"],
585 $m ) ) {
586 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
587 wfDebug( " accepts gzip\n" );
588 return true;
589 }
590 }
591 return false;
592 }
593
594 # Yay, more global functions!
595 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
596 global $wgUser;
597
598 $limit = (int)$_REQUEST['limit'];
599 if( $limit < 0 ) $limit = 0;
600 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
601 $limit = (int)$wgUser->getOption( $optionname );
602 }
603 if( $limit <= 0 ) $limit = $deflimit;
604 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
605
606 $offset = (int)$_REQUEST['offset'];
607 $offset = (int)$offset;
608 if( $offset < 0 ) $offset = 0;
609 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
610
611 return array( $limit, $offset );
612 }
613
614 # Used in OutputPage::replaceVariables and Article:pstPass2
615 function replaceMsgVar( $matches ) {
616 return wfMsg( $matches[1] );
617 }
618
619 function replaceMsgVarNw( $matches ) {
620 $text = htmlspecialchars( wfMsg( $matches[1] ) );
621 return $text;
622 }
623
624 ?>