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")) {
10 // Backward compatibility (for PHP < 4.0.5)
11 if (!check_php_version(4,0,5)) {
12 define("LC_ALL", "LC_ALL");
13 define("LC_CTYPE", "LC_CTYPE");
16 define("LC_CTYPE", 2);
20 define ('_DEBUG_VERBOSE', 1); // verbose msgs and add validator links on footer
21 define ('_DEBUG_PAGELINKS', 2); // list the extraced pagelinks at the top of each pages
22 define ('_DEBUG_PARSER', 4); // verbose parsing steps
23 define ('_DEBUG_TRACE', 8); // test php memory usage, prints php debug backtraces
24 define ('_DEBUG_INFO', 16);
25 define ('_DEBUG_APD', 32); // APD tracing/profiling
26 define ('_DEBUG_LOGIN', 64); // verbose login debug-msg (settings and reason for failure)
27 define ('_DEBUG_SQL', 128); // force check db, force optimize, print some debugging logs
28 define ('_DEBUG_REMOTE', 256); // remote debug into subrequests (xmlrpc, ajax, wikiwyg, ...)
29 // or test local SearchHighlight.
30 // internal links have persistent ?start_debug=1
33 return (substr(php_sapi_name(),0,3) == 'cgi' and
34 isset($GLOBALS['HTTP_ENV_VARS']['GATEWAY_INTERFACE']) and
35 @preg_match('/CGI/',$GLOBALS['HTTP_ENV_VARS']['GATEWAY_INTERFACE']));
39 // copy some $_ENV vars to $_SERVER for CGI compatibility. php does it automatically since when?
41 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) {
42 $GLOBALS['HTTP_SERVER_VARS'][$key] = &$GLOBALS['HTTP_ENV_VARS'][$key];
47 // essential internal stuff
48 if (!check_php_version(6))
49 set_magic_quotes_runtime(0);
52 * Browser Detection Functions
55 * NS/IE < 4.0 doesn't accept < ? xml version="1.0" ? >
56 * NS/IE < 4.0 cannot display PNG
57 * NS/IE < 4.0 cannot display all XHTML tags
58 * NS < 5.0 needs textarea wrap=virtual
59 * IE55 has problems with transparent PNG's
62 function browserAgent() {
63 static $HTTP_USER_AGENT = false;
64 if ($HTTP_USER_AGENT !== false) return $HTTP_USER_AGENT;
65 if (!$HTTP_USER_AGENT)
66 $HTTP_USER_AGENT = @$GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'];
67 if (!$HTTP_USER_AGENT) // CGI
68 $HTTP_USER_AGENT = @$GLOBALS['HTTP_ENV_VARS']['HTTP_USER_AGENT'];
69 if (!$HTTP_USER_AGENT) // local CGI testing
70 $HTTP_USER_AGENT = 'none';
71 return $HTTP_USER_AGENT;
73 function browserDetect($match) {
74 return (strpos(strtolower(browserAgent()), strtolower($match)) !== false);
76 // returns a similar number for Netscape/Mozilla (gecko=5.0)/IE/Opera features.
77 function browserVersion() {
78 $agent = browserAgent();
79 if (strstr($agent, "Mozilla/4.0 (compatible; MSIE"))
80 return (float)substr($agent, 30);
81 elseif (strstr($agent, "Mozilla/5.0 (compatible; Konqueror/"))
82 return (float)substr($agent, 36);
83 elseif (strstr($agent, "AppleWebKit/"))
84 return (float)substr($agent, strpos($agent, "AppleWebKit/") + 12);
86 return (float)substr($agent, 8);
88 function isBrowserIE() {
89 return (browserDetect('Mozilla/') and
90 browserDetect('MSIE'));
92 // problem with transparent PNG's
93 function isBrowserIE55() {
94 return (isBrowserIE() and
95 browserVersion() > 5.1 and browserVersion() < 6.0);
97 // old Netscape prior to Mozilla
98 function isBrowserNetscape($version = false) {
99 $agent = (browserDetect('Mozilla/') and
100 ! browserDetect('Gecko/') and
101 ! browserDetect('MSIE'));
102 if ($version) return $agent and browserVersion() >= $version;
106 function isBrowserNS3() {
107 return (isBrowserNetscape() and browserVersion() < 4.0);
110 function isBrowserNS4() {
111 return (isBrowserNetscape() and browserVersion() < 5.0);
113 // must omit display alternate stylesheets: konqueror 3.1.4
114 // http://sourceforge.net/tracker/index.php?func=detail&aid=945154&group_id=6121&atid=106121
115 function isBrowserKonqueror($version = false) {
116 if ($version) return browserDetect('Konqueror/') and browserVersion() >= $version;
117 return browserDetect('Konqueror/');
119 // MacOSX Safari has certain limitations. Need detection and patches.
120 // * no <object>, only <embed>
121 function isBrowserSafari($version = false) {
122 $found = browserDetect('Spoofer/');
123 $found = browserDetect('AppleWebKit/') or $found;
124 if ($version) return $found and browserVersion() >= $version;
127 function isBrowserOpera($version = false) {
128 if ($version) return browserDetect('Opera/') and browserVersion() >= $version;
129 return browserDetect('Opera/');
134 * If $LANG is undefined:
135 * Smart client language detection, based on our supported languages
136 * HTTP_ACCEPT_LANGUAGE="de-at,en;q=0.5"
138 * We should really check additionally if the i18n HomePage version is defined.
139 * So must defer this to the request loop.
141 function guessing_lang ($languages=false) {
144 $languages = array("en","de","es","fr","it","ja","zh","nl","sv");
145 // ignore possible "_<territory>" and codeset "ja.utf8"
147 require_once("lib/WikiTheme.php");
148 $languages = listAvailableLanguages();
149 if (defined('DEFAULT_LANGUAGE') and in_array(DEFAULT_LANGUAGE, $languages))
152 if ($i = array_search(DEFAULT_LANGUAGE, $languages) !== false) {
153 array_splice($languages, $i, 1);
155 array_unshift($languages, DEFAULT_LANGUAGE);
156 foreach ($languages as $lang) {
157 $arr = FileFinder::locale_versions($lang);
158 $languages = array_merge($languages, $arr);
165 if (isset($GLOBALS['request'])) // in fixup-dynamic-config there's no request yet
166 $accept = $GLOBALS['request']->get('HTTP_ACCEPT_LANGUAGE');
167 elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
168 $accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
171 $lang_list = array();
172 $list = explode(",", $accept);
173 for ($i=0; $i<count($list); $i++) {
174 $pos = strchr($list[$i], ";") ;
175 if ($pos === false) {
176 // No Q it is only a locale...
177 $lang_list[$list[$i]] = 100;
180 $q = explode(";",$list[$i]) ;
182 $q = explode("=",$q[1]) ;
183 $lang_list[$loc] = $q[1]*100 ;
190 // compare with languages, ignoring sublang and charset
191 foreach ($lang_list as $lang => $q) {
192 if (in_array($lang, $languages))
194 // de_DE.iso8859-1@euro => de_DE.iso8859-1, de_DE, de
195 // de-DE => de-DE, de
196 foreach (array('@', '.', '_') as $sep) {
197 if ( ($tail = strchr($lang, $sep)) ) {
198 $lang_short = substr($lang, 0, -strlen($tail));
199 if (in_array($lang_short, $languages))
203 if ($pos = strchr($lang, "-") and in_array(substr($lang, 0, $pos), $languages))
204 return substr($lang, 0, $pos);
207 return $languages[0];
213 * This is a version of the builtin setlocale() which is
214 * smart enough to try some alternatives...
216 * @param mixed $category
217 * @param string $locale
218 * @return string The new locale, or <code>false</code> if unable
219 * to set the requested locale.
223 function guessing_setlocale ($category, $locale) {
224 $alt = array('en' => array('C', 'en_US', 'en_GB', 'en_AU', 'en_CA', 'english'),
225 'de' => array('de_DE', 'de_DE', 'de_DE@euro',
226 'de_AT@euro', 'de_AT', 'German_Austria.1252', 'deutsch',
228 'es' => array('es_ES', 'es_MX', 'es_AR', 'spanish'),
229 'nl' => array('nl_NL', 'dutch'),
230 'fr' => array('fr_FR', 'français', 'french'),
231 'it' => array('it_IT'),
232 'sv' => array('sv_SE'),
233 'ja.utf-8' => array('ja_JP','ja_JP.utf-8','japanese'),
234 'ja.euc-jp' => array('ja_JP','ja_JP.eucJP','japanese.euc'),
235 'zh' => array('zh_TW', 'zh_CN'),
237 if (!$locale or $locale=='C') {
238 // do the reverse: return the detected locale collapsed to our LANG
239 $locale = setlocale($category, '');
241 if (strstr($locale, '_')) list ($lang) = split('_', $locale);
242 else $lang = $locale;
243 if (strlen($lang) > 2) {
244 foreach ($alt as $try => $locs) {
245 if (in_array($locale, $locs) or in_array($lang, $locs)) {
246 //if (empty($GLOBALS['LANG'])) $GLOBALS['LANG'] = $try;
253 if (strlen($locale) == 2)
256 list ($lang) = split('_', $locale);
257 if (!isset($alt[$lang]))
260 foreach ($alt[$lang] as $try) {
261 if ($res = setlocale($category, $try))
263 // Try with charset appended...
264 $try = $try . '.' . $GLOBALS['charset'];
265 if ($res = setlocale($category, $try))
267 foreach (array(".", '@', '_') as $sep) {
268 if ($i = strpos($try, $sep)) {
269 $try = substr($try, 0, $i);
270 if (($res = setlocale($category, $try)))
276 // A standard locale name is typically of the form
277 // language[_territory][.codeset][@modifier], where language is
278 // an ISO 639 language code, territory is an ISO 3166 country code,
279 // and codeset is a character set or encoding identifier like
280 // ISO-8859-1 or UTF-8.
284 function update_locale($loc) {
285 if ($loc == 'C' or $loc == 'en') return;
286 // $LANG or DEFAULT_LANGUAGE is too less information, at least on unix for
287 // setlocale(), for bindtextdomain() to succeed.
288 $setlocale = guessing_setlocale(LC_ALL, $loc); // [56ms]
289 if (!$setlocale) { // system has no locale for this language, so gettext might fail
290 $setlocale = FileFinder::_get_lang();
291 list ($setlocale,) = split('_', $setlocale, 2);
292 $setlocale = guessing_setlocale(LC_ALL, $setlocale); // try again
293 if (!$setlocale) $setlocale = $loc;
295 // Try to put new locale into environment (so any
296 // programs we run will get the right locale.)
297 if (!function_exists('bindtextdomain')) {
298 // Reinitialize translation array.
301 // do reinit to purge PHP's static cache [43ms]
302 if ( ($lcfile = FindLocalizedFile("LC_MESSAGES/phpwiki.php", 'missing_ok', 'reinit')) ) {
306 // If PHP is in safe mode, this is not allowed,
308 @putenv("LC_ALL=$setlocale");
309 @putenv("LANG=$loc");
310 @putenv("LANGUAGE=$loc");
313 // To get the POSIX character classes in the PCRE's (e.g.
314 // [[:upper:]]) to match extended characters (e.g. GrüßGott), we have
315 // to set the locale, using setlocale().
317 // The problem is which locale to set? We would like to recognize all
318 // upper-case characters in the iso-8859-1 character set as upper-case
319 // characters --- not just the ones which are in the current $LANG.
321 // As it turns out, at least on my system (Linux/glibc-2.2) as long as
322 // you setlocale() to anything but "C" it works fine. (I'm not sure
323 // whether this is how it's supposed to be, or whether this is a bug
326 // We don't currently use the locale setting for anything else, so for
327 // now, just set the locale to US English.
329 // FIXME: Not all environments may support en_US? We should probably
330 // have a list of locales to try.
331 if (setlocale(LC_CTYPE, 0) == 'C') {
332 $x = setlocale(LC_CTYPE, 'en_US.' . $GLOBALS['charset']);
334 $x = setlocale(LC_CTYPE, $setlocale);
340 /** string pcre_fix_posix_classes (string $regexp)
342 * Older version (pre 3.x?) of the PCRE library do not support
343 * POSIX named character classes (e.g. [[:alnum:]]).
345 * This is a helper function which can be used to convert a regexp
346 * which contains POSIX named character classes to one that doesn't.
348 * All instances of strings like '[:<class>:]' are replaced by the equivalent
349 * enumerated character class.
351 * Implementation Notes:
353 * Currently we use hard-coded values which are valid only for
354 * ISO-8859-1. Also, currently on the classes [:alpha:], [:alnum:],
355 * [:upper:] and [:lower:] are implemented. (The missing classes:
356 * [:blank:], [:cntrl:], [:digit:], [:graph:], [:print:], [:punct:],
357 * [:space:], and [:xdigit:] could easily be added if needed.)
359 * This is a hack. I tried to generate these classes automatically
360 * using ereg(), but discovered that in my PHP, at least, ereg() is
361 * slightly broken w.r.t. POSIX character classes. (It includes
362 * "\xaa" and "\xba" in [:alpha:].)
364 * So for now, this will do. --Jeff <dairiki@dairiki.org> 14 Mar, 2001
366 function pcre_fix_posix_classes ($regexp) {
369 if (defined('GFORGE') and GFORGE) {
373 if (!isset($charset))
374 $charset = CHARSET; // get rid of constant. pref is dynamic and language specific
375 if (in_array($GLOBALS['LANG'], array('zh')))
377 if (strstr($GLOBALS['LANG'],'.utf-8'))
379 elseif (strstr($GLOBALS['LANG'],'.euc-jp'))
381 elseif (strstr($GLOBALS['LANG'], 'ja'))
384 if (strtolower($charset) == 'utf-8') { // thanks to John McPherson
385 // until posix class names/pcre work with utf-8
386 if (preg_match('/[[:upper:]]/', '\xc4\x80'))
388 // utf-8 non-ascii chars: most common (eg western) latin chars are 0xc380-0xc3bf
389 // we currently ignore other less common non-ascii characters
390 // (eg central/east european) latin chars are 0xc432-0xcdbf and 0xc580-0xc5be
391 // and indian/cyrillic/asian languages
393 // this replaces [[:lower:]] with utf-8 match (Latin only)
394 $regexp = preg_replace('/\[\[\:lower\:\]\]/','(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])',
396 // this replaces [[:upper:]] with utf-8 match (Latin only)
397 $regexp = preg_replace('/\[\[\:upper\:\]\]/','(?:[A-Z]|\xc3[\x80-\x9e]|\xc4[\x80\x82\x84\x86])',
399 } elseif (preg_match('/[[:upper:]]/', 'Ä')) {
400 // First check to see if our PCRE lib supports POSIX character
401 // classes. If it does, there's nothing to do.
404 static $classes = array(
405 'alnum' => "0-9A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
406 'alpha' => "A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
407 'upper' => "A-Z\xc0-\xd6\xd8-\xde",
408 'lower' => "a-z\xdf-\xf6\xf8-\xff"
410 $keys = join('|', array_keys($classes));
411 return preg_replace("/\[:($keys):]/e", '$classes["\1"]', $regexp);
414 function deduce_script_name() {
415 $s = &$GLOBALS['HTTP_SERVER_VARS'];
416 $script = @$s['SCRIPT_NAME'];
417 if (empty($script) or $script[0] != '/') {
418 // Some places (e.g. Lycos) only supply a relative name in
419 // SCRIPT_NAME, but give what we really want in SCRIPT_URL.
420 if (!empty($s['SCRIPT_URL']))
421 $script = $s['SCRIPT_URL'];
426 function IsProbablyRedirectToIndex () {
427 // This might be a redirect to the DirectoryIndex,
428 // e.g. REQUEST_URI = /dir/?some_action got redirected
429 // to SCRIPT_NAME = /dir/index.php
431 // In this case, the proper virtual path is still
432 // $SCRIPT_NAME, since pages appear at
433 // e.g. /dir/index.php/HomePage.
435 $requri = preg_replace('/\?.*$/','',$GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']);
436 $requri = preg_quote($requri, '%');
437 return preg_match("%^${requri}[^/]*$%", $GLOBALS['HTTP_SERVER_VARS']['SCRIPT_NAME']);
441 if (!function_exists('array_key_exists')) { // lib/IniConfig.php, sqlite, adodb, ...
442 function array_key_exists($item, $array) {
443 return isset($array[$item]);
448 if (!function_exists('is_scalar')) { // lib/stdlib.php:wikihash()
449 function is_scalar($x) {
450 return is_numeric($x) or is_string($x) or is_float($x) or is_bool($x);
454 // => php-4.2.0. pear wants to break old php's! DB uses it now.
455 if (!function_exists('is_a')) {
456 function is_a($item,$class) {
457 return isa($item,$class);
462 // by bradhuizenga at softhome dot net from the php docs
463 if (!function_exists('str_ireplace')) {
464 function str_ireplace($find, $replace, $string) {
465 if (!is_array($find)) $find = array($find);
466 if (!is_array($replace)) {
467 if (!is_array($find))
468 $replace = array($replace);
470 // this will duplicate the string into an array the size of $find
474 for ($i = 0; $i < $c; $i++) {
475 $replace[$i] = $rString;
479 foreach ($find as $fKey => $fItem) {
480 $between = explode(strtolower($fItem),strtolower($string));
482 foreach ($between as $bKey => $bItem) {
483 $between[$bKey] = substr($string,$pos,strlen($bItem));
484 $pos += strlen($bItem) + strlen($fItem);
486 $string = implode($replace[$fKey], $between);
493 * safe php4 definition for clone.
494 * php5 copies objects by reference, but we need to clone "deep copy" in some places.
496 * We need to eval it as workaround for the php5 parser.
497 * See http://www.acko.net/node/54
499 if (!check_php_version(5)) {
501 function clone($object) {
508 * array_diff_assoc() returns an array containing all the values from array1 that are not
509 * present in any of the other arguments. Note that the keys are used in the comparison
510 * unlike array_diff(). In core since php-4.3.0
511 * Our fallback here supports only hashes and two args.
512 * $array1 = array("a" => "green", "b" => "brown", "c" => "blue");
513 * $array2 = array("a" => "green", "y" => "yellow", "r" => "red");
514 * => b => brown, c => blue
516 if (!function_exists('array_diff_assoc')) {
517 function array_diff_assoc($a1, $a2) {
519 foreach ($a1 as $k => $v) {
520 if (!isset($a2[$k]) or !$a2[$k])
528 * wordwrap() might crash between 4.1.2 and php-4.3.0RC2, fixed in 4.3.0
529 * See http://bugs.php.net/bug.php?id=20927 and
530 * http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-1396
531 * Improved version of wordwrap2() in the comments at http://www.php.net/wordwrap
533 function safe_wordwrap($str, $width=80, $break="\n", $cut=false) {
534 if (check_php_version(4,3))
535 return wordwrap($str, $width, $break, $cut);
536 elseif (!check_php_version(4,1,2))
537 return wordwrap($str, $width, $break, $cut);
540 $tag = 0; $result = ''; $wordlen = 0;
541 for ($i = 0; $i < $len; $i++) {
543 // don't break inside xml tags
546 } elseif ($chr == '>') {
549 if (!function_exists('ctype_space')) {
550 if (preg_match('/^\s$/', $chr))
555 elseif (ctype_space($chr)) {
561 if ((!$tag) && ($wordlen) && (!($wordlen % $width))) {
568 if (isset($str) && isset($width)) {
569 $ex = explode(" ", $str); // wrong: must use preg_split \s+
571 for ($i=0; $i<count($ex); $i++) {
572 // $word_array = preg_split('//', $ex[$i], -1, PREG_SPLIT_NO_EMPTY);
573 // delete #&& !is_numeric($ex[$i])# if you want force it anyway
574 if (strlen($ex[$i]) > $width && !is_numeric($ex[$i])) {
577 for($b=0; $b < (ceil(strlen($ex[$i]) / $width)); $b++) {
578 $rp[$i] .= substr($ex[$i], $where, $width).$break;
585 return implode(" ",$rp);
592 function getUploadFilePath() {
594 if (defined('UPLOAD_FILE_PATH')) {
595 // Force creation of the returned directory if it does not exist.
596 if (!file_exists(UPLOAD_FILE_PATH)) {
597 mkdir(UPLOAD_FILE_PATH, 0775);
599 if (string_ends_with(UPLOAD_FILE_PATH, "/")
600 or string_ends_with(UPLOAD_FILE_PATH, "\\")) {
601 return UPLOAD_FILE_PATH;
603 return UPLOAD_FILE_PATH."/";
606 return defined('PHPWIKI_DIR')
607 ? PHPWIKI_DIR . "/uploads/"
608 : realpath(dirname(__FILE__) . "/../uploads/");
610 function getUploadDataPath() {
611 if (defined('UPLOAD_DATA_PATH')) {
612 return string_ends_with(UPLOAD_DATA_PATH, "/")
613 ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/";
615 return SERVER_URL . (string_ends_with(DATA_PATH, "/") ? '' : "/")
616 . DATA_PATH . '/uploads/';
624 // c-hanging-comment-ender-p: nil
625 // indent-tabs-mode: nil