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