]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/config.php
Let's assume PHP >= 4.2
[SourceForge/phpwiki.git] / lib / config.php
1 <?php
2 // rcs_id('$Id$');
3 /*
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()
7  */
8
9 if (!defined("LC_ALL")) {
10     define("LC_ALL",   0);
11     define("LC_CTYPE", 2);
12 }
13 // debug flags:
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 
25
26 function isCGI() {
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']));
30 }
31
32 /*
33 // copy some $_ENV vars to $_SERVER for CGI compatibility. php does it automatically since when?
34 if (isCGI()) {
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];
37     }
38 }
39 */
40
41 // essential internal stuff
42 if (!check_php_version(6))
43     set_magic_quotes_runtime(0);
44
45 /**
46  * Browser Detection Functions
47  *
48  * Current Issues:
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
54  * @author: ReiniUrban
55  */
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;
66 }
67 function browserDetect($match) {
68     return (strpos(strtolower(browserAgent()), strtolower($match)) !== false);
69 }
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);
79     else
80         return (float)substr($agent, 8);
81 }
82 function isBrowserIE() {
83     return (browserDetect('Mozilla/') and 
84             browserDetect('MSIE'));
85 }
86 // problem with transparent PNG's
87 function isBrowserIE55() {
88     return (isBrowserIE() and 
89             browserVersion() > 5.1 and browserVersion() < 6.0);
90 }
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; 
97     else return $agent;
98 }
99 // NS3 or less
100 function isBrowserNS3() {
101     return (isBrowserNetscape() and browserVersion() < 4.0);
102 }
103 // NS4 or less
104 function isBrowserNS4() {
105     return (isBrowserNetscape() and browserVersion() < 5.0);
106 }
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/');
112 }
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; 
119     return $found;
120 }
121 function isBrowserOpera($version = false) {
122     if ($version) return browserDetect('Opera/') and browserVersion() >= $version; 
123     return browserDetect('Opera/');
124 }
125
126
127 /**
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"
131  *   => "de"
132  * We should really check additionally if the i18n HomePage version is defined.
133  * So must defer this to the request loop.
134  */
135 function guessing_lang ($languages=false) {
136     if (!$languages) {
137         // make this faster
138         $languages = array("en","de","es","fr","it","ja","zh","nl","sv");
139         // ignore possible "_<territory>" and codeset "ja.utf8"
140         /*
141         require_once("lib/WikiTheme.php");
142         $languages = listAvailableLanguages();
143         if (defined('DEFAULT_LANGUAGE') and in_array(DEFAULT_LANGUAGE, $languages))
144         {
145             // remove duplicates
146             if ($i = array_search(DEFAULT_LANGUAGE, $languages) !== false) {
147                 array_splice($languages, $i, 1);
148             }
149             array_unshift($languages, DEFAULT_LANGUAGE);
150             foreach ($languages as $lang) {
151                 $arr = FileFinder::locale_versions($lang);
152                 $languages = array_merge($languages, $arr);
153             }
154         }
155         */
156     }
157
158     $accept = false; 
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'];
163
164     if ($accept) {
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;
172             } else {
173                 // Has a Q rating        
174                 $q = explode(";",$list[$i]) ;
175                 $loc = $q[0] ;
176                 $q = explode("=",$q[1]) ;
177                 $lang_list[$loc] = $q[1]*100 ;
178             }
179         }
180
181         // sort by q desc
182         arsort($lang_list);
183
184         // compare with languages, ignoring sublang and charset
185         foreach ($lang_list as $lang => $q) {
186             if (in_array($lang, $languages))
187                 return $lang;
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))
194                         return $lang_short;
195                 }
196             }
197             if ($pos = strchr($lang, "-") and in_array(substr($lang, 0, $pos), $languages))
198                 return substr($lang, 0, $pos);
199         }
200     }
201     return $languages[0];
202 }
203
204 /**
205  * Smart setlocale().
206  *
207  * This is a version of the builtin setlocale() which is
208  * smart enough to try some alternatives...
209  *
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.
214  * @see setlocale
215  * [56ms]
216  */
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', 
221                                'german', 'ge'),
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'),
230                  );
231     if (!$locale or $locale=='C') { 
232         // do the reverse: return the detected locale collapsed to our LANG
233         $locale = setlocale($category, '');
234         if ($locale) {
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;
241                         return $try;
242                     }
243                 }
244             }
245         }
246     }
247     if (strlen($locale) == 2)
248         $lang = $locale;
249     else 
250         list ($lang) = split('_', $locale);
251     if (!isset($alt[$lang]))
252         return false;
253         
254     foreach ($alt[$lang] as $try) {
255         if ($res = setlocale($category, $try))
256             return $res;
257         // Try with charset appended...
258         $try = $try . '.' . $GLOBALS['charset'];
259         if ($res = setlocale($category, $try))
260             return $res;
261         foreach (array(".", '@', '_') as $sep) {
262             if ($i = strpos($try, $sep)) {
263                 $try = substr($try, 0, $i);
264                 if (($res = setlocale($category, $try)))
265                     return $res;
266             }
267         }
268     }
269     return false;
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.
275 }
276
277 // [99ms]
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;
288     }
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.
293         global $locale;
294         $locale = array();
295         // do reinit to purge PHP's static cache [43ms]
296         if ( ($lcfile = FindLocalizedFile("LC_MESSAGES/phpwiki.php", 'missing_ok', 'reinit')) ) {
297             include($lcfile);
298         }
299     } else {
300         // If PHP is in safe mode, this is not allowed,
301         // so hide errors...
302         @putenv("LC_ALL=$setlocale");
303         @putenv("LANG=$loc");
304         @putenv("LANGUAGE=$loc");
305     }
306
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().
310     //
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.
314     //
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
318     // in the libc...)
319     //
320     // We don't currently use the locale setting for anything else, so for
321     // now, just set the locale to US English.
322     //
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']);
327     } else {
328         $x = setlocale(LC_CTYPE, $setlocale);
329     }
330
331     return $loc;
332 }
333
334 /** string pcre_fix_posix_classes (string $regexp)
335 *
336 * Older version (pre 3.x?) of the PCRE library do not support
337 * POSIX named character classes (e.g. [[:alnum:]]).
338 *
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.
341 *
342 * All instances of strings like '[:<class>:]' are replaced by the equivalent
343 * enumerated character class.
344 *
345 * Implementation Notes:
346 *
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.)
352 *
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:].)
357 *
358 * So for now, this will do.  --Jeff <dairiki@dairiki.org> 14 Mar, 2001
359 */
360 function pcre_fix_posix_classes ($regexp) {
361     global $charset;
362
363     if (defined('GFORGE') and GFORGE) {
364         return $regexp;
365     }
366
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')))
370         $charset = 'utf-8';
371     if (strstr($GLOBALS['LANG'],'.utf-8'))
372         $charset = 'utf-8';
373     elseif (strstr($GLOBALS['LANG'],'.euc-jp'))
374         $charset = 'euc-jp';
375     elseif (strstr($GLOBALS['LANG'], 'ja'))
376         $charset = 'euc-jp';
377
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'))
381             return $regexp;    
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
386         
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])',
389                                $regexp);
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])',
392                                $regexp);
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.
396         return $regexp;
397     }
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"
403                             );
404     $keys = join('|', array_keys($classes));
405     return preg_replace("/\[:($keys):]/e", '$classes["\1"]', $regexp);
406 }
407
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'];
416     }
417     return $script;
418 }
419
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
424
425     // In this case, the proper virtual path is still
426     // $SCRIPT_NAME, since pages appear at
427     // e.g. /dir/index.php/HomePage.
428
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']);
432 }
433
434 // >= php-4.1.0
435 if (!function_exists('array_key_exists')) { // lib/IniConfig.php, sqlite, adodb, ...
436     function array_key_exists($item, $array) {
437         return isset($array[$item]);
438     }
439 }
440
441 // => php-4.0.5
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); 
445     }
446 }
447
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); 
452     }
453 }
454
455 // needed < php5
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);
463           else {
464               // this will duplicate the string into an array the size of $find
465               $c = count($find);
466               $rString = $replace;
467               unset($replace);
468               for ($i = 0; $i < $c; $i++) {
469                   $replace[$i] = $rString;
470               }
471           }
472       }
473       foreach ($find as $fKey => $fItem) {
474           $between = explode(strtolower($fItem),strtolower($string));
475           $pos = 0;
476           foreach ($between as $bKey => $bItem) {
477               $between[$bKey] = substr($string,$pos,strlen($bItem));
478               $pos += strlen($bItem) + strlen($fItem);
479           }
480           $string = implode($replace[$fKey], $between);
481       }
482       return($string);
483   }
484 }
485
486 /**
487  * safe php4 definition for clone.
488  * php5 copies objects by reference, but we need to clone "deep copy" in some places.
489  * (BlockParser)
490  * We need to eval it as workaround for the php5 parser.
491  * See http://www.acko.net/node/54
492  */
493 if (!check_php_version(5)) {
494     eval('
495     function clone($object) {
496       return $object;
497     }
498     ');
499 }
500
501 /**
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
509  */
510 if (!function_exists('array_diff_assoc')) {
511     function array_diff_assoc($a1, $a2) {
512         $result = array();
513         foreach ($a1 as $k => $v) {
514             if (!isset($a2[$k]) or !$a2[$k])
515                 $result[$k] = $v;       
516         }
517         return $result;
518     }
519 }
520
521 function safe_wordwrap($str, $width=80, $break="\n", $cut=false) {
522     return wordwrap($str, $width, $break, $cut);
523 }
524
525 function getUploadFilePath() {
526
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);
531         }
532         if (string_ends_with(UPLOAD_FILE_PATH, "/") 
533             or string_ends_with(UPLOAD_FILE_PATH, "\\")) {
534             return UPLOAD_FILE_PATH;
535         } else {
536             return UPLOAD_FILE_PATH."/";
537         }
538     }
539     return defined('PHPWIKI_DIR') 
540         ? PHPWIKI_DIR . "/uploads/" 
541         : realpath(dirname(__FILE__) . "/../uploads/");
542 }
543 function getUploadDataPath() {
544     if (defined('UPLOAD_DATA_PATH')) {
545         return string_ends_with(UPLOAD_DATA_PATH, "/") 
546             ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/";
547     }
548     return SERVER_URL . (string_ends_with(DATA_PATH, "/") ? '' : "/") 
549          . DATA_PATH . '/uploads/';
550 }
551
552 // For emacs users
553 // Local Variables:
554 // mode: php
555 // tab-width: 8
556 // c-basic-offset: 4
557 // c-hanging-comment-ender-p: nil
558 // indent-tabs-mode: nil
559 // End:
560 ?>