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" );
14 * Compatibility functions
17 # PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
18 # <4.1.x will not work, as we use a number of features introduced in 4.1.0
19 # such as the new autoglobals.
21 if( !function_exists('iconv') ) {
22 # iconv support is not in the default configuration and so may not be present.
23 # Assume will only ever use utf-8 and iso-8859-1.
24 # This will *not* work in all circumstances.
25 function iconv( $from, $to, $string ) {
26 if(strcasecmp( $from, $to ) == 0) return $string;
27 if(strcasecmp( $from, "utf-8" ) == 0) return utf8_decode( $string );
28 if(strcasecmp( $to, "utf-8" ) == 0) return utf8_encode( $string );
33 if( !function_exists('file_get_contents') ) {
34 # Exists in PHP 4.3.0+
35 function file_get_contents( $filename ) {
36 return implode( "", file( $filename ) );
40 $wgRandomSeeded = false;
42 function wfSeedRandom()
44 global $wgRandomSeeded;
46 if ( ! $wgRandomSeeded ) {
47 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
49 $wgRandomSeeded = true;
53 function wfLocalUrl( $a, $q = "" )
55 global $wgServer, $wgScript, $wgArticlePath;
57 $a = str_replace( " ", "_", $a );
58 #$a = wfUrlencode( $a ); # This stuff is _already_ URL-encoded.
64 $a = "{$wgScript}?{$q}";
66 } else if ( "" == $q ) {
67 $a = str_replace( "$1", $a, $wgArticlePath );
69 $a = "{$wgScript}?title={$a}&{$q}";
74 function wfLocalUrlE( $a, $q = "" )
76 return wfEscapeHTML( wfLocalUrl( $a, $q ) );
79 function wfFullUrl( $a, $q = "" ) {
81 return $wgServer . wfLocalUrl( $a, $q );
84 function wfFullUrlE( $a, $q = "" ) {
85 return wfEscapeHTML( wfFullUrl( $a, $q ) );
88 function wfImageUrl( $img )
92 $nt = Title
::newFromText( $img );
95 $name = $nt->getDBkey();
98 $url = "{$wgUploadPath}/" . $hash{0} . "/" .
99 substr( $hash, 0, 2 ) . "/{$name}";
100 return wfUrlencode( $url );
103 function wfImageArchiveUrl( $name )
105 global $wgUploadPath;
107 $hash = md5( substr( $name, 15) );
108 $url = "{$wgUploadPath}/archive/" . $hash{0} . "/" .
109 substr( $hash, 0, 2 ) . "/{$name}";
113 function wfUrlencode ( $s )
115 $ulink = urlencode( $s );
116 $ulink = preg_replace( "/%3[Aa]/", ":", $ulink );
117 $ulink = preg_replace( "/%2[Ff]/", "/", $ulink );
121 function wfUtf8Sequence($codepoint) {
122 if($codepoint < 0x80) return chr($codepoint);
123 if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f |
0xc0) .
124 chr($codepoint & 0x3f |
0x80);
125 if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f |
0xe0) .
126 chr($codepoint >> 6 & 0x3f |
0x80) .
127 chr($codepoint & 0x3f |
0x80);
128 if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 |
0xf0) . # Double-check this
129 chr($codepoint >> 12 & 0x3f |
0x80) .
130 chr($codepoint >> 6 & 0x3f |
0x80) .
131 chr($codepoint & 0x3f |
0x80);
132 # Doesn't yet handle outside the BMP
133 return "&#$codepoint;";
136 function wfMungeToUtf8($string) {
137 global $wgInputEncoding; # This is debatable
138 #$string = iconv($wgInputEncoding, "UTF-8", $string);
139 $string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
140 $string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
141 # Should also do named entities here
145 function wfDebug( $text, $logonly = false )
147 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly;
149 if ( $wgDebugComments && !$logonly ) {
150 $wgOut->debug( $text );
152 if ( "" != $wgDebugLogFile && !$wgProfileOnly ) {
153 error_log( $text, 3, $wgDebugLogFile );
157 function wfReadOnly()
159 global $wgReadOnlyFile;
161 if ( "" == $wgReadOnlyFile ) { return false; }
162 return is_file( $wgReadOnlyFile );
165 $wgReplacementKeys = array( "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" );
167 # Get a message from anywhere
168 function wfMsg( $key ) {
169 $args = func_get_args();
170 if ( count( $args ) ) {
171 array_shift( $args );
173 return wfMsgReal( $key, $args, true );
176 # Get a message from the language file
177 function wfMsgNoDB( $key ) {
178 $args = func_get_args();
179 if ( count( $args ) ) {
180 array_shift( $args );
182 return wfMsgReal( $key, $args, false );
185 # Really get a message
186 function wfMsgReal( $key, $args, $useDB ) {
187 global $wgLang, $wgReplacementKeys, $wgMemc, $wgDBname;
188 global $wgUseDatabaseMessages, $wgUseMemCached, $wgOut;
189 global $wgAllMessagesEn, $wgLanguageCode;
192 wfProfileIn( $fname );
194 static $messageCache = false;
195 $memcKey = "$wgDBname:messages";
199 # newFromText is too slow!
200 $title = ucfirst( $key );
201 if ( $messageCache ) {
202 $message = $messageCache[$title];
203 } elseif ( !$wgUseDatabaseMessages ||
!$useDB ) {
204 $message = $wgLang->getMessage( $key );
207 if ( !$message && $wgUseMemCached ) {
209 if ( !$messageCache ) {
210 $messageCache = $wgMemc->get( $memcKey );
213 # If there's nothing in memcached, load all the messages from the database
214 # This should only happen on server reset -- ordinary changes should update
215 # memcached in editUpdates()
216 if ( !$messageCache ) {
217 # Other threads don't need to load the messages if another thread is doing it.
218 $wgMemc->set( $memcKey, "loading", time() +
60 );
219 $messageCache = wfLoadAllMessages();
221 $wgMemc->set( $memcKey, $messageCache, time() +
3600 );
225 if ( is_array( $messageCache ) && array_key_exists( $title, $messageCache ) ) {
226 $message = $messageCache[$title];
230 # If there was no MemCached, load each message from the DB individually
233 $sql = "SELECT cur_text FROM cur WHERE cur_namespace=" . NS_MEDIAWIKI
.
234 " AND cur_title='$title'";
235 $res = wfQuery( $sql, DB_READ
, $fname );
237 if ( wfNumRows( $res ) ) {
238 $obj = wfFetchObject( $res );
239 $message = $obj->cur_text
;
240 wfFreeResult( $res );
245 # Try the array in $wgLang
247 $message = $wgLang->getMessage( $key );
250 # Try the English array
251 if ( !$message && $wgLanguageCode != "en" ) {
252 $message = Language
::getMessage( $key );
256 if( count( $args ) ) {
257 $message = str_replace( $wgReplacementKeys, $args, $message );
259 wfProfileOut( $fname );
261 # Failed, message does not exist
262 return "<$key>";
267 function wfCleanFormFields( $fields )
269 global $HTTP_POST_VARS;
270 global $wgInputEncoding, $wgOutputEncoding, $wgEditEncoding, $wgLang;
272 if ( get_magic_quotes_gpc() ) {
273 foreach ( $fields as $fname ) {
274 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
275 $HTTP_POST_VARS[$fname] = stripslashes(
276 $HTTP_POST_VARS[$fname] );
279 if ( isset( $
{$fname} ) ) {
280 $
{$fname} = stripslashes( $
{$fname} );
284 $enc = $wgOutputEncoding;
285 if( $wgEditEncoding != "") $enc = $wgEditEncoding;
286 if ( $enc != $wgInputEncoding ) {
287 foreach ( $fields as $fname ) {
288 if ( isset( $HTTP_POST_VARS[$fname] ) ) {
289 $HTTP_POST_VARS[$fname] = $wgLang->iconv(
290 $wgOutputEncoding, $wgInputEncoding,
291 $HTTP_POST_VARS[$fname] );
294 if ( isset( $
{$fname} ) ) {
295 $
{$fname} = $wgLang->iconv(
296 $enc, $wgInputEncoding, $
{$fname} );
302 function wfMungeQuotes( $in )
304 $out = str_replace( "%", "%25", $in );
305 $out = str_replace( "'", "%27", $out );
306 $out = str_replace( "\"", "%22", $out );
310 function wfDemungeQuotes( $in )
312 $out = str_replace( "%22", "\"", $in );
313 $out = str_replace( "%27", "'", $out );
314 $out = str_replace( "%25", "%", $out );
318 function wfCleanQueryVar( $var )
321 if ( get_magic_quotes_gpc() ) {
322 $var = stripslashes( $var );
324 return $wgLang->recodeInput( $var );
327 function wfSpecialPage()
329 global $wgUser, $wgOut, $wgTitle, $wgLang;
331 /* FIXME: this list probably shouldn't be language-specific, per se */
332 $validSP = $wgLang->getValidSpecialPages();
333 $sysopSP = $wgLang->getSysopSpecialPages();
334 $devSP = $wgLang->getDeveloperSpecialPages();
336 $wgOut->setArticleFlag( false );
337 $wgOut->setRobotpolicy( "noindex,follow" );
340 list($t, $par) = split( "/", $wgTitle->getDBkey(), 2 );
342 if ( array_key_exists( $t, $validSP ) ||
343 ( $wgUser->isSysop() && array_key_exists( $t, $sysopSP ) ) ||
344 ( $wgUser->isDeveloper() && array_key_exists( $t, $devSP ) ) ) {
346 $wgTitle = Title
::makeTitle( Namespace::getSpecial(), $t );
348 $wgOut->setPageTitle( wfMsg( strtolower( $wgTitle->getText() ) ) );
350 $inc = "Special" . $t . ".php";
351 include_once( $inc );
352 $call = "wfSpecial" . $t;
354 } else if ( array_key_exists( $t, $sysopSP ) ) {
355 $wgOut->sysopRequired();
356 } else if ( array_key_exists( $t, $devSP ) ) {
357 $wgOut->developerRequired();
359 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
363 function wfSearch( $s )
365 $se = new SearchEngine( wfCleanQueryVar( $s ) );
370 { # pick the nearest match
371 $se = new SearchEngine( wfCleanQueryVar( $s ) );
375 function wfNumberOfArticles()
377 global $wgNumberOfArticles;
380 return $wgNumberOfArticles;
383 /* private */ function wfLoadSiteStats()
385 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
386 if ( -1 != $wgNumberOfArticles ) return;
388 $sql = "SELECT ss_total_views, ss_total_edits, ss_good_articles " .
389 "FROM site_stats WHERE ss_row_id=1";
390 $res = wfQuery( $sql, DB_READ
, "wfLoadSiteStats" );
392 if ( 0 == wfNumRows( $res ) ) { return; }
394 $s = wfFetchObject( $res );
395 $wgTotalViews = $s->ss_total_views
;
396 $wgTotalEdits = $s->ss_total_edits
;
397 $wgNumberOfArticles = $s->ss_good_articles
;
401 function wfEscapeHTML( $in )
404 array( "&", "\"", ">", "<" ),
405 array( "&", """, ">", "<" ),
409 function wfEscapeHTMLTagsOnly( $in ) {
411 array( "\"", ">", "<" ),
412 array( """, ">", "<" ),
416 function wfUnescapeHTML( $in )
418 $in = str_replace( "<", "<", $in );
419 $in = str_replace( ">", ">", $in );
420 $in = str_replace( """, "\"", $in );
421 $in = str_replace( "&", "&", $in );
425 function wfImageDir( $fname )
427 global $wgUploadDirectory;
429 $hash = md5( $fname );
430 $oldumask = umask(0);
431 $dest = $wgUploadDirectory . "/" . $hash{0};
432 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
433 $dest .= "/" . substr( $hash, 0, 2 );
434 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
440 function wfImageArchiveDir( $fname )
442 global $wgUploadDirectory;
444 $hash = md5( $fname );
445 $oldumask = umask(0);
446 $archive = "{$wgUploadDirectory}/archive";
447 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
448 $archive .= "/" . $hash{0};
449 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
450 $archive .= "/" . substr( $hash, 0, 2 );
451 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
457 function wfRecordUpload( $name, $oldver, $size, $desc )
459 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
460 global $wgUseCopyrightUpload , $wpUploadCopyStatus , $wpUploadSource ;
462 $fname = "wfRecordUpload";
464 $sql = "SELECT img_name,img_size,img_timestamp,img_description,img_user," .
465 "img_user_text FROM image WHERE img_name='" . wfStrencode( $name ) . "'";
466 $res = wfQuery( $sql, DB_READ
, $fname );
468 $now = wfTimestampNow();
469 $won = wfInvertTimestamp( $now );
470 $size = IntVal( $size );
472 if ( $wgUseCopyrightUpload )
474 $textdesc = "== " . wfMsg ( "filedesc" ) . " ==\n" . $desc . "\n" .
475 "== " . wfMsg ( "filestatus" ) . " ==\n" . $wpUploadCopyStatus . "\n" .
476 "== " . wfMsg ( "filesource" ) . " ==\n" . $wpUploadSource ;
478 else $textdesc = $desc ;
480 $now = wfTimestampNow();
481 $won = wfInvertTimestamp( $now );
483 if ( 0 == wfNumRows( $res ) ) {
484 $sql = "INSERT INTO image (img_name,img_size,img_timestamp," .
485 "img_description,img_user,img_user_text) VALUES ('" .
486 wfStrencode( $name ) . "',$size,'{$now}','" .
487 wfStrencode( $desc ) . "', '" . $wgUser->getID() .
488 "', '" . wfStrencode( $wgUser->getName() ) . "')";
489 wfQuery( $sql, DB_WRITE
, $fname );
491 $sql = "SELECT cur_id,cur_text FROM cur WHERE cur_namespace=" .
492 Namespace::getImage() . " AND cur_title='" .
493 wfStrencode( $name ) . "'";
494 $res = wfQuery( $sql, DB_READ
, $fname );
495 if ( 0 == wfNumRows( $res ) ) {
497 Namespace::getImage() . ",'" .
498 wfStrencode( $name ) . "','" .
499 wfStrencode( $desc ) . "','" . $wgUser->getID() . "','" .
500 wfStrencode( $wgUser->getName() ) . "','" . $now .
502 $sql = "INSERT INTO cur (cur_namespace,cur_title," .
503 "cur_comment,cur_user,cur_user_text,cur_timestamp,cur_is_new," .
504 "cur_text,inverse_timestamp,cur_touched) VALUES (" .
506 ",'" . wfStrencode( $textdesc ) . "','{$won}','{$now}')";
507 wfQuery( $sql, DB_WRITE
, $fname );
508 $id = wfInsertId() or 0; # We should throw an error instead
509 $sql = "INSERT INTO recentchanges (rc_namespace,rc_title,
510 rc_comment,rc_user,rc_user_text,rc_timestamp,rc_new,
511 rc_cur_id,rc_cur_time) VALUES ({$common},{$id},'{$now}')";
512 wfQuery( $sql, DB_WRITE
, $fname );
513 $u = new SearchUpdate( $id, $name, $desc );
517 $s = wfFetchObject( $res );
519 $sql = "INSERT INTO oldimage (oi_name,oi_archive_name,oi_size," .
520 "oi_timestamp,oi_description,oi_user,oi_user_text) VALUES ('" .
521 wfStrencode( $s->img_name
) . "','" .
522 wfStrencode( $oldver ) .
523 "',{$s->img_size},'{$s->img_timestamp}','" .
524 wfStrencode( $s->img_description
) . "','" .
525 wfStrencode( $s->img_user
) . "','" .
526 wfStrencode( $s->img_user_text
) . "')";
527 wfQuery( $sql, DB_WRITE
, $fname );
529 $sql = "UPDATE image SET img_size={$size}," .
530 "img_timestamp='" . wfTimestampNow() . "',img_user='" .
531 $wgUser->getID() . "',img_user_text='" .
532 wfStrencode( $wgUser->getName() ) . "', img_description='" .
533 wfStrencode( $desc ) . "' WHERE img_name='" .
534 wfStrencode( $name ) . "'";
535 wfQuery( $sql, DB_WRITE
, $fname );
537 $sql = "UPDATE cur SET cur_touched='{$now}' WHERE cur_namespace=" .
538 Namespace::getImage() . " AND cur_title='" .
539 wfStrencode( $name ) . "'";
540 wfQuery( $sql, DB_WRITE
, $fname );
543 $log = new LogPage( wfMsg( "uploadlogpage" ), wfMsg( "uploadlogpagetext" ) );
544 $da = wfMsg( "uploadedimage", "[[:" . $wgLang->getNsText(
545 Namespace::getImage() ) . ":{$name}|{$name}]]" );
546 $ta = wfMsg( "uploadedimage", $name );
547 $log->addEntry( $da, $desc, $ta );
551 /* Some generic result counters, pulled out of SearchEngine */
553 function wfShowingResults( $offset, $limit )
555 return wfMsg( "showingresults", $limit, $offset+
1 );
558 function wfShowingResultsNum( $offset, $limit, $num )
560 return wfMsg( "showingresultsnum", $limit, $offset+
1, $num );
563 function wfViewPrevNext( $offset, $limit, $link, $query = "" )
566 $prev = wfMsg( "prevn", $limit );
567 $next = wfMsg( "nextn", $limit );
569 $sk = $wgUser->getSkin();
570 if ( 0 != $offset ) {
571 $po = $offset - $limit;
572 if ( $po < 0 ) { $po = 0; }
573 $q = "limit={$limit}&offset={$po}";
574 if ( "" != $query ) { $q .= "&{$query}"; }
575 $plink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$prev}</a>";
576 } else { $plink = $prev; }
578 $no = $offset +
$limit;
579 $q = "limit={$limit}&offset={$no}";
580 if ( "" != $query ) { $q .= "&{$query}"; }
582 $nlink = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$next}</a>";
583 $nums = wfNumLink( $offset, 20, $link , $query ) . " | " .
584 wfNumLink( $offset, 50, $link, $query ) . " | " .
585 wfNumLink( $offset, 100, $link, $query ) . " | " .
586 wfNumLink( $offset, 250, $link, $query ) . " | " .
587 wfNumLink( $offset, 500, $link, $query );
589 return wfMsg( "viewprevnext", $plink, $nlink, $nums );
592 function wfNumLink( $offset, $limit, $link, $query = "" )
595 if ( "" == $query ) { $q = ""; }
596 else { $q = "{$query}&"; }
597 $q .= "limit={$limit}&offset={$offset}";
599 $s = "<a href=\"" . wfLocalUrlE( $link, $q ) . "\">{$limit}</a>";
603 function wfClientAcceptsGzip() {
606 # FIXME: we may want to blacklist some broken browsers
608 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
609 $_SERVER["HTTP_ACCEPT_ENCODING"],
611 if( ( $m[1] == "q" ) && ( $m[2] == 0 ) ) return false;
612 wfDebug( " accepts gzip\n" );
619 # Yay, more global functions!
620 function wfCheckLimits( $deflimit = 50, $optionname = "rclimit" ) {
623 $limit = (int)$_REQUEST['limit'];
624 if( $limit < 0 ) $limit = 0;
625 if( ( $limit == 0 ) && ( $optionname != "" ) ) {
626 $limit = (int)$wgUser->getOption( $optionname );
628 if( $limit <= 0 ) $limit = $deflimit;
629 if( $limit > 5000 ) $limit = 5000; # We have *some* limits...
631 $offset = (int)$_REQUEST['offset'];
632 $offset = (int)$offset;
633 if( $offset < 0 ) $offset = 0;
634 if( $offset > 65000 ) $offset = 65000; # do we need a max? what?
636 return array( $limit, $offset );
639 # Escapes the given text so that it may be output using addWikiText()
640 # without any linking, formatting, etc. making its way through. This
641 # is achieved by substituting certain characters with HTML entities.
642 # As required by the callers, <nowiki> is not used. It currently does
643 # not filter out characters which have special meaning only at the
644 # start of a line, such as "*".
645 function wfEscapeWikiText( $text )
648 array( '[', "'", 'ISBN ' , '://' , "\n=" ),
649 array( '[', ''', 'ISBN ', '://' , "\n=" ),
650 htmlspecialchars($text) );
654 # Loads the entire MediaWiki namespace, returns the array
655 function wfLoadAllMessages()
657 $sql = "SELECT cur_title,cur_text FROM cur WHERE cur_namespace=" . NS_MEDIAWIKI
;
658 $res = wfQuery( $sql, DB_READ
, $fname );
661 for ( $row = wfFetchObject( $res ); $row; $row = wfFetchObject( $res ) ) {
662 $messages[$row->cur_title
] = $row->cur_text
;
664 wfFreeResult( $res );
668 function wfQuotedPrintable( $string, $charset = "" )
670 # Probably incomplete; see RFC 2045
671 if( empty( $charset ) ) {
672 global $wgInputEncoding;
673 $charset = $wgInputEncoding;
675 $charset = strtoupper( $charset );
676 $charset = str_replace( "ISO-8859", "ISO8859", $charset ); // ?
678 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
679 $replace = $illegal . '\t ?_';
680 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
681 $out = "=?$charset?Q?";
682 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );