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