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