4 * NOTE: The settings here should probably not need to be changed.
5 * The user-configurable settings have been moved to IniConfig.php
6 * The run-time code has been moved to lib/IniConfig.php:fix_configs()
9 if (!defined("LC_ALL")) {
11 define("LC_CTYPE", 2);
14 define ('_DEBUG_VERBOSE', 1); // verbose msgs and add validator links on footer
15 define ('_DEBUG_PAGELINKS', 2); // list the extraced pagelinks at the top of each pages
16 define ('_DEBUG_PARSER', 4); // verbose parsing steps
17 define ('_DEBUG_TRACE', 8); // test php memory usage, prints php debug backtraces
18 define ('_DEBUG_INFO', 16);
19 define ('_DEBUG_APD', 32); // APD tracing/profiling
20 define ('_DEBUG_LOGIN', 64); // verbose login debug-msg (settings and reason for failure)
21 define ('_DEBUG_SQL', 128); // force check db, force optimize, print some debugging logs
22 define ('_DEBUG_REMOTE', 256); // remote debug into subrequests (xmlrpc, ajax, wikiwyg, ...)
23 // or test local SearchHighlight.
24 // internal links have persistent ?start_debug=1
27 return (substr(php_sapi_name(),0,3) == 'cgi' and
28 isset($GLOBALS['HTTP_ENV_VARS']['GATEWAY_INTERFACE']) and
29 @preg_match('/CGI/',$GLOBALS['HTTP_ENV_VARS']['GATEWAY_INTERFACE']));
33 // copy some $_ENV vars to $_SERVER for CGI compatibility. php does it automatically since when?
35 foreach (explode(':','SERVER_SOFTWARE:SERVER_NAME:GATEWAY_INTERFACE:SERVER_PROTOCOL:SERVER_PORT:REQUEST_METHOD:HTTP_ACCEPT:PATH_INFO:PATH_TRANSLATED:SCRIPT_NAME:QUERY_STRING:REMOTE_HOST:REMOTE_ADDR:REMOTE_USER:AUTH_TYPE:CONTENT_TYPE:CONTENT_LENGTH') as $key) {
36 $GLOBALS['HTTP_SERVER_VARS'][$key] = &$GLOBALS['HTTP_ENV_VARS'][$key];
41 // essential internal stuff
42 if (!check_php_version(6))
43 set_magic_quotes_runtime(0);
46 * Browser Detection Functions
49 * NS/IE < 4.0 doesn't accept < ? xml version="1.0" ? >
50 * NS/IE < 4.0 cannot display PNG
51 * NS/IE < 4.0 cannot display all XHTML tags
52 * NS < 5.0 needs textarea wrap=virtual
53 * IE55 has problems with transparent PNG's
56 function browserAgent() {
57 static $HTTP_USER_AGENT = false;
58 if ($HTTP_USER_AGENT !== false) return $HTTP_USER_AGENT;
59 if (!$HTTP_USER_AGENT)
60 $HTTP_USER_AGENT = @$GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'];
61 if (!$HTTP_USER_AGENT) // CGI
62 $HTTP_USER_AGENT = @$GLOBALS['HTTP_ENV_VARS']['HTTP_USER_AGENT'];
63 if (!$HTTP_USER_AGENT) // local CGI testing
64 $HTTP_USER_AGENT = 'none';
65 return $HTTP_USER_AGENT;
67 function browserDetect($match) {
68 return (strpos(strtolower(browserAgent()), strtolower($match)) !== false);
70 // returns a similar number for Netscape/Mozilla (gecko=5.0)/IE/Opera features.
71 function browserVersion() {
72 $agent = browserAgent();
73 if (strstr($agent, "Mozilla/4.0 (compatible; MSIE"))
74 return (float)substr($agent, 30);
75 elseif (strstr($agent, "Mozilla/5.0 (compatible; Konqueror/"))
76 return (float)substr($agent, 36);
77 elseif (strstr($agent, "AppleWebKit/"))
78 return (float)substr($agent, strpos($agent, "AppleWebKit/") + 12);
80 return (float)substr($agent, 8);
82 function isBrowserIE() {
83 return (browserDetect('Mozilla/') and
84 browserDetect('MSIE'));
86 // problem with transparent PNG's
87 function isBrowserIE55() {
88 return (isBrowserIE() and
89 browserVersion() > 5.1 and browserVersion() < 6.0);
91 // old Netscape prior to Mozilla
92 function isBrowserNetscape($version = false) {
93 $agent = (browserDetect('Mozilla/') and
94 ! browserDetect('Gecko/') and
95 ! browserDetect('MSIE'));
96 if ($version) return $agent and browserVersion() >= $version;
100 function isBrowserNS3() {
101 return (isBrowserNetscape() and browserVersion() < 4.0);
104 function isBrowserNS4() {
105 return (isBrowserNetscape() and browserVersion() < 5.0);
107 // must omit display alternate stylesheets: konqueror 3.1.4
108 // http://sourceforge.net/tracker/index.php?func=detail&aid=945154&group_id=6121&atid=106121
109 function isBrowserKonqueror($version = false) {
110 if ($version) return browserDetect('Konqueror/') and browserVersion() >= $version;
111 return browserDetect('Konqueror/');
113 // MacOSX Safari has certain limitations. Need detection and patches.
114 // * no <object>, only <embed>
115 function isBrowserSafari($version = false) {
116 $found = browserDetect('Spoofer/');
117 $found = browserDetect('AppleWebKit/') or $found;
118 if ($version) return $found and browserVersion() >= $version;
121 function isBrowserOpera($version = false) {
122 if ($version) return browserDetect('Opera/') and browserVersion() >= $version;
123 return browserDetect('Opera/');
128 * If $LANG is undefined:
129 * Smart client language detection, based on our supported languages
130 * HTTP_ACCEPT_LANGUAGE="de-at,en;q=0.5"
132 * We should really check additionally if the i18n HomePage version is defined.
133 * So must defer this to the request loop.
135 function guessing_lang ($languages=false) {
138 $languages = array("en","de","es","fr","it","ja","zh","nl","sv");
139 // ignore possible "_<territory>" and codeset "ja.utf8"
141 require_once("lib/WikiTheme.php");
142 $languages = listAvailableLanguages();
143 if (defined('DEFAULT_LANGUAGE') and in_array(DEFAULT_LANGUAGE, $languages))
146 if ($i = array_search(DEFAULT_LANGUAGE, $languages) !== false) {
147 array_splice($languages, $i, 1);
149 array_unshift($languages, DEFAULT_LANGUAGE);
150 foreach ($languages as $lang) {
151 $arr = FileFinder::locale_versions($lang);
152 $languages = array_merge($languages, $arr);
159 if (isset($GLOBALS['request'])) // in fixup-dynamic-config there's no request yet
160 $accept = $GLOBALS['request']->get('HTTP_ACCEPT_LANGUAGE');
161 elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
162 $accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
165 $lang_list = array();
166 $list = explode(",", $accept);
167 for ($i=0; $i<count($list); $i++) {
168 $pos = strchr($list[$i], ";") ;
169 if ($pos === false) {
170 // No Q it is only a locale...
171 $lang_list[$list[$i]] = 100;
174 $q = explode(";",$list[$i]) ;
176 $q = explode("=",$q[1]) ;
177 $lang_list[$loc] = $q[1]*100 ;
184 // compare with languages, ignoring sublang and charset
185 foreach ($lang_list as $lang => $q) {
186 if (in_array($lang, $languages))
188 // de_DE.iso8859-1@euro => de_DE.iso8859-1, de_DE, de
189 // de-DE => de-DE, de
190 foreach (array('@', '.', '_') as $sep) {
191 if ( ($tail = strchr($lang, $sep)) ) {
192 $lang_short = substr($lang, 0, -strlen($tail));
193 if (in_array($lang_short, $languages))
197 if ($pos = strchr($lang, "-") and in_array(substr($lang, 0, $pos), $languages))
198 return substr($lang, 0, $pos);
201 return $languages[0];
207 * This is a version of the builtin setlocale() which is
208 * smart enough to try some alternatives...
210 * @param mixed $category
211 * @param string $locale
212 * @return string The new locale, or <code>false</code> if unable
213 * to set the requested locale.
217 function guessing_setlocale ($category, $locale) {
218 $alt = array('en' => array('C', 'en_US', 'en_GB', 'en_AU', 'en_CA', 'english'),
219 'de' => array('de_DE', 'de_DE', 'de_DE@euro',
220 'de_AT@euro', 'de_AT', 'German_Austria.1252', 'deutsch',
222 'es' => array('es_ES', 'es_MX', 'es_AR', 'spanish'),
223 'nl' => array('nl_NL', 'dutch'),
224 'fr' => array('fr_FR', 'français', 'french'),
225 'it' => array('it_IT'),
226 'sv' => array('sv_SE'),
227 'ja.utf-8' => array('ja_JP','ja_JP.utf-8','japanese'),
228 'ja.euc-jp' => array('ja_JP','ja_JP.eucJP','japanese.euc'),
229 'zh' => array('zh_TW', 'zh_CN'),
231 if (!$locale or $locale=='C') {
232 // do the reverse: return the detected locale collapsed to our LANG
233 $locale = setlocale($category, '');
235 if (strstr($locale, '_')) list ($lang) = split('_', $locale);
236 else $lang = $locale;
237 if (strlen($lang) > 2) {
238 foreach ($alt as $try => $locs) {
239 if (in_array($locale, $locs) or in_array($lang, $locs)) {
240 //if (empty($GLOBALS['LANG'])) $GLOBALS['LANG'] = $try;
247 if (strlen($locale) == 2)
250 list ($lang) = split('_', $locale);
251 if (!isset($alt[$lang]))
254 foreach ($alt[$lang] as $try) {
255 if ($res = setlocale($category, $try))
257 // Try with charset appended...
258 $try = $try . '.' . $GLOBALS['charset'];
259 if ($res = setlocale($category, $try))
261 foreach (array(".", '@', '_') as $sep) {
262 if ($i = strpos($try, $sep)) {
263 $try = substr($try, 0, $i);
264 if (($res = setlocale($category, $try)))
270 // A standard locale name is typically of the form
271 // language[_territory][.codeset][@modifier], where language is
272 // an ISO 639 language code, territory is an ISO 3166 country code,
273 // and codeset is a character set or encoding identifier like
274 // ISO-8859-1 or UTF-8.
278 function update_locale($loc) {
279 if ($loc == 'C' or $loc == 'en') return;
280 // $LANG or DEFAULT_LANGUAGE is too less information, at least on unix for
281 // setlocale(), for bindtextdomain() to succeed.
282 $setlocale = guessing_setlocale(LC_ALL, $loc); // [56ms]
283 if (!$setlocale) { // system has no locale for this language, so gettext might fail
284 $setlocale = FileFinder::_get_lang();
285 list ($setlocale,) = split('_', $setlocale, 2);
286 $setlocale = guessing_setlocale(LC_ALL, $setlocale); // try again
287 if (!$setlocale) $setlocale = $loc;
289 // Try to put new locale into environment (so any
290 // programs we run will get the right locale.)
291 if (!function_exists('bindtextdomain')) {
292 // Reinitialize translation array.
295 // do reinit to purge PHP's static cache [43ms]
296 if ( ($lcfile = FindLocalizedFile("LC_MESSAGES/phpwiki.php", 'missing_ok', 'reinit')) ) {
300 // If PHP is in safe mode, this is not allowed,
302 @putenv("LC_ALL=$setlocale");
303 @putenv("LANG=$loc");
304 @putenv("LANGUAGE=$loc");
307 // To get the POSIX character classes in the PCRE's (e.g.
308 // [[:upper:]]) to match extended characters (e.g. GrüßGott), we have
309 // to set the locale, using setlocale().
311 // The problem is which locale to set? We would like to recognize all
312 // upper-case characters in the iso-8859-1 character set as upper-case
313 // characters --- not just the ones which are in the current $LANG.
315 // As it turns out, at least on my system (Linux/glibc-2.2) as long as
316 // you setlocale() to anything but "C" it works fine. (I'm not sure
317 // whether this is how it's supposed to be, or whether this is a bug
320 // We don't currently use the locale setting for anything else, so for
321 // now, just set the locale to US English.
323 // FIXME: Not all environments may support en_US? We should probably
324 // have a list of locales to try.
325 if (setlocale(LC_CTYPE, 0) == 'C') {
326 $x = setlocale(LC_CTYPE, 'en_US.' . $GLOBALS['charset']);
328 $x = setlocale(LC_CTYPE, $setlocale);
334 /** string pcre_fix_posix_classes (string $regexp)
336 * Older version (pre 3.x?) of the PCRE library do not support
337 * POSIX named character classes (e.g. [[:alnum:]]).
339 * This is a helper function which can be used to convert a regexp
340 * which contains POSIX named character classes to one that doesn't.
342 * All instances of strings like '[:<class>:]' are replaced by the equivalent
343 * enumerated character class.
345 * Implementation Notes:
347 * Currently we use hard-coded values which are valid only for
348 * ISO-8859-1. Also, currently on the classes [:alpha:], [:alnum:],
349 * [:upper:] and [:lower:] are implemented. (The missing classes:
350 * [:blank:], [:cntrl:], [:digit:], [:graph:], [:print:], [:punct:],
351 * [:space:], and [:xdigit:] could easily be added if needed.)
353 * This is a hack. I tried to generate these classes automatically
354 * using ereg(), but discovered that in my PHP, at least, ereg() is
355 * slightly broken w.r.t. POSIX character classes. (It includes
356 * "\xaa" and "\xba" in [:alpha:].)
358 * So for now, this will do. --Jeff <dairiki@dairiki.org> 14 Mar, 2001
360 function pcre_fix_posix_classes ($regexp) {
363 if (defined('GFORGE') and GFORGE) {
367 if (!isset($charset))
368 $charset = CHARSET; // get rid of constant. pref is dynamic and language specific
369 if (in_array($GLOBALS['LANG'], array('zh')))
371 if (strstr($GLOBALS['LANG'],'.utf-8'))
373 elseif (strstr($GLOBALS['LANG'],'.euc-jp'))
375 elseif (strstr($GLOBALS['LANG'], 'ja'))
378 if (strtolower($charset) == 'utf-8') { // thanks to John McPherson
379 // until posix class names/pcre work with utf-8
380 if (preg_match('/[[:upper:]]/', '\xc4\x80'))
382 // utf-8 non-ascii chars: most common (eg western) latin chars are 0xc380-0xc3bf
383 // we currently ignore other less common non-ascii characters
384 // (eg central/east european) latin chars are 0xc432-0xcdbf and 0xc580-0xc5be
385 // and indian/cyrillic/asian languages
387 // this replaces [[:lower:]] with utf-8 match (Latin only)
388 $regexp = preg_replace('/\[\[\:lower\:\]\]/','(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])',
390 // this replaces [[:upper:]] with utf-8 match (Latin only)
391 $regexp = preg_replace('/\[\[\:upper\:\]\]/','(?:[A-Z]|\xc3[\x80-\x9e]|\xc4[\x80\x82\x84\x86])',
393 } elseif (preg_match('/[[:upper:]]/', 'Ä')) {
394 // First check to see if our PCRE lib supports POSIX character
395 // classes. If it does, there's nothing to do.
398 static $classes = array(
399 'alnum' => "0-9A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
400 'alpha' => "A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
401 'upper' => "A-Z\xc0-\xd6\xd8-\xde",
402 'lower' => "a-z\xdf-\xf6\xf8-\xff"
404 $keys = join('|', array_keys($classes));
405 return preg_replace("/\[:($keys):]/e", '$classes["\1"]', $regexp);
408 function deduce_script_name() {
409 $s = &$GLOBALS['HTTP_SERVER_VARS'];
410 $script = @$s['SCRIPT_NAME'];
411 if (empty($script) or $script[0] != '/') {
412 // Some places (e.g. Lycos) only supply a relative name in
413 // SCRIPT_NAME, but give what we really want in SCRIPT_URL.
414 if (!empty($s['SCRIPT_URL']))
415 $script = $s['SCRIPT_URL'];
420 function IsProbablyRedirectToIndex () {
421 // This might be a redirect to the DirectoryIndex,
422 // e.g. REQUEST_URI = /dir/?some_action got redirected
423 // to SCRIPT_NAME = /dir/index.php
425 // In this case, the proper virtual path is still
426 // $SCRIPT_NAME, since pages appear at
427 // e.g. /dir/index.php/HomePage.
429 $requri = preg_replace('/\?.*$/','',$GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']);
430 $requri = preg_quote($requri, '%');
431 return preg_match("%^${requri}[^/]*$%", $GLOBALS['HTTP_SERVER_VARS']['SCRIPT_NAME']);
435 if (!function_exists('array_key_exists')) { // lib/IniConfig.php, sqlite, adodb, ...
436 function array_key_exists($item, $array) {
437 return isset($array[$item]);
442 if (!function_exists('is_scalar')) { // lib/stdlib.php:wikihash()
443 function is_scalar($x) {
444 return is_numeric($x) or is_string($x) or is_float($x) or is_bool($x);
448 // => php-4.2.0. pear wants to break old php's! DB uses it now.
449 if (!function_exists('is_a')) {
450 function is_a($item,$class) {
451 return isa($item,$class);
456 // by bradhuizenga at softhome dot net from the php docs
457 if (!function_exists('str_ireplace')) {
458 function str_ireplace($find, $replace, $string) {
459 if (!is_array($find)) $find = array($find);
460 if (!is_array($replace)) {
461 if (!is_array($find))
462 $replace = array($replace);
464 // this will duplicate the string into an array the size of $find
468 for ($i = 0; $i < $c; $i++) {
469 $replace[$i] = $rString;
473 foreach ($find as $fKey => $fItem) {
474 $between = explode(strtolower($fItem),strtolower($string));
476 foreach ($between as $bKey => $bItem) {
477 $between[$bKey] = substr($string,$pos,strlen($bItem));
478 $pos += strlen($bItem) + strlen($fItem);
480 $string = implode($replace[$fKey], $between);
487 * safe php4 definition for clone.
488 * php5 copies objects by reference, but we need to clone "deep copy" in some places.
490 * We need to eval it as workaround for the php5 parser.
491 * See http://www.acko.net/node/54
493 if (!check_php_version(5)) {
495 function clone($object) {
502 * array_diff_assoc() returns an array containing all the values from array1 that are not
503 * present in any of the other arguments. Note that the keys are used in the comparison
504 * unlike array_diff(). In core since php-4.3.0
505 * Our fallback here supports only hashes and two args.
506 * $array1 = array("a" => "green", "b" => "brown", "c" => "blue");
507 * $array2 = array("a" => "green", "y" => "yellow", "r" => "red");
508 * => b => brown, c => blue
510 if (!function_exists('array_diff_assoc')) {
511 function array_diff_assoc($a1, $a2) {
513 foreach ($a1 as $k => $v) {
514 if (!isset($a2[$k]) or !$a2[$k])
521 function safe_wordwrap($str, $width=80, $break="\n", $cut=false) {
522 return wordwrap($str, $width, $break, $cut);
525 function getUploadFilePath() {
527 if (defined('UPLOAD_FILE_PATH')) {
528 // Force creation of the returned directory if it does not exist.
529 if (!file_exists(UPLOAD_FILE_PATH)) {
530 mkdir(UPLOAD_FILE_PATH, 0775);
532 if (string_ends_with(UPLOAD_FILE_PATH, "/")
533 or string_ends_with(UPLOAD_FILE_PATH, "\\")) {
534 return UPLOAD_FILE_PATH;
536 return UPLOAD_FILE_PATH."/";
539 return defined('PHPWIKI_DIR')
540 ? PHPWIKI_DIR . "/uploads/"
541 : realpath(dirname(__FILE__) . "/../uploads/");
543 function getUploadDataPath() {
544 if (defined('UPLOAD_DATA_PATH')) {
545 return string_ends_with(UPLOAD_DATA_PATH, "/")
546 ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/";
548 return SERVER_URL . (string_ends_with(DATA_PATH, "/") ? '' : "/")
549 . DATA_PATH . '/uploads/';
557 // c-hanging-comment-ender-p: nil
558 // indent-tabs-mode: nil