]> 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 // must omit display alternate stylesheets: konqueror 3.1.4
100 // http://sourceforge.net/tracker/index.php?func=detail&aid=945154&group_id=6121&atid=106121
101 function isBrowserKonqueror($version = false) {
102     if ($version) return browserDetect('Konqueror/') and browserVersion() >= $version; 
103     return browserDetect('Konqueror/');
104 }
105 // MacOSX Safari has certain limitations. Need detection and patches.
106 // * no <object>, only <embed>
107 function isBrowserSafari($version = false) {
108     $found = browserDetect('Spoofer/');
109     $found = browserDetect('AppleWebKit/') or $found;
110     if ($version) return $found and browserVersion() >= $version; 
111     return $found;
112 }
113 function isBrowserOpera($version = false) {
114     if ($version) return browserDetect('Opera/') and browserVersion() >= $version; 
115     return browserDetect('Opera/');
116 }
117
118
119 /**
120  * If $LANG is undefined:
121  * Smart client language detection, based on our supported languages
122  * HTTP_ACCEPT_LANGUAGE="de-at,en;q=0.5"
123  *   => "de"
124  * We should really check additionally if the i18n HomePage version is defined.
125  * So must defer this to the request loop.
126  */
127 function guessing_lang ($languages=false) {
128     if (!$languages) {
129         // make this faster
130         $languages = array("en","de","es","fr","it","ja","zh","nl","sv");
131         // ignore possible "_<territory>" and codeset "ja.utf8"
132         /*
133         require_once("lib/WikiTheme.php");
134         $languages = listAvailableLanguages();
135         if (defined('DEFAULT_LANGUAGE') and in_array(DEFAULT_LANGUAGE, $languages))
136         {
137             // remove duplicates
138             if ($i = array_search(DEFAULT_LANGUAGE, $languages) !== false) {
139                 array_splice($languages, $i, 1);
140             }
141             array_unshift($languages, DEFAULT_LANGUAGE);
142             foreach ($languages as $lang) {
143                 $arr = FileFinder::locale_versions($lang);
144                 $languages = array_merge($languages, $arr);
145             }
146         }
147         */
148     }
149
150     $accept = false; 
151     if (isset($GLOBALS['request'])) // in fixup-dynamic-config there's no request yet
152         $accept = $GLOBALS['request']->get('HTTP_ACCEPT_LANGUAGE');
153     elseif (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
154         $accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
155
156     if ($accept) {
157         $lang_list = array();
158         $list = explode(",", $accept);
159         for ($i=0; $i<count($list); $i++) {
160             $pos = strchr($list[$i], ";") ;
161             if ($pos === false) {
162                 // No Q it is only a locale...
163                 $lang_list[$list[$i]] = 100;
164             } else {
165                 // Has a Q rating        
166                 $q = explode(";",$list[$i]) ;
167                 $loc = $q[0] ;
168                 $q = explode("=",$q[1]) ;
169                 $lang_list[$loc] = $q[1]*100 ;
170             }
171         }
172
173         // sort by q desc
174         arsort($lang_list);
175
176         // compare with languages, ignoring sublang and charset
177         foreach ($lang_list as $lang => $q) {
178             if (in_array($lang, $languages))
179                 return $lang;
180             // de_DE.iso8859-1@euro => de_DE.iso8859-1, de_DE, de
181             // de-DE => de-DE, de
182             foreach (array('@', '.', '_') as $sep) {
183                 if ( ($tail = strchr($lang, $sep)) ) {
184                     $lang_short = substr($lang, 0, -strlen($tail));
185                     if (in_array($lang_short, $languages))
186                         return $lang_short;
187                 }
188             }
189             if ($pos = strchr($lang, "-") and in_array(substr($lang, 0, $pos), $languages))
190                 return substr($lang, 0, $pos);
191         }
192     }
193     return $languages[0];
194 }
195
196 /**
197  * Smart setlocale().
198  *
199  * This is a version of the builtin setlocale() which is
200  * smart enough to try some alternatives...
201  *
202  * @param mixed $category
203  * @param string $locale
204  * @return string The new locale, or <code>false</code> if unable
205  *  to set the requested locale.
206  * @see setlocale
207  * [56ms]
208  */
209 function guessing_setlocale ($category, $locale) {
210     $alt = array('en' => array('C', 'en_US', 'en_GB', 'en_AU', 'en_CA', 'english'),
211                  'de' => array('de_DE', 'de_DE', 'de_DE@euro', 
212                                'de_AT@euro', 'de_AT', 'German_Austria.1252', 'deutsch', 
213                                'german', 'ge'),
214                  'es' => array('es_ES', 'es_MX', 'es_AR', 'spanish'),
215                  'nl' => array('nl_NL', 'dutch'),
216                  'fr' => array('fr_FR', 'français', 'french'),
217                  'it' => array('it_IT'),
218                  'sv' => array('sv_SE'),
219                  'ja.utf-8'  => array('ja_JP','ja_JP.utf-8','japanese'),
220                  'ja.euc-jp' => array('ja_JP','ja_JP.eucJP','japanese.euc'),
221                  'zh' => array('zh_TW', 'zh_CN'),
222                  );
223     if (!$locale or $locale=='C') { 
224         // do the reverse: return the detected locale collapsed to our LANG
225         $locale = setlocale($category, '');
226         if ($locale) {
227             if (strstr($locale, '_')) list ($lang) = split('_', $locale);
228             else $lang = $locale;
229             if (strlen($lang) > 2) { 
230                 foreach ($alt as $try => $locs) {
231                     if (in_array($locale, $locs) or in_array($lang, $locs)) {
232                         //if (empty($GLOBALS['LANG'])) $GLOBALS['LANG'] = $try;
233                         return $try;
234                     }
235                 }
236             }
237         }
238     }
239     if (strlen($locale) == 2)
240         $lang = $locale;
241     else 
242         list ($lang) = split('_', $locale);
243     if (!isset($alt[$lang]))
244         return false;
245         
246     foreach ($alt[$lang] as $try) {
247         if ($res = setlocale($category, $try))
248             return $res;
249         // Try with charset appended...
250         $try = $try . '.' . $GLOBALS['charset'];
251         if ($res = setlocale($category, $try))
252             return $res;
253         foreach (array(".", '@', '_') as $sep) {
254             if ($i = strpos($try, $sep)) {
255                 $try = substr($try, 0, $i);
256                 if (($res = setlocale($category, $try)))
257                     return $res;
258             }
259         }
260     }
261     return false;
262     // A standard locale name is typically of  the  form
263     // language[_territory][.codeset][@modifier],  where  language is
264     // an ISO 639 language code, territory is an ISO 3166 country code,
265     // and codeset  is  a  character  set or encoding identifier like
266     // ISO-8859-1 or UTF-8.
267 }
268
269 // [99ms]
270 function update_locale($loc) {
271     if ($loc == 'C' or $loc == 'en') return;
272     // $LANG or DEFAULT_LANGUAGE is too less information, at least on unix for
273     // setlocale(), for bindtextdomain() to succeed.
274     $setlocale = guessing_setlocale(LC_ALL, $loc); // [56ms]
275     if (!$setlocale) { // system has no locale for this language, so gettext might fail
276         $setlocale = FileFinder::_get_lang();
277         list ($setlocale,) = split('_', $setlocale, 2);
278         $setlocale = guessing_setlocale(LC_ALL, $setlocale); // try again
279         if (!$setlocale) $setlocale = $loc;
280     }
281     // Try to put new locale into environment (so any
282     // programs we run will get the right locale.)
283     if (!function_exists('bindtextdomain'))  {
284         // Reinitialize translation array.
285         global $locale;
286         $locale = array();
287         // do reinit to purge PHP's static cache [43ms]
288         if ( ($lcfile = FindLocalizedFile("LC_MESSAGES/phpwiki.php", 'missing_ok', 'reinit')) ) {
289             include($lcfile);
290         }
291     } else {
292         // If PHP is in safe mode, this is not allowed,
293         // so hide errors...
294         @putenv("LC_ALL=$setlocale");
295         @putenv("LANG=$loc");
296         @putenv("LANGUAGE=$loc");
297     }
298
299     // To get the POSIX character classes in the PCRE's (e.g.
300     // [[:upper:]]) to match extended characters (e.g. GrüßGott), we have
301     // to set the locale, using setlocale().
302     //
303     // The problem is which locale to set?  We would like to recognize all
304     // upper-case characters in the iso-8859-1 character set as upper-case
305     // characters --- not just the ones which are in the current $LANG.
306     //
307     // As it turns out, at least on my system (Linux/glibc-2.2) as long as
308     // you setlocale() to anything but "C" it works fine.  (I'm not sure
309     // whether this is how it's supposed to be, or whether this is a bug
310     // in the libc...)
311     //
312     // We don't currently use the locale setting for anything else, so for
313     // now, just set the locale to US English.
314     //
315     // FIXME: Not all environments may support en_US?  We should probably
316     // have a list of locales to try.
317     if (setlocale(LC_CTYPE, 0) == 'C') {
318         $x = setlocale(LC_CTYPE, 'en_US.' . $GLOBALS['charset']);
319     } else {
320         $x = setlocale(LC_CTYPE, $setlocale);
321     }
322
323     return $loc;
324 }
325
326 /** string pcre_fix_posix_classes (string $regexp)
327 *
328 * Older version (pre 3.x?) of the PCRE library do not support
329 * POSIX named character classes (e.g. [[:alnum:]]).
330 *
331 * This is a helper function which can be used to convert a regexp
332 * which contains POSIX named character classes to one that doesn't.
333 *
334 * All instances of strings like '[:<class>:]' are replaced by the equivalent
335 * enumerated character class.
336 *
337 * Implementation Notes:
338 *
339 * Currently we use hard-coded values which are valid only for
340 * ISO-8859-1.  Also, currently on the classes [:alpha:], [:alnum:],
341 * [:upper:] and [:lower:] are implemented.  (The missing classes:
342 * [:blank:], [:cntrl:], [:digit:], [:graph:], [:print:], [:punct:],
343 * [:space:], and [:xdigit:] could easily be added if needed.)
344 *
345 * This is a hack.  I tried to generate these classes automatically
346 * using ereg(), but discovered that in my PHP, at least, ereg() is
347 * slightly broken w.r.t. POSIX character classes.  (It includes
348 * "\xaa" and "\xba" in [:alpha:].)
349 *
350 * So for now, this will do.  --Jeff <dairiki@dairiki.org> 14 Mar, 2001
351 */
352 function pcre_fix_posix_classes ($regexp) {
353     global $charset;
354
355     if (defined('GFORGE') and GFORGE) {
356         return $regexp;
357     }
358
359     if (!isset($charset))
360         $charset = CHARSET; // get rid of constant. pref is dynamic and language specific
361     if (in_array($GLOBALS['LANG'], array('zh')))
362         $charset = 'utf-8';
363     if (strstr($GLOBALS['LANG'],'.utf-8'))
364         $charset = 'utf-8';
365     elseif (strstr($GLOBALS['LANG'],'.euc-jp'))
366         $charset = 'euc-jp';
367     elseif (strstr($GLOBALS['LANG'], 'ja'))
368         $charset = 'euc-jp';
369
370     if (strtolower($charset) == 'utf-8') { // thanks to John McPherson
371         // until posix class names/pcre work with utf-8
372         if (preg_match('/[[:upper:]]/', '\xc4\x80'))
373             return $regexp;    
374         // utf-8 non-ascii chars: most common (eg western) latin chars are 0xc380-0xc3bf
375         // we currently ignore other less common non-ascii characters
376         // (eg central/east european) latin chars are 0xc432-0xcdbf and 0xc580-0xc5be
377         // and indian/cyrillic/asian languages
378         
379         // this replaces [[:lower:]] with utf-8 match (Latin only)
380         $regexp = preg_replace('/\[\[\:lower\:\]\]/','(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])',
381                                $regexp);
382         // this replaces [[:upper:]] with utf-8 match (Latin only)
383         $regexp = preg_replace('/\[\[\:upper\:\]\]/','(?:[A-Z]|\xc3[\x80-\x9e]|\xc4[\x80\x82\x84\x86])',
384                                $regexp);
385     } elseif (preg_match('/[[:upper:]]/', 'Ä')) {
386         // First check to see if our PCRE lib supports POSIX character
387         // classes.  If it does, there's nothing to do.
388         return $regexp;
389     }
390     static $classes = array(
391                             'alnum' => "0-9A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
392                             'alpha' => "A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\xff",
393                             'upper' => "A-Z\xc0-\xd6\xd8-\xde",
394                             'lower' => "a-z\xdf-\xf6\xf8-\xff"
395                             );
396     $keys = join('|', array_keys($classes));
397     return preg_replace("/\[:($keys):]/e", '$classes["\1"]', $regexp);
398 }
399
400 function deduce_script_name() {
401     $s = &$GLOBALS['HTTP_SERVER_VARS'];
402     $script = @$s['SCRIPT_NAME'];
403     if (empty($script) or $script[0] != '/') {
404         // Some places (e.g. Lycos) only supply a relative name in
405         // SCRIPT_NAME, but give what we really want in SCRIPT_URL.
406         if (!empty($s['SCRIPT_URL']))
407             $script = $s['SCRIPT_URL'];
408     }
409     return $script;
410 }
411
412 function IsProbablyRedirectToIndex () {
413     // This might be a redirect to the DirectoryIndex,
414     // e.g. REQUEST_URI = /dir/?some_action got redirected
415     // to SCRIPT_NAME = /dir/index.php
416
417     // In this case, the proper virtual path is still
418     // $SCRIPT_NAME, since pages appear at
419     // e.g. /dir/index.php/HomePage.
420
421     $requri = preg_replace('/\?.*$/','',$GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']);
422     $requri = preg_quote($requri, '%');
423     return preg_match("%^${requri}[^/]*$%", $GLOBALS['HTTP_SERVER_VARS']['SCRIPT_NAME']);
424 }
425
426 // needed < php5
427 // by bradhuizenga at softhome dot net from the php docs
428 if (!function_exists('str_ireplace')) {
429   function str_ireplace($find, $replace, $string) {
430       if (!is_array($find)) $find = array($find);
431       if (!is_array($replace)) {
432           if (!is_array($find)) 
433               $replace = array($replace);
434           else {
435               // this will duplicate the string into an array the size of $find
436               $c = count($find);
437               $rString = $replace;
438               unset($replace);
439               for ($i = 0; $i < $c; $i++) {
440                   $replace[$i] = $rString;
441               }
442           }
443       }
444       foreach ($find as $fKey => $fItem) {
445           $between = explode(strtolower($fItem),strtolower($string));
446           $pos = 0;
447           foreach ($between as $bKey => $bItem) {
448               $between[$bKey] = substr($string,$pos,strlen($bItem));
449               $pos += strlen($bItem) + strlen($fItem);
450           }
451           $string = implode($replace[$fKey], $between);
452       }
453       return($string);
454   }
455 }
456
457 /**
458  * safe php4 definition for clone.
459  * php5 copies objects by reference, but we need to clone "deep copy" in some places.
460  * (BlockParser)
461  * We need to eval it as workaround for the php5 parser.
462  * See http://www.acko.net/node/54
463  */
464 if (!check_php_version(5)) {
465     eval('
466     function clone($object) {
467       return $object;
468     }
469     ');
470 }
471
472 /**
473  * array_diff_assoc() returns an array containing all the values from array1 that are not
474  * present in any of the other arguments. Note that the keys are used in the comparison 
475  * unlike array_diff(). In core since php-4.3.0
476  * Our fallback here supports only hashes and two args.
477  * $array1 = array("a" => "green", "b" => "brown", "c" => "blue");
478  * $array2 = array("a" => "green", "y" => "yellow", "r" => "red");
479  * => b => brown, c => blue
480  */
481 if (!function_exists('array_diff_assoc')) {
482     function array_diff_assoc($a1, $a2) {
483         $result = array();
484         foreach ($a1 as $k => $v) {
485             if (!isset($a2[$k]) or !$a2[$k])
486                 $result[$k] = $v;       
487         }
488         return $result;
489     }
490 }
491
492 function getUploadFilePath() {
493
494     if (defined('UPLOAD_FILE_PATH')) {
495         // Force creation of the returned directory if it does not exist.
496         if (!file_exists(UPLOAD_FILE_PATH)) {
497             mkdir(UPLOAD_FILE_PATH, 0775);
498         }
499         if (string_ends_with(UPLOAD_FILE_PATH, "/") 
500             or string_ends_with(UPLOAD_FILE_PATH, "\\")) {
501             return UPLOAD_FILE_PATH;
502         } else {
503             return UPLOAD_FILE_PATH."/";
504         }
505     }
506     return defined('PHPWIKI_DIR') 
507         ? PHPWIKI_DIR . "/uploads/" 
508         : realpath(dirname(__FILE__) . "/../uploads/");
509 }
510 function getUploadDataPath() {
511     if (defined('UPLOAD_DATA_PATH')) {
512         return string_ends_with(UPLOAD_DATA_PATH, "/") 
513             ? UPLOAD_DATA_PATH : UPLOAD_DATA_PATH."/";
514     }
515     return SERVER_URL . (string_ends_with(DATA_PATH, "/") ? '' : "/") 
516          . DATA_PATH . '/uploads/';
517 }
518
519 // For emacs users
520 // Local Variables:
521 // mode: php
522 // tab-width: 8
523 // c-basic-offset: 4
524 // c-hanging-comment-ender-p: nil
525 // indent-tabs-mode: nil
526 // End:
527 ?>