2 # Global functions used everywhere
4 $wgNumberOfArticles = -1; # Unset
9 include_once( "$IP/DatabaseFunctions.php" );
10 include_once( "$IP/UpdateClasses.php" );
11 include_once( "$IP/LogPage.php" );
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
18 if ( phpversion() == "4.0.6" ) {
19 function array_key_exists( $k, $a ) {
20 return key_exists( $k, $a );
22 } else if (phpversion() < "4.1") {
23 function array_key_exists( $k, $a ) {
28 $wgRandomSeeded = false;
30 function wfSeedRandom()
32 global $wgRandomSeeded;
34 if ( ! $wgRandomSeeded ) {
35 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
37 $wgRandomSeeded = true;
41 function wfLocalUrl( $a, $q = "" )
43 global $wgServer, $wgScript, $wgArticlePath;
45 $a = str_replace( " ", "_", $a );
46 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
52 $a = "{$wgScript}?{$q}";
54 } else if ( "" == $q ) {
55 $a = str_replace( "$1", $a, $wgArticlePath );
57 $a = "{$wgScript}?title={$a}&{$q}";
62 function wfLocalUrlE( $a, $q = "" )
64 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
67 function wfFullUrl( $a, $q = "" ) {
69 return $wgServer . wfLocalUrl( $a, $q );
72 function wfFullUrlE( $a, $q = "" ) {
73 return wfEscapeHTML( wfFullUrl( $a, $q ) );
76 function wfImageUrl( $img )
80 $nt = Title
::newFromText( $img );
81 $name = $nt->getDBkey();
84 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
85 substr( $hash, 0, 2 ) . "/{$name}";
86 return wfUrlencode( $url );
89 function wfImageArchiveUrl( $name )
93 $hash = md5( substr( $name, 15) );
94 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
95 substr( $hash, 0, 2 ) . "/{$name}";
99 function wfUrlencode ( $s )
101 $ulink = urlencode( $s );
102 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
103 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
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;";
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
131 function wfDebug( $text, $logonly = false )
133 global $wgOut, $wgDebugLogFile, $wgDebugComments;
135 if ( $wgDebugComments && !$logonly ) {
136 $wgOut->debug( $text );
138 if ( "" != $wgDebugLogFile ) {
139 error_log( $text, 3, $wgDebugLogFile );
143 function wfReadOnly()
145 global $wgReadOnlyFile;
147 if ( "" == $wgReadOnlyFile ) { return false; }
148 return is_file( $wgReadOnlyFile );
151 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
153 function wfMsg( $key ) {
154 $args = func_get_args();
155 if ( count( $args ) ) {
156 array_shift( $args );
158 return wfMsgReal( $key, $args, true );
161 function wfMsgNoDB( $key ) {
162 $args = func_get_args();
163 if ( count( $args ) ) {
164 array_shift( $args );
166 return wfMsgReal( $key, $args, false );
169 function wfMsgReal( $key, $args, $useDB ) {
170 global $wgLang, $wgReplacementKeys, $wgMemc, $wgDBname;
171 global $wgUseDatabaseMessages;
173 static $l1cache = array();
175 wfProfileIn( $fname );
179 # Check for DB suppression
180 if ( !$wgUseDatabaseMessages ||
!$useDB ) {
181 $message = $wgLang->getMessage( $key );
185 if ( $message === false && array_key_exists( $key, $l1cache ) ) {
186 $message = $l1cache[$key];
187 if ( $message === false ) {
188 $message = $wgLang->getMessage( $key );
194 if ( $message === false ) {
195 $titleObj = Title
::newFromText( $key );
196 $title = $titleObj->getDBkey();
197 $mcKey = "$wgDBname:MediaWiki:title:$title";
198 $message = $wgMemc->get( $mcKey );
202 if ( $message === false) {
204 $sql = "SELECT cur_text FROM cur WHERE cur_namespace=" . NS_MEDIAWIKI
.
205 " AND cur_title='$title'";
206 $res = wfQuery( $sql, DB_READ
, $fname );
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*/ );
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;
227 if( count( $args ) ) {
228 $message = str_replace( $wgReplacementKeys, $args, $message );
231 wfProfileOut( $fname );
233 if ( "" == $message ) {
234 # Failed, message not translated
235 return "<$key>";
240 function wfCleanFormFields( $fields )
242 global $HTTP_POST_VARS;
243 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
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] );
252 if ( isset( $
{$fname} ) ) {
253 $
{$fname} = stripslashes( $
{$fname} );
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] );
267 if ( isset( $
{$fname} ) ) {
268 $
{$fname} = $wgLang->iconv(
269 $enc, $wgInputEncoding, $
{$fname} );
275 function wfMungeQuotes( $in )
277 $out = str_replace( "%", "%25", $in );
278 $out = str_replace( "'", "%27", $out );
279 $out = str_replace( "\"", "%22", $out );
283 function wfDemungeQuotes( $in )
285 $out = str_replace( "%22", "\"", $in );
286 $out = str_replace( "%27", "'", $out );
287 $out = str_replace( "%25", "%", $out );
291 function wfCleanQueryVar( $var )
294 if ( get_magic_quotes_gpc() ) {
295 $var = stripslashes( $var );
297 return $wgLang->recodeInput( $var );
300 function wfSpecialPage()
302 global $wgUser, $wgOut, $wgTitle, $wgLang;
304 /* FIXME: this list probably shouldn't be language-specific, per se */
305 $validSP = $wgLang->getValidSpecialPages();
306 $sysopSP = $wgLang->getSysopSpecialPages();
307 $devSP = $wgLang->getDeveloperSpecialPages();
309 $wgOut->setArticleFlag( false );
310 $wgOut->setRobotpolicy( "noindex,follow" );
313 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
315 if ( array_key_exists( $t, $validSP ) ||
316 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
317 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
319 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
321 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
323 $inc = "Special" . $t . ".php";
324 include_once( $inc );
325 $call = "wfSpecial" . $t;
327 } else if ( array_key_exists( $t, $sysopSP ) ) {
328 $wgOut->sysopRequired();
329 } else if ( array_key_exists( $t, $devSP ) ) {
330 $wgOut->developerRequired();
332 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
336 function wfSearch( $s )
338 $se = new SearchEngine( wfCleanQueryVar( $s ) );
343 { # pick the nearest match
344 $se = new SearchEngine( wfCleanQueryVar( $s ) );
348 function wfNumberOfArticles()
350 global $wgNumberOfArticles;
353 return $wgNumberOfArticles;
356 /* private */ function wfLoadSiteStats()
358 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
359 if ( -1 != $wgNumberOfArticles ) return;
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" );
365 if ( 0 == wfNumRows( $res ) ) { return; }
367 $s = wfFetchObject( $res );
368 $wgTotalViews = $s->ss_total_views
;
369 $wgTotalEdits = $s->ss_total_edits
;
370 $wgNumberOfArticles = $s->ss_good_articles
;
374 function wfEscapeHTML( $in )
377 array( "&", "\"", ">", "<" ),
378 array( "&", """, ">", "<" ),
382 function wfEscapeHTMLTagsOnly( $in ) {
384 array( "\"", ">", "<" ),
385 array( """, ">", "<" ),
389 function wfUnescapeHTML( $in )
391 $in = str_replace( "<", "<", $in );
392 $in = str_replace( ">", ">", $in );
393 $in = str_replace( """, "\"", $in );
394 $in = str_replace( "&", "&", $in );
398 function wfImageDir( $fname )
400 global $wgUploadDirectory;
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 ); }
413 function wfImageArchiveDir( $fname )
415 global $wgUploadDirectory;
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 ); }
430 function wfRecordUpload( $name, $oldver, $size, $desc )
432 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
433 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
435 $fname = "wfRecordUpload";
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 );
441 $now = wfTimestampNow();
442 $won = wfInvertTimestamp( $now );
444 if ( $wgUseCopyrightUpload )
446 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
447 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
448 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
450 else $textdesc = $desc ;
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 );
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 ) ) {
466 Namespace::getImage() . ",'" .
467 wfStrencode( $name ) . "','" .
468 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
469 wfStrencode( $wgUser->getName() ) . "','" . $now .
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 (" .
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 );
486 $s = wfFetchObject( $res );
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 );
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 );
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 );
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 );
521 /* Some generic result counters, pulled out of SearchEngine */
523 function wfShowingResults( $offset, $limit )
525 $top = str_replace( "$1", $limit, wfMsg( "showingresults" ) );
526 $top = str_replace( "$2", $offset+
1, $top );
530 function wfShowingResultsNum( $offset, $limit, $num )
532 $top = str_replace( "$1", $limit, wfMsg( "showingresultsnum" ) );
533 $top = str_replace( "$2", $offset+
1, $top );
534 $top = str_replace( "$3", $num, $top );
538 function wfViewPrevNext( $offset, $limit, $link, $query = "" )
541 $prev = str_replace( "$1", $limit, wfMsg( "prevn" ) );
542 $next = str_replace( "$1", $limit, wfMsg( "nextn" ) );
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; }
553 $no = $offset +
$limit;
554 $q = "limit={$limit}&offset={$no}";
555 if ( "" != $query ) { $q .= "&{$query}"; }
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 );
564 $sl = str_replace( "$1", $plink, wfMsg( "viewprevnext" ) );
565 $sl = str_replace( "$2", $nlink, $sl );
566 $sl = str_replace( "$3", $nums, $sl );
570 function wfNumLink( $offset, $limit, $link, $query = "" )
573 if ( "" == $query ) { $q = ""; }
574 else { $q = "{$query}&"; }
575 $q .= "limit={$limit}&offset={$offset}";
577 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
581 function wfClientAcceptsGzip() {
584 # FIXME: we may want to blacklist some broken browsers
586 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
587 $_SERVER["HTTP_ACCEPT_ENCODING"],
589 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
590 wfDebug( " accepts gzip\n" );
597 # Yay, more global functions!
598 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
601 $limit = (int)$_REQUEST['limit'];
602 if( $limit < 0 ) $limit = 0;
603 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
604 $limit = (int)$wgUser->getOption( $optionname );
606 if( $limit <= 0 ) $limit = $deflimit;
607 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
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?
614 return array( $limit, $offset );
617 # Used in OutputPage::replaceVariables and Article:pstPass2
618 function replaceMsgVar( $matches ) {
619 return wfMsg( $matches[1] );
622 function replaceMsgVarNw( $matches ) {
623 $text = htmlspecialchars( wfMsg( $matches[1] ) );