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